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
- Model
- Real RAM
- Properties
- deterministicnot exactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Les Piegl, Wayne Tiller, 1997
Newton point inversion finds the parameters of the point of a parametric surface nearest to a given point , by Newton's method on the two first order equations and . It starts from the best sample of a coarse grid of parameters and stops when the point is reached, when the vector 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 on , given by its control net, a point , a grid size , and two tolerances: for distances in space and for cosines. The output is a parameter pair 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 , and . The squared distance has gradient and half Hessian
which is the Jacobian of . At a foot point , in terms of the fundamental forms, so is singular exactly when is a center of principal curvature of the foot point.
The algorithm
NEWTON-INVERT(r, p, n, ε1, ε2, kmax)- 1
(u, v) ← the grid point (i/n, j/n), 0 ≤ i, j ≤ n, with the least D = |r − p|² - 2
repeat at most kmax times - 3
evaluate 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 - 4
if |w| ≤ ε1 then return (u, v) ▷ point coincidence - 5
if, 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 - 6
H ← the half Hessian above - 7
δ ← −A⁻¹ (f, g) on the parameters not frozen, with A = H if H is positive definite and A = I otherwise - 8
λ ← 1; while D(clamp((u, v) + λδ)) > D(u, v): λ ← λ/2; (u', v') ← clamp((u, v) + λδ) - 9
if |(u' − u) r_u + (v' − v) r_v| ≤ ε1 then return (u', v') ▷ the point no longer moves - 10
return (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 is not positive definite, line L7 uses the first fundamental form , 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 . 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 .
Example
Take the bicubic patch with control points , , where and all other . Since the and coordinates of the net are evenly spaced, , a bump of height . Project with .
The grid samples have distances from (at the center) to , so line L1 starts at . There , and , so the first step is .
| iteration | |||||
|---|---|---|---|---|---|
| 0 | |||||
| 1 | |||||
| 2 | |||||
| 3 | |||||
| 4 |
Line L5 stops at iteration . The residual is roughly squared at each step: , , , , with ratios of about , and . The foot point is , and is a multiple of , so is on the normal line. The point lies on the diagonal because and the patch are symmetric about the plane . A grid gives 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 never increases: the answer is never worse than the best grid sample. Near an interior foot point at which and , a strict local minimum with off the focal surface, the iterates take full Newton steps and , with for the Lipschitz constant of . This is the standard local estimate for Newton's method, proved in the file. Last, if every point whose value of is within of the global minimum lies in that quadratic basin, a grid with spacing , for a bound on , makes the method return the global minimum.
What is not proved is that a given grid is fine enough: depends on the second best local minimum, which the method does not know. On random bicubic patches, with control points jittered by up to around a grid, heights in and in the box , the answer was worse than a grid in of cases for , in of for , and in none of for . 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 be a regular patch of class on the box , let be a point, and let . Write , , and , so that . Let be half the Hessian of , the matrix of line L6, and let be the first fundamental form. The proof uses exact arithmetic. The implementation accepts a step shorter than in space without the test of line L8, to stop rounding from blocking the last Newton steps; that device changes nothing below.
Call a first order point if the conditions of the box hold: for each parameter, either its derivative ( for , for ) is zero, or the parameter is on an edge and its derivative points out of the box ( and , or and , and the same for with ). Every local minimum of on 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 , that is, the cosine of the angle between and is at most , and the same for . A point returned at line L4 is within of .
Proof. These are the tests of lines L4 and L5.
Claim 2 (descent). If is not a first order point, the direction of line L7 satisfies , and a step of length along stays in for all small . So the halving loop of line L8 ends with .
Proof. Let be the set of parameters that are not frozen. A frozen parameter has its component of set to . On , the direction is for a positive definite matrix : the Hessian block when it is positive definite, otherwise the block of , which is positive definite because is regular. Then unless . A component that points out of the box at a parameter on an edge is set to zero next. If the result still has , it is kept. Otherwise the code takes the fallback on , with , for which unless on , which, with the frozen parameters, makes 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 points into the box as well. For small no component is clamped, so , and halving reaches such a .
Claim 3 (no increase). The values of at the iterates do not increase, and the returned point has no larger than at the best sample of the start grid.
Proof. Line L8 accepts a new point only if does not increase, and by Claim 2 it finds one unless is a first order point, in which case line L5 has already returned.
Claim 4 (local quadratic convergence). Let be an interior point with at which is positive definite. By the second order test on the problem page, this holds exactly when and , where and are the principal curvatures, that is, when is a strict local minimum and is not on the focal surface. Then there are and such that from every with the iterates take full Newton steps, stay in the ball, and satisfy
Proof. Put , so . Since , is Lipschitz near with some constant . Choose so that the closed ball of radius about lies inside , and so that on the matrix is positive definite with , where . This is possible by continuity. On no parameter is on an edge, so nothing is frozen, and line L7 takes the Newton step . With and ,
By the fundamental theorem of calculus, , so the bracket has norm at most . Hence . Put .
It remains to show that line L8 accepts the full step. By Taylor's theorem and the positive definiteness of , there are and with for . Take . For the full step gives , so the new point is in the ball, and
because . So does not increase, line L8 keeps , and induction on gives the claim.
The constants , , and 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 be the global minimizer and assume it satisfies Claim 4 with radius . Let bound on and let be such that every with lies within of . If the grid spacing satisfies , the method converges to .
Proof. Some grid point lies within half a diagonal of a grid cell, , of . By the mean value theorem . The best sample has , so , and Claim 4 applies.
can be bounded from the control net, since and the derivative nets bound and by the convex hull property. But 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.
Complexity
Let the patch have control points for bidegree . One evaluation of the point and its derivatives up to order two costs once the Bernstein values are known, which cost . Line L1 makes evaluations, time. Each iteration costs for line L3 and for each halving of line L8. Near the solution no halving happens, and quadratic convergence makes about once the error is below , so is to in double precision. The total is time and extra space. For NURBS each evaluation costs after a search for the knot span, which is for 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 is indefinite. The guards remove both failures at the cost of one extra evaluation per step.
- Curves. For a curve the iteration is , 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 , , from gives the Gauss-Newton algorithm for the least squares problem . It needs no second derivatives. It converges quadratically for point inversion, where at the solution and the dropped terms vanish there, and only linearly when 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 , below the top, the center is a grid point for even and satisfies exactly, by symmetry. Line L5 returns it at once with distance . But there , and , so the center is not a minimum, it is a local maximum of the distance. The true minimum is at and its three mirror images , , . An odd does not help: its best sample lies on the diagonal , the iterates stay on it by symmetry, and they end at near , a saddle of the distance. The smallest grid that finds the minimum is . A second order check at line L5 catches both cases.
- Near the focal surface. When is near , 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 and on only to about .
- Singular parametrizations. At a pole of a sphere or the apex of a cone, , the zero cosine test divides by zero, and 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. is a distance and must match the size of the model. A value of 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.
# 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
- 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)
- 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
- 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.
| 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 BYMVEB Edit this page History Report an error Markdown