Algorithm Search⌘K

Algorithmcore

Newton point inversion

Also called Newton foot point iteration.

Solves (S(u, v) - P) . S_u = 0 and (S(u, v) - P) . S_v = 0 by Newton steps from the best sample of a coarse grid, the method of Piegl and Tiller.

Time
O((n^2 + k) m) worst
Space
O(m) extra
Where
k = the number of Newton iterations; m = the number of control points of the patch; n = the number of grid intervals per parameter
Properties
deterministicnot exactiterative
Origin
Les Piegl, Wayne Tiller, 1997

Newton point inversion finds the parameters (u,v)(u, v) of the point of a parametric surface r(u,v)r(u, v) nearest to a given point pp, by Newton's method on the two first order equations (r−p)⋅ru=0(r - p) \cdot r_u = 0 and (r−p)⋅rv=0(r - p) \cdot r_v = 0. It starts from the best sample of a coarse grid of parameters and stops when the point is reached, when the vector r−pr - p is normal to the surface, or when the steps stop moving the point. Piegl and Tiller gave this form in The NURBS Book, and most CAD kernels use a variant of it. It converges quadratically near a nondegenerate foot point, but it returns the nearest point of the whole surface only when the start grid is fine enough, a condition the method cannot check.

In plain words

You want the spot on a curved sheet closest to a point. First, try a small grid of spots, for example eleven by eleven, and keep the closest one. That is a rough answer.

Then improve it. Near the rough answer, pretend the sheet is a simple bowl that matches the sheet in height, slope and bend. The bottom of that bowl is easy to compute. Jump there. Repeat. Each jump roughly doubles the number of correct digits, so a few jumps are enough.

Stop when the line from the point to the sheet is at a right angle to the sheet, or when the jumps become too small to matter. If a jump would make the distance larger, take half of it instead. If the rough answer was near the wrong valley, the jumps go to the bottom of that valley, and the method has no way to know.

The problem

The input is a tensor product Bézier patch r(u,v)r(u, v) on Ω=[0,1]2\Omega = [0, 1]^2, given by its control net, a point pp, a grid size nn, and two tolerances: ε1\varepsilon_1 for distances in space and ε2\varepsilon_2 for cosines. The output is a parameter pair (u,v)∈Ω(u, v) \in \Omega that satisfies the first order conditions of point projection to the tolerance, and is the nearest point when the start lies in its basin. A B-spline or NURBS surface is handled the same way, with the evaluation done by the de Boor algorithm.

Write w=r(u,v)−pw = r(u, v) - p, f=w⋅ruf = w \cdot r_u and g=w⋅rvg = w \cdot r_v. The squared distance D=∣w∣2D = |w|^2 has gradient 2(f,g)2 (f, g) and half Hessian

H=(ru⋅ru+w⋅ruuru⋅rv+w⋅ruvru⋅rv+w⋅ruvrv⋅rv+w⋅rvv),H = \begin{pmatrix} r_u \cdot r_u + w \cdot r_{uu} & r_u \cdot r_v + w \cdot r_{uv} \\ r_u \cdot r_v + w \cdot r_{uv} & r_v \cdot r_v + w \cdot r_{vv} \end{pmatrix},

which is the Jacobian of (f,g)(f, g). At a foot point p=r+tNp = r + t N, H=I−t IIH = \mathrm{I} - t \, \mathrm{II} in terms of the fundamental forms, so HH is singular exactly when pp is a center of principal curvature of the foot point.

The algorithm

  1. NEWTON-INVERT(r, p, n, ε1, ε2, kmax)
  2. 1(u, v) ← the grid point (i/n, j/n), 0 ≤ i, j ≤ n, with the least D = |r − p|²
  3. 2repeat at most kmax times
  4. 3evaluate r, r_u, r_v, r_uu, r_uv, r_vv at (u, v); w ← r − p; f ← w·r_u; g ← w·r_v
  5. 4if |w| ≤ ε1 then return (u, v) ▷ point coincidence
  6. 5if, for u and for v, |cos(w, r_u)| ≤ ε2 or the parameter is on an edge with its derivative pointing out, then return (u, v) ▷ zero cosine
  7. 6H ← the half Hessian above
  8. 7δ ← −A⁻¹ (f, g) on the parameters not frozen, with A = H if H is positive definite and A = I otherwise
  9. 8λ ← 1; while D(clamp((u, v) + λδ)) > D(u, v): λ ← λ/2; (u', v') ← clamp((u, v) + λδ)
  10. 9if |(u' − u) r_u + (v' − v) r_v| ≤ ε1 then return (u', v') ▷ the point no longer moves
  11. 10return (u, v)

Lines L1 to L5 and L9 are the method of Piegl and Tiller. Their three tests are the point coincidence of line L4, the zero cosine of line L5, and the test of line L9 that the step no longer moves the point in space. They clamp a parameter that leaves the box to its end, or wrap it around for a closed surface. This version adds three guards, each a few lines. A parameter on an edge whose derivative points out of the box is frozen, because there the box constraint is active and the Newton step in that parameter is meaningless. Where HH is not positive definite, line L7 uses the first fundamental form I\mathrm{I}, which is the Gauss-Newton matrix of the problem and always positive definite, so the step goes downhill. Line L8 halves a step that would raise DD. Near a nondegenerate minimum none of the guards fires, and the method is the plain Newton iteration. If a direction is still not downhill after the frozen and clamped parts are dropped, the code falls back to the scaled gradient −(f/E,g/G)-(f / E, g / G).

Example

Take the bicubic patch with control points Pij=(i,j,zij)P_{ij} = (i, j, z_{ij}), 0≤i,j≤30 \le i, j \le 3, where z11=z12=z21=z22=3z_{11} = z_{12} = z_{21} = z_{22} = 3 and all other zij=0z_{ij} = 0. Since the xx and yy coordinates of the net are evenly spaced, r(u,v)=(3u,3v,h(u,v))r(u, v) = (3u, 3v, h(u, v)), a bump of height h(12,12)=1.6875h(\tfrac12, \tfrac12) = 1.6875. Project p=(1,2,2.5)p = (1, 2, 2.5) with n=4n = 4.

The 2525 grid samples have distances from 1.07711.0771 (at the center) to 3.77493.7749, so line L1 starts at (0.5,0.5)(0.5, 0.5). There f=1.5f = 1.5, g=−1.5g = -1.5 and H=diag⁡(19.96875,19.96875)H = \operatorname{diag}(19.96875, 19.96875), so the first step is δ=(−0.0751174,0.0751174)\delta = (-0.0751174, 0.0751174).

iteration uu vv ∣w∣\lvert w \rvert ff gg
0 0.50.5 0.50.5 1.07710549621.0771054962 1.51.5 −1.5-1.5
1 0.42488262910.4248826291 0.57511737090.5751173709 0.96906122090.9690612209 −5.6⋅10−2-5.6 \cdot 10^{-2} 5.6⋅10−25.6 \cdot 10^{-2}
2 0.42741463590.4274146359 0.57258536410.5725853641 0.96891444900.9689144490 −1.7⋅10−4-1.7 \cdot 10^{-4} 1.7⋅10−41.7 \cdot 10^{-4}
3 0.42742233320.4274223332 0.57257766680.5725776668 0.96891444760.9689144476 −1.5⋅10−9-1.5 \cdot 10^{-9} 1.5⋅10−91.5 \cdot 10^{-9}
4 0.42742233330.4274223333 0.57257766670.5725776667 0.96891444760.9689144476 −1.1⋅10−15-1.1 \cdot 10^{-15} −1.3⋅10−15-1.3 \cdot 10^{-15}

Line L5 stops at iteration 44. The residual is roughly squared at each step: 1.51.5, 5.6⋅10−25.6 \cdot 10^{-2}, 1.7⋅10−41.7 \cdot 10^{-4}, 1.5⋅10−91.5 \cdot 10^{-9}, with ratios ek+1/ek2e_{k+1} / e_k^2 of about 0.0250.025, 0.0540.054 and 0.0540.054. The foot point is r=(1.282267,1.717733,1.617138)r = (1.282267, 1.717733, 1.617138), and w=(0.282267,−0.282267,−0.882862)w = (0.282267, -0.282267, -0.882862) is a multiple of ru×rv=(−2.877462,2.877462,9)r_u \times r_v = (-2.877462, 2.877462, 9), so pp is on the normal line. The point lies on the diagonal u+v=1u + v = 1 because pp and the patch are symmetric about the plane x+y=3x + y = 3. A 301×301301 \times 301 grid gives 0.9689270.968927 as its best distance, a little worse than the Newton answer, as a grid must be.

Correctness

The full proof shows five facts, in exact arithmetic. A point returned by line L5 satisfies the first order conditions of the box to the tolerance. Each direction of line L7 goes downhill unless the point already satisfies them, so the halving of line L8 ends and DD never increases: the answer is never worse than the best grid sample. Near an interior foot point at which 1−tk1>01 - t k_1 > 0 and 1−tk2>01 - t k_2 > 0, a strict local minimum with pp off the focal surface, the iterates take full Newton steps and ∣xk+1−x∗∣≤C∣xk−x∗∣2|x_{k+1} - x^*| \le C |x_k - x^*|^2, with C=∣H(x∗)−1∣⋅γC = |H(x^*)^{-1}| \cdot \gamma for the Lipschitz constant γ\gamma of HH. This is the standard local estimate for Newton's method, proved in the file. Last, if every point whose value of DD is within η\eta of the global minimum lies in that quadratic basin, a grid with spacing h≤2 η/Λh \le \sqrt 2 \, \eta / \Lambda, for a bound Λ\Lambda on ∣∇D∣|\nabla D|, makes the method return the global minimum.

What is not proved is that a given grid is fine enough: η\eta depends on the second best local minimum, which the method does not know. On random bicubic patches, with control points jittered by up to 0.30.3 around a 4×44 \times 4 grid, heights in [−1.5,1.5][-1.5, 1.5] and pp in the box [−0.5,3.5]2×[−2,2][-0.5, 3.5]^2 \times [-2, 2], the answer was worse than a 101×101101 \times 101 grid in 44 of 300300 cases for n=2n = 2, in 11 of 300300 for n=4n = 4, and in none of 300300 for n=10n = 10. These rates are measured on that class only.

Proof: Newton point inversion stops at a first order point, never raises the distance, and converges quadratically near a nondegenerate foot pointfull

Let r:Ω→R3r : \Omega \to \mathbb{R}^3 be a regular patch of class C3C^3 on the box Ω=[0,1]2\Omega = [0, 1]^2, let pp be a point, and let D(u,v)=∣r(u,v)−p∣2D(u, v) = |r(u, v) - p|^2. Write x=(u,v)x = (u, v), w=r−pw = r - p, f=w⋅ruf = w \cdot r_u and g=w⋅rvg = w \cdot r_v, so that ∇D=2(f,g)\nabla D = 2 (f, g). Let H(x)H(x) be half the Hessian of DD, the matrix of line L6, and let I(x)\mathrm{I}(x) be the first fundamental form. The proof uses exact arithmetic. The implementation accepts a step shorter than 10−6(1+∣w∣)10^{-6} (1 + |w|) in space without the test of line L8, to stop rounding from blocking the last Newton steps; that device changes nothing below.

Call xx a first order point if the conditions of the box hold: for each parameter, either its derivative (ff for uu, gg for vv) is zero, or the parameter is on an edge and its derivative points out of the box (u=0u = 0 and f>0f > 0, or u=1u = 1 and f<0f < 0, and the same for vv with gg). Every local minimum of DD on Ω\Omega is a first order point, by the proof on the problem page.

Claim 1 (what is returned). A point returned at line L5 is a first order point up to the tolerance: each derivative that is not frozen satisfies ∣f∣≤ε2∣w∣∣ru∣|f| \le \varepsilon_2 |w| |r_u|, that is, the cosine of the angle between ww and rur_u is at most ε2\varepsilon_2, and the same for gg. A point returned at line L4 is within ε1\varepsilon_1 of pp.

Proof. These are the tests of lines L4 and L5. □\square

Claim 2 (descent). If xx is not a first order point, the direction δ\delta of line L7 satisfies ∇D(x)⋅δ<0\nabla D(x) \cdot \delta < 0, and a step of length λ∣δ∣\lambda |\delta| along δ\delta stays in Ω\Omega for all small λ>0\lambda > 0. So the halving loop of line L8 ends with D(x′)<D(x)D(x') < D(x).

Proof. Let FF be the set of parameters that are not frozen. A frozen parameter has its component of δ\delta set to 00. On FF, the direction is −A−1∇F-A^{-1} \nabla_F for a positive definite matrix AA: the Hessian block when it is positive definite, otherwise the block of I\mathrm{I}, which is positive definite because rr is regular. Then ∇F⋅δ=−∇F⊤A−1∇F<0\nabla_F \cdot \delta = -\nabla_F^\top A^{-1} \nabla_F < 0 unless ∇F=0\nabla_F = 0. A component that points out of the box at a parameter on an edge is set to zero next. If the result still has ∇⋅δ<0\nabla \cdot \delta < 0, it is kept. Otherwise the code takes the fallback δ=(−f/E,−g/G)\delta = (-f / E, -g / G) on FF, with E,G>0E, G > 0, for which ∇⋅δ=−2(f2/E+g2/G)<0\nabla \cdot \delta = -2 (f^2 / E + g^2 / G) < 0 unless f=g=0f = g = 0 on FF, which, with the frozen parameters, makes xx a first order point. The fallback never points out of the box: a parameter on an edge whose derivative points into the box is not frozen, and then −f/E-f / E points into the box as well. For small λ\lambda no component is clamped, so D(x+λδ)=D(x)+λ∇D⋅δ+O(λ2)<D(x)D(x + \lambda \delta) = D(x) + \lambda \nabla D \cdot \delta + O(\lambda^2) < D(x), and halving reaches such a λ\lambda. □\square

Claim 3 (no increase). The values of DD at the iterates do not increase, and the returned point has DD no larger than at the best sample of the start grid.

Proof. Line L8 accepts a new point only if DD does not increase, and by Claim 2 it finds one unless xx is a first order point, in which case line L5 has already returned. □\square

Claim 4 (local quadratic convergence). Let x∗x^* be an interior point with f=g=0f = g = 0 at which H(x∗)H(x^*) is positive definite. By the second order test on the problem page, this holds exactly when 1−tk1>01 - t k_1 > 0 and 1−tk2>01 - t k_2 > 0, where p=r(x∗)+tNp = r(x^*) + t N and k1,k2k_1, k_2 are the principal curvatures, that is, when x∗x^* is a strict local minimum and pp is not on the focal surface. Then there are ρ>0\rho > 0 and CC such that from every x0x_0 with ∣x0−x∗∣≤ρ|x_0 - x^*| \le \rho the iterates take full Newton steps, stay in the ball, and satisfy

∣xk+1−x∗∣≤C∣xk−x∗∣2.|x_{k+1} - x^*| \le C |x_k - x^*|^2.

Proof. Put Φ(x)=(f,g)\Phi(x) = (f, g), so Φ′=H\Phi' = H. Since r∈C3r \in C^3, HH is Lipschitz near x∗x^* with some constant γ\gamma. Choose ρ0\rho_0 so that the closed ball BB of radius ρ0\rho_0 about x∗x^* lies inside Ω\Omega, and so that on BB the matrix HH is positive definite with ∣H(x)−1∣≤2β|H(x)^{-1}| \le 2 \beta, where β=∣H(x∗)−1∣\beta = |H(x^*)^{-1}|. This is possible by continuity. On BB no parameter is on an edge, so nothing is frozen, and line L7 takes the Newton step δ=−H(x)−1Φ(x)\delta = -H(x)^{-1} \Phi(x). With e=x−x∗e = x - x^* and Φ(x∗)=0\Phi(x^*) = 0,

x+δ−x∗=H(x)−1(H(x)e−(Φ(x)−Φ(x∗))).x + \delta - x^* = H(x)^{-1} \big( H(x) e - (\Phi(x) - \Phi(x^*)) \big).

By the fundamental theorem of calculus, Φ(x)−Φ(x∗)=∫01H(x∗+se)e ds\Phi(x) - \Phi(x^*) = \int_0^1 H(x^* + s e) e \, ds, so the bracket has norm at most ∫01γ(1−s)∣e∣2ds=γ2∣e∣2\int_0^1 \gamma (1 - s) |e|^2 ds = \frac{\gamma}{2} |e|^2. Hence ∣x+δ−x∗∣≤βγ∣e∣2|x + \delta - x^*| \le \beta \gamma |e|^2. Put C=βγC = \beta \gamma.

It remains to show that line L8 accepts the full step. By Taylor's theorem and the positive definiteness of H(x∗)H(x^*), there are 0<μ≤M0 < \mu \le M and ρ1≤ρ0\rho_1 \le \rho_0 with μ∣e∣2≤D(x)−D(x∗)≤M∣e∣2\mu |e|^2 \le D(x) - D(x^*) \le M |e|^2 for ∣e∣≤ρ1|e| \le \rho_1. Take ρ=min⁡(ρ1,12C,μ/M/C)\rho = \min(\rho_1, \frac{1}{2C}, \sqrt{\mu / M} / C). For ∣e∣≤ρ|e| \le \rho the full step gives ∣e′∣≤C∣e∣2≤∣e∣/2|e'| \le C |e|^2 \le |e| / 2, so the new point is in the ball, and

D(x+δ)−D(x∗)≤MC2∣e∣4≤μ∣e∣2≤D(x)−D(x∗),D(x + \delta) - D(x^*) \le M C^2 |e|^4 \le \mu |e|^2 \le D(x) - D(x^*),

because C2∣e∣2≤μ/MC^2 |e|^2 \le \mu / M. So DD does not increase, line L8 keeps λ=1\lambda = 1, and induction on kk gives the claim. □\square

The constants β\beta, γ\gamma, μ\mu and MM are not computed by the method. The Kantorovich theorem gives a test with constants that can be computed at the start point and that proves a Newton sequence converges, which certified versions use.

Claim 5 (when the start grid is dense enough). Let x∗x^* be the global minimizer and assume it satisfies Claim 4 with radius ρ\rho. Let Λ\Lambda bound ∣∇D∣|\nabla D| on Ω\Omega and let η>0\eta > 0 be such that every x∈Ωx \in \Omega with D(x)≤D(x∗)+ηD(x) \le D(x^*) + \eta lies within ρ\rho of x∗x^*. If the grid spacing h=1/nh = 1/n satisfies Λh/2≤η\Lambda h / \sqrt 2 \le \eta, the method converges to x∗x^*.

Proof. Some grid point yy lies within half a diagonal of a grid cell, h/2h / \sqrt 2, of x∗x^*. By the mean value theorem D(y)≤D(x∗)+Λh/2≤D(x∗)+ηD(y) \le D(x^*) + \Lambda h / \sqrt 2 \le D(x^*) + \eta. The best sample x0x_0 has D(x0)≤D(y)D(x_0) \le D(y), so ∣x0−x∗∣≤ρ|x_0 - x^*| \le \rho, and Claim 4 applies. □\square

Λ\Lambda can be bounded from the control net, since ∣∇D∣≤2∣w∣∣ru∣2+∣rv∣2|\nabla D| \le 2 |w| \sqrt{|r_u|^2 + |r_v|^2} and the derivative nets bound rur_u and rvr_v by the convex hull property. But η\eta depends on how close the second best local minimum comes to the global one, and no cheap bound for it is known, so Claim 5 explains when the method works and does not give a grid size in advance. ■\blacksquare

Complexity

Let the patch have m=(d1+1)(d2+1)m = (d_1 + 1)(d_2 + 1) control points for bidegree (d1,d2)(d_1, d_2). One evaluation of the point and its derivatives up to order two costs O(m)O(m) once the Bernstein values are known, which cost O(d1+d2)O(d_1 + d_2). Line L1 makes (n+1)2(n + 1)^2 evaluations, O(n2m)O(n^2 m) time. Each iteration costs O(m)O(m) for line L3 and O(m)O(m) for each halving of line L8. Near the solution no halving happens, and quadratic convergence makes kk about log⁡2log⁡2(1/ε)\log_2 \log_2 (1 / \varepsilon) once the error is below 1/(2C)1 / (2C), so kk is 44 to 66 in double precision. The total is O((n2+k)m)O((n^2 + k) m) time and O(m)O(m) extra space. For NURBS each evaluation costs O((d1+1)(d2+1))O((d_1 + 1)(d_2 + 1)) after a search for the knot span, which is O(log⁡K)O(\log K) for KK knots.

Properties

  • Local. It finds the stationary point whose basin holds the start, and the start is the only global ingredient.
  • Quadratic near a regular minimum. The number of correct digits roughly doubles per step, as the example shows.
  • Monotone. With the halving of line L8 the distance never increases, so the answer is at least as good as the start sample.
  • Floating point. All steps are in floating point. The output satisfies the tests to the tolerances, and nothing is exact.

Variants and improvements

  • Plain Piegl and Tiller. Without the guards, the iteration is the textbook Newton method with clamping. It can cycle on an edge, where clamping one parameter leaves the other step wrong, and it can climb to a maximum where HH is indefinite. The guards remove both failures at the cost of one extra evaluation per step.
  • Curves. For a curve c(u)c(u) the iteration is u←u−(c−p)⋅c′c′⋅c′+(c−p)⋅c′′u \leftarrow u - \frac{(c - p) \cdot c'}{c' \cdot c' + (c - p) \cdot c''}, with the same tests.
  • Better start points. Ma and Hewitt subdivide the control net, discard the pieces whose control polygon is farther than the best distance found, and start Newton from the remaining pieces. With exclusion by proved bounds this makes the answer global up to the tolerance.
  • Certified. The interval Newton method or the interval projected polyhedron method finds all stationary points in the box with proofs.
  • Gauss-Newton. Dropping the terms w⋅ruuw \cdot r_{uu}, w⋅ruvw \cdot r_{uv}, w⋅rvvw \cdot r_{vv} from HH gives the Gauss-Newton algorithm for the least squares problem min⁡∣r−p∣2\min |r - p|^2. It needs no second derivatives. It converges quadratically for point inversion, where w=0w = 0 at the solution and the dropped terms vanish there, and only linearly when pp is off the surface, with a rate that is good when the distance is small compared with the radius of curvature.
  • Many points. When many points are projected onto one surface, as in iterative closest point or parameter correction, the foot point of a neighbor is a better start than the grid.

When to use it

Use it to snap picked points, to invert points known to lie on the surface, and in loops that project many points that move little, where a good start is always at hand. Use a subdivision method with exclusion, or a certified solver, when the answer must be the global minimum, for example when a distance is used as a tolerance check in inspection.

Pitfalls

  • The wrong valley. The best grid sample can lie in the basin of a local minimum that is not the global one. Then the method converges, quickly and accurately, to the wrong answer.
  • A start on a stationary point. For the bump patch and p=(1.5,1.5,1)p = (1.5, 1.5, 1), below the top, the center (0.5,0.5)(0.5, 0.5) is a grid point for even nn and satisfies f=g=0f = g = 0 exactly, by symmetry. Line L5 returns it at once with distance 0.68750.6875. But there t=−0.6875t = -0.6875, k=−1.5k = -1.5 and 1−tk=−0.03125<01 - t k = -0.03125 < 0, so the center is not a minimum, it is a local maximum of the distance. The true minimum is 17/6≈0.6871843\sqrt{17} / 6 \approx 0.6871843 at (49,12)(\tfrac49, \tfrac12) and its three mirror images (59,12)(\tfrac59, \tfrac12), (12,49)(\tfrac12, \tfrac49), (12,59)(\tfrac12, \tfrac59). An odd nn does not help: its best sample lies on the diagonal u=vu = v, the iterates stay on it by symmetry, and they end at 0.68723660.6872366 near (0.4641,0.4641)(0.4641, 0.4641), a saddle of the distance. The smallest grid that finds the minimum is n=14n = 14. A second order check at line L5 catches both cases.
  • Near the focal surface. When 1−tki1 - t k_i is near 00, HH is nearly singular, convergence slows, and the parameters are ill conditioned even when the distance is accurate. In the case above, runs from different grids agree on the distance to 10−1010^{-10} and on uu only to about 10−510^{-5}.
  • Singular parametrizations. At a pole of a sphere or the apex of a cone, ru=0r_u = 0, the zero cosine test divides by zero, and I\mathrm{I} is singular. Treat such points as special cases.
  • Clamping alone. Clamping a Newton step to the box without freezing the parameter can cycle along an edge, as the variant above notes.
  • Tolerances in model units. ε1\varepsilon_1 is a distance and must match the size of the model. A value of 10−1210^{-12} is too strict for a part measured in meters with single precision data.

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.

newton_point_inversion.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/newton-point-inversion/. The authors are listed in prov/BYMVEB.jsonl.

"""Newton point inversion on a tensor product Bezier patch, in floating point.

The patch r(u, v) is given by its control net on the box [0, 1] x [0, 1]. The
method of Piegl and Tiller takes the best sample of an (n + 1) x (n + 1) grid
as the start, then runs Newton's method on the two equations
f = (r - p) . r_u = 0 and g = (r - p) . r_v = 0, and stops on one of three
tests: point coincidence, zero cosine, or a step that no longer moves the
point. This version adds the guards that the page describes: a parameter on
an edge of the box whose derivative points out of the box is frozen, the
Gauss-Newton matrix (the first fundamental form) replaces a Hessian that is
not positive definite, and a step that does not lower D = |r - p|^2 is
halved. So D never increases, except by steps shorter than 1e-6 (1 + |r - p|)
in space, which only occur next to a solution.
"""

from typing import Sequence

from si1geom import Vec, dot, norm, patch_derivs, patch_point, sub


def _clamp(x: float) -> float:
    return 0.0 if x < 0.0 else 1.0 if x > 1.0 else x


def _sq_dist(P: Sequence[Sequence[Vec]], p: Vec, u: float, v: float) -> float:
    w = sub(patch_point(P, u, v), p)
    return dot(w, w)


def _direction(u: float, v: float, f: float, g: float, hess: tuple, gn: tuple) -> tuple[float, float]:
    """A descent direction for D at (u, v) inside the box, or (0, 0) at a
    point that satisfies the first order conditions of the box exactly.

    hess = (a, b, c) is half the Hessian of D, gn = (E, F, G) the
    Gauss-Newton matrix. The gradient of D/2 is (f, g).
    """
    out_u = (u == 0.0 and f > 0) or (u == 1.0 and f < 0)
    out_v = (v == 0.0 and g > 0) or (v == 1.0 and g < 0)
    a, b, c = hess
    E, F, G = gn
    if out_u and out_v:
        return 0.0, 0.0
    if out_u:
        du, dv = 0.0, -g / (c if c > 0 else G)
    elif out_v:
        du, dv = -f / (a if a > 0 else E), 0.0
    else:
        if not (a > 0 and a * c - b * b > 0):
            a, b, c = E, F, G
        det = a * c - b * b
        du, dv = (-f * c + g * b) / det, (-g * a + f * b) / det
    # a component that would leave the box at once is dropped
    if (u == 0.0 and du < 0) or (u == 1.0 and du > 0):
        du = 0.0
    if (v == 0.0 and dv < 0) or (v == 1.0 and dv > 0):
        dv = 0.0
    if f * du + g * dv < 0:
        return du, dv
    # fallback: the scaled gradient, without the components that point out
    du = 0.0 if out_u else -f / E
    dv = 0.0 if out_v else -g / G
    return du, dv


def newton_point_inversion(
    P: Sequence[Sequence[Vec]],
    p: Vec,
    n_grid: int = 10,
    eps1: float = 1e-12,
    eps2: float = 1e-12,
    max_iter: int = 100,
    trace: list | None = None,
) -> tuple[float, float]:
    """Return parameters (u, v) in [0, 1]^2 of a foot point of p on the patch P.

    The result is a point at which the first order conditions of the box
    hold to the tolerance eps2, or the last iterate when a test of L4, L9 or
    the iteration limit fires first. It is the global nearest point when the
    best grid sample lies in the basin of the global minimizer. If trace is a
    list, the iterates (u, v, |r - p|, f, g) are appended to it.
    """
    best = None
    for i in range(n_grid + 1):  # @line L1
        for j in range(n_grid + 1):
            u0, v0 = i / n_grid, j / n_grid
            d = _sq_dist(P, p, u0, v0)
            if best is None or d < best[0]:
                best = (d, u0, v0)
    D, u, v = best
    for _ in range(max_iter):  # @line L2
        r, ru, rv, ruu, ruv, rvv = patch_derivs(P, u, v)  # @line L3
        w = sub(r, p)
        f, g = dot(w, ru), dot(w, rv)
        nw = norm(w)
        if trace is not None:
            trace.append((u, v, nw, f, g))
        if nw <= eps1:  # @line L4
            return u, v
        E, F, G = dot(ru, ru), dot(ru, rv), dot(rv, rv)
        ok_u = (u == 0.0 and f > 0) or (u == 1.0 and f < 0) or abs(f) <= eps2 * nw * E ** 0.5
        ok_v = (v == 0.0 and g > 0) or (v == 1.0 and g < 0) or abs(g) <= eps2 * nw * G ** 0.5
        if ok_u and ok_v:  # @line L5
            return u, v
        hess = (E + dot(w, ruu), F + dot(w, ruv), G + dot(w, rvv))  # @line L6
        du, dv = _direction(u, v, f, g, hess, (E, F, G))  # @line L7
        small = norm((du * ru[0] + dv * rv[0], du * ru[1] + dv * rv[1], du * ru[2] + dv * rv[2])) <= 1e-6 * (1 + nw)
        lam = 1.0
        while True:  # @line L8
            un, vn = _clamp(u + lam * du), _clamp(v + lam * dv)
            Dn = _sq_dist(P, p, un, vn)
            if small:
                Dn = min(Dn, D)
            if Dn <= D * (1 + 1e-14) or lam < 1e-12:
                break
            lam *= 0.5
        if Dn > D * (1 + 1e-14):
            return u, v
        moved = norm(((un - u) * ru[0] + (vn - v) * rv[0],
                      (un - u) * ru[1] + (vn - v) * rv[1],
                      (un - u) * ru[2] + (vn - v) * rv[2]))
        u, v, D = un, vn, Dn
        if moved <= eps1:  # @line L9
            return u, v
    return u, v  # @line L10
si1geom.py 298 lines
# SPDX-License-Identifier: MIT
# Shared helper of the si1 cad pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small geometric and algebraic tools for the si1 pages.

Vectors are tuples of three numbers. A tensor product Bezier patch of bidegree
(m, n) is a list of m + 1 rows of n + 1 control points. Univariate polynomials
are lists of coefficients from the constant term up. Entries may be int,
Fraction or float; exact inputs give exact results where no square root or
division by a float is involved. No function here is the algorithm of a page.
"""

from fractions import Fraction
from math import comb, sqrt
from typing import Sequence

Vec = tuple
Num = float


# ---- vectors ---------------------------------------------------------------

def add(a: Vec, b: Vec) -> Vec:
    return (a[0] + b[0], a[1] + b[1], a[2] + b[2])


def sub(a: Vec, b: Vec) -> Vec:
    return (a[0] - b[0], a[1] - b[1], a[2] - b[2])


def scale(t, a: Vec) -> Vec:
    return (t * a[0], t * a[1], t * a[2])


def dot(a: Vec, b: Vec):
    return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]


def cross(a: Vec, b: Vec) -> Vec:
    return (a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0])


def norm(a: Vec) -> float:
    return sqrt(float(dot(a, a)))


def lincomb(ws: Sequence, ps: Sequence[Vec]) -> Vec:
    """Return sum of ws[i] * ps[i]."""
    x = y = z = 0
    for w, p in zip(ws, ps):
        x += w * p[0]
        y += w * p[1]
        z += w * p[2]
    return (x, y, z)


# ---- Bernstein basis -------------------------------------------------------

def bernstein(n: int, t) -> list:
    """Values B_{i,n}(t) for i = 0..n, by the explicit formula."""
    s = 1 - t
    return [comb(n, i) * t ** i * s ** (n - i) for i in range(n + 1)]


def bernstein_d(n: int, t, k: int) -> list:
    """k-th derivatives of B_{i,n} at t, for k = 0, 1, 2, from the difference formula."""
    if k == 0 or n == 0:
        return bernstein(n, t) if k == 0 else [0] * (n + 1)
    low = bernstein_d(n - 1, t, k - 1)
    out = []
    for i in range(n + 1):
        a = low[i - 1] if i >= 1 else 0
        b = low[i] if i <= n - 1 else 0
        out.append(n * (a - b))
    return out


def patch_point(P: Sequence[Sequence[Vec]], u, v) -> Vec:
    m, n = len(P) - 1, len(P[0]) - 1
    bu, bv = bernstein(m, u), bernstein(n, v)
    x = y = z = 0
    for i in range(m + 1):
        for j in range(n + 1):
            w = bu[i] * bv[j]
            q = P[i][j]
            x += w * q[0]
            y += w * q[1]
            z += w * q[2]
    return (x, y, z)


def patch_derivs(P: Sequence[Sequence[Vec]], u, v) -> tuple:
    """Return (r, r_u, r_v, r_uu, r_uv, r_vv) of a Bezier patch at (u, v)."""
    m, n = len(P) - 1, len(P[0]) - 1
    U = [bernstein_d(m, u, k) for k in range(3)]
    V = [bernstein_d(n, v, k) for k in range(3)]
    out = []
    for a, b in ((0, 0), (1, 0), (0, 1), (2, 0), (1, 1), (0, 2)):
        x = y = z = 0
        for i in range(m + 1):
            ui = U[a][i]
            for j in range(n + 1):
                w = ui * V[b][j]
                q = P[i][j]
                x += w * q[0]
                y += w * q[1]
                z += w * q[2]
        out.append((x, y, z))
    return tuple(out)


def curve_point(C: Sequence[Vec], t) -> Vec:
    return lincomb(bernstein(len(C) - 1, t), C)


# ---- univariate polynomials, coefficient lists from the constant term ------

def ptrim(a: list) -> list:
    a = list(a)
    while len(a) > 1 and a[-1] == 0:
        a.pop()
    return a


def padd(a: list, b: list) -> list:
    n = max(len(a), len(b))
    return ptrim([(a[i] if i < len(a) else 0) + (b[i] if i < len(b) else 0) for i in range(n)])


def pscale(c, a: list) -> list:
    return ptrim([c * x for x in a])


def pmul(a: list, b: list) -> list:
    out = [0] * (len(a) + len(b) - 1)
    for i, x in enumerate(a):
        if x == 0:
            continue
        for j, y in enumerate(b):
            out[i + j] += x * y
    return ptrim(out)


def ppow(a: list, k: int) -> list:
    out = [1]
    for _ in range(k):
        out = pmul(out, a)
    return out


def peval(a: list, t):
    s = 0
    for c in reversed(a):
        s = s * t + c
    return s


def pderiv(a: list) -> list:
    return ptrim([i * a[i] for i in range(1, len(a))]) if len(a) > 1 else [0]


def real_roots(a: list, lo: float, hi: float, tol: float = 1e-13) -> list:
    """Real roots of a polynomial in [lo, hi], each once, in increasing order.

    The roots of the derivative split [lo, hi] into pieces on which the
    polynomial is monotone; each piece holds at most one root, found by
    bisection. A root of even multiplicity is found when the polynomial is
    zero (to within the rounding of a float) at a critical point.
    """
    a = ptrim([float(c) for c in a])
    if len(a) == 1:
        return []
    crit = real_roots(pderiv(a), lo, hi, tol) if len(a) > 2 else []
    knots = [lo] + [c for c in crit if lo < c < hi] + [hi]
    scale_ = max(abs(c) for c in a)
    roots = []
    for x0, x1 in zip(knots, knots[1:]):
        f0, f1 = peval(a, x0), peval(a, x1)
        if f0 == 0 or abs(f0) <= 1e-14 * scale_:
            if not roots or abs(roots[-1] - x0) > 1e-9:
                roots.append(x0)
            continue
        if f0 * f1 > 0:
            continue
        if f1 == 0 or abs(f1) <= 1e-14 * scale_:
            continue
        a0, a1 = x0, x1
        while a1 - a0 > tol:
            mid = 0.5 * (a0 + a1)
            fm = peval(a, mid)
            if (fm < 0) == (f0 < 0):
                a0, f0 = mid, fm
            else:
                a1 = mid
        roots.append(0.5 * (a0 + a1))
    f_hi = peval(a, hi)
    if abs(f_hi) <= 1e-14 * scale_ and (not roots or abs(roots[-1] - hi) > 1e-9):
        roots.append(hi)
    return roots


# ---- dense linear algebra --------------------------------------------------

def solve(A: list, b: list) -> list:
    """Solve A x = b by Gaussian elimination with partial pivoting.

    Works for Fraction entries (exact, pivot = first nonzero) and for floats.
    Raises ZeroDivisionError when A is singular (exactly, or to the pivot test
    1e-300 for floats).
    """
    n = len(A)
    M = [list(A[i]) + [b[i]] for i in range(n)]
    for c in range(n):
        piv = max(range(c, n), key=lambda r: abs(M[r][c]))
        if M[piv][c] == 0 or (isinstance(M[piv][c], float) and abs(M[piv][c]) < 1e-300):
            raise ZeroDivisionError("singular matrix")
        M[c], M[piv] = M[piv], M[c]
        for r in range(c + 1, n):
            f = M[r][c] / M[c][c]
            if f != 0:
                for k in range(c, n + 1):
                    M[r][k] -= f * M[c][k]
    x = [0] * n
    for i in range(n - 1, -1, -1):
        s = M[i][n] - sum(M[i][k] * x[k] for k in range(i + 1, n))
        x[i] = s / M[i][i]
    return x


def det(A: list):
    """Determinant by fraction free Bareiss elimination for int and Fraction
    entries, and by Gaussian elimination for floats."""
    n = len(A)
    if n == 0:
        return 1
    if any(isinstance(x, float) for row in A for x in row):
        M = [list(map(float, row)) for row in A]
        d = 1.0
        for c in range(n):
            piv = max(range(c, n), key=lambda r: abs(M[r][c]))
            if M[piv][c] == 0:
                return 0.0
            if piv != c:
                M[c], M[piv] = M[piv], M[c]
                d = -d
            d *= M[c][c]
            for r in range(c + 1, n):
                f = M[r][c] / M[c][c]
                for k in range(c, n):
                    M[r][k] -= f * M[c][k]
        return d
    M = [[Fraction(x) for x in row] for row in A]
    sign = 1
    prev = Fraction(1)
    for c in range(n - 1):
        if M[c][c] == 0:
            piv = next((r for r in range(c + 1, n) if M[r][c] != 0), None)
            if piv is None:
                return Fraction(0)
            M[c], M[piv] = M[piv], M[c]
            sign = -sign
        for r in range(c + 1, n):
            for k in range(c + 1, n):
                M[r][k] = (M[r][k] * M[c][c] - M[r][c] * M[c][k]) / prev
            M[r][c] = Fraction(0)
        prev = M[c][c]
    return sign * M[n - 1][n - 1]


def jacobi_eigen(A: list, sweeps: int = 60) -> tuple:
    """Eigenvalues and eigenvectors of a small symmetric float matrix by the
    cyclic Jacobi method. Returns (values, vectors) with vectors[k] the unit
    eigenvector of values[k], sorted by increasing value."""
    n = len(A)
    M = [[float(x) for x in row] for row in A]
    V = [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]
    for _ in range(sweeps):
        off = sum(M[i][j] ** 2 for i in range(n) for j in range(n) if i != j)
        if off < 1e-30:
            break
        for p in range(n - 1):
            for q in range(p + 1, n):
                if abs(M[p][q]) < 1e-300:
                    continue
                theta = (M[q][q] - M[p][p]) / (2 * M[p][q])
                t = (1.0 if theta >= 0 else -1.0) / (abs(theta) + sqrt(theta * theta + 1))
                c = 1 / sqrt(t * t + 1)
                s = t * c
                for k in range(n):
                    mkp, mkq = M[k][p], M[k][q]
                    M[k][p], M[k][q] = c * mkp - s * mkq, s * mkp + c * mkq
                for k in range(n):
                    mpk, mqk = M[p][k], M[q][k]
                    M[p][k], M[q][k] = c * mpk - s * mqk, s * mpk + c * mqk
                for k in range(n):
                    vkp, vkq = V[k][p], V[k][q]
                    V[k][p], V[k][q] = c * vkp - s * vkq, s * vkp + c * vkq
    order = sorted(range(n), key=lambda i: M[i][i])
    return [M[i][i] for i in order], [[V[k][i] for k in range(n)] for i in order]
test_newton_point_inversion.py 103 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/newton-point-inversion/. The authors are listed in prov/BYMVEB.jsonl.

import random
import unittest

from newton_point_inversion import newton_point_inversion
from si1geom import bernstein, dot, norm, patch_derivs, patch_point, sub

Z = [[0, 0, 0, 0], [0, 3, 3, 0], [0, 3, 3, 0], [0, 0, 0, 0]]
BUMP = [[(i, j, Z[i][j]) for j in range(4)] for i in range(4)]


def dense_min(P, p, n):
    """Brute force: the least distance from p over an (n + 1) x (n + 1) grid."""
    m = len(P) - 1
    B = [bernstein(m, i / n) for i in range(n + 1)]
    best = float("inf")
    for i in range(n + 1):
        bu = B[i]
        rows = [tuple(sum(bu[a] * P[a][b][k] for a in range(m + 1)) for k in range(3)) for b in range(m + 1)]
        for j in range(n + 1):
            bv = B[j]
            x = sum(bv[b] * rows[b][0] for b in range(m + 1)) - p[0]
            y = sum(bv[b] * rows[b][1] for b in range(m + 1)) - p[1]
            z = sum(bv[b] * rows[b][2] for b in range(m + 1)) - p[2]
            best = min(best, x * x + y * y + z * z)
    return best ** 0.5


def kkt_holds(P, p, u, v, tol=1e-7):
    r, ru, rv = patch_derivs(P, u, v)[:3]
    w = sub(r, p)
    f, g = dot(w, ru), dot(w, rv)
    scale_ = 1 + norm(w)
    ok_u = abs(f) <= tol * scale_ * norm(ru) or (u == 0.0 and f > 0) or (u == 1.0 and f < 0)
    ok_v = abs(g) <= tol * scale_ * norm(rv) or (v == 0.0 and g > 0) or (v == 1.0 and g < 0)
    return ok_u and ok_v


class TestNewtonPointInversion(unittest.TestCase):
    def test_example_trace(self):
        tr = []
        u, v = newton_point_inversion(BUMP, (1.0, 2.0, 2.5), n_grid=4, trace=tr)
        self.assertEqual(tr[0][:2], (0.5, 0.5))
        self.assertAlmostEqual(tr[1][0], 0.4248826291, places=9)
        self.assertAlmostEqual(u, 0.4274223333, places=9)
        self.assertAlmostEqual(v, 0.5725776667, places=9)
        self.assertAlmostEqual(norm(sub(patch_point(BUMP, u, v), (1.0, 2.0, 2.5))), 0.9689144476, places=9)
        self.assertEqual(len(tr), 5)

    def test_quadratic_convergence(self):
        tr = []
        newton_point_inversion(BUMP, (0.5, 2.0, 2.0), n_grid=4, trace=tr)
        e = [max(abs(t[3]), abs(t[4])) for t in tr]
        for k in range(1, len(e) - 1):
            if e[k] > 1e-10:
                self.assertLessEqual(e[k + 1], 0.2 * e[k] ** 2)

    def test_inversion_of_points_on_the_patch(self):
        rng = random.Random(3)
        for _ in range(40):
            u0, v0 = rng.uniform(0.02, 0.98), rng.uniform(0.02, 0.98)
            u, v = newton_point_inversion(BUMP, patch_point(BUMP, u0, v0))
            self.assertAlmostEqual(u, u0, places=9)
            self.assertAlmostEqual(v, v0, places=9)

    def test_edges_and_corners(self):
        flat = [[(i / 3, j / 3, 0) for j in range(4)] for i in range(4)]
        self.assertEqual(newton_point_inversion(flat, (2.0, 0.5, 1.0)), (1.0, 0.5))
        self.assertEqual(newton_point_inversion(flat, (2.0, 2.0, 1.0)), (1.0, 1.0))
        u, v = newton_point_inversion(flat, (-1.0, 0.3, -1.0))
        self.assertEqual(u, 0.0)
        self.assertAlmostEqual(v, 0.3, places=12)

    def test_stationary_start_is_a_pitfall(self):
        p = (1.5, 1.5, 1.0)
        self.assertEqual(newton_point_inversion(BUMP, p, n_grid=2), (0.5, 0.5))
        # An odd grid starts on the diagonal u = v and ends at a saddle of the distance.
        u, v = newton_point_inversion(BUMP, p, n_grid=3)
        self.assertAlmostEqual(u, v, places=8)
        self.assertAlmostEqual(norm(sub(patch_point(BUMP, u, v), p)), 0.6872365853, places=8)
        # The true minimum is sqrt(17) / 6 at (4/9, 1/2) and its mirror images.
        u, v = newton_point_inversion(BUMP, p, n_grid=14)
        self.assertAlmostEqual(u, 4 / 9, places=8)
        self.assertAlmostEqual(v, 0.5, places=8)
        self.assertAlmostEqual(norm(sub(patch_point(BUMP, u, v), p)), 17 ** 0.5 / 6, places=10)

    def test_against_dense_sampling(self):
        rng = random.Random(7)
        for _ in range(60):
            P = [[(i + rng.uniform(-0.3, 0.3), j + rng.uniform(-0.3, 0.3), rng.uniform(-1.5, 1.5))
                  for j in range(4)] for i in range(4)]
            p = (rng.uniform(-0.5, 3.5), rng.uniform(-0.5, 3.5), rng.uniform(-2.0, 2.0))
            u, v = newton_point_inversion(P, p, n_grid=10)
            d = norm(sub(patch_point(P, u, v), p))
            self.assertLessEqual(d, dense_min(P, p, 100) + 1e-9)
            self.assertLessEqual(d, dense_min(P, p, 10) + 1e-9)
            self.assertTrue(kkt_holds(P, p, u, v))


if __name__ == "__main__":
    unittest.main()

History

Newton's method for the foot point on a parametric curve or surface is older than any single source. Piegl and Tiller gave the form used in most NURBS libraries in The NURBS Book (first edition 1995, second edition 1997), with the start from evenly spaced samples and the three stopping tests. Patrikalakis and Maekawa (2002) listed it with implicitization, subdivision and distance function methods for point and surface problems. Ma and Hewitt (2003) replaced the sampled start by a start from the subdivided control net, to make the choice of the basin more reliable.

References

  1. Les Piegl and Wayne Tiller, The NURBS Book, second edition, Springer, 1997, Chapter 6, Section 6.1, Point inversion and projection for curves and surfaces, pages 229 to 234 (the Newton iteration on the two equations, the start point from evenly spaced samples, the three stopping tests, and the clamping or wrapping of the parameters)
  2. Nicholas M. Patrikalakis and Takashi Maekawa, Shape Interrogation for Computer Aided Design and Manufacturing, Springer, 2002, Chapter 5, Section 5.5.2.2, Newton's method, and Section 5.5.2.3, bounding box and subdivision followed by minimization
  3. Ying Liang Ma and W. T. Hewitt, Point inversion and projection for NURBS curve and surface, control polygon approach, Computer Aided Geometric Design 20(2), 79 to 99, 2003, the whole paper (the failures of a start point taken from samples, and a start point from the subdivided control net)

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