Algorithmadvanced
Levin's quadric intersection method
Also called Levin pencil method, quadric surface intersection.
Intersects two quadrics by finding a ruled quadric in their pencil, parameterizing it, and solving a quadratic along each ruling, after Levin in 1976.
- Time
- O(N) worst
- Space
- O(N) extra
- Where
- N = the number of sample values of the ruling parameter u
- Model
- Real RAM
- Properties
- deterministicnot exactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Joshua Levin, 1976
Levin's method computes the intersection curve of two quadric surfaces and . Every surface of their pencil passes through the curve, and the method picks a member that is ruled in a simple way: it has a parametrization that is linear in . On each line of the other quadric becomes a quadratic equation in , so the curve is found by solving one quadratic per value of , in closed form.
In plain words
Two curved surfaces of the simplest kind, such as a sphere and a cylinder, cross along a curve. Mixing their equations in any proportion gives a new surface that still passes through that curve. Among these mixtures there is always one that is made of straight lines, like a sheet of paper that is bent but not stretched, or a saddle that can be built from straight sticks. The method finds that one.
Now walk along the straight lines of that surface, one by one. Each line meets the other surface in at most two points, and finding them is only a school quadratic equation. Collect the points for many lines and you have the whole curve, as a formula in the line number.
The only hard step is to find the right mixture, and that is a cubic equation.
The problem
A quadric is a surface in , stored as the symmetric matrix with upper left block , last column , so that for in homogeneous coordinates. Spheres, ellipsoids, cylinders, cones, paraboloids, hyperboloids and pairs of planes are quadrics. The input is two quadrics and that are not multiples of each other, and a list of sample values. The output is a description of their real intersection curve: a member of the pencil, its sheets , and for each sample the points of the curve on the line of , at most two per line, or the whole line when it lies in both quadrics. The intersection of two quadrics is a curve of degree at most , so this is the closed form case of surface surface intersection.
The algorithm
The quadratic part of a member is a symmetric matrix. The method needs a member whose quadratic part is singular and not semidefinite of rank 2, that is, not with one zero eigenvalue and two of the same sign. Such a member is a plane, two planes, a hyperbolic or parabolic cylinder, a hyperbolic paraboloid, or empty, a simple ruled quadric in Levin's sense. The members with a singular quadratic part are the roots of the cubic .
LEVIN(S, T, U)- 1
f ← the binary cubic det(α S_u + β T_u), from its values at four points - 2
C ← the real roots (α, β) of f on the unit circle, or, if f ≡ 0, a zero of the middle eigenvalue of α S_u + β T_u - 3
for each (α, β) ∈ C: R ← α S + β T - 4
G ← S if |β| ≥ |α| else T - 5
if R_u is singular and not semidefinite of rank 2: sheets ← the rulings p(u) + v d(u) of R = 0 from the principal axes of R_u, and stop - 6
for each sheet and each u ∈ U - 7
a ← dᵀ G_u d, b ← 2 d · (G_u p + g), c ← G(p); if a = b = c = 0, record the whole line - 8
for each real root v of a v² + b v + c = 0: output p(u) + v d(u) - 9
return R, its sheets, the points and the lines
Line L5 diagonalizes with the Jacobi eigenvalue algorithm, completes the squares, and reads the type of from the signs of the eigenvalues and the linear part. In the principal coordinates , a hyperbolic paraboloid is , and with , it becomes , linear in . A hyperbolic cylinder uses , and the free axis . A parabolic cylinder uses and its free axis as . A plane uses two directions in it, with along a direction on which is not constant. Line L4 keeps the generator that, with , still defines the same curve. The code also tries the zero of the middle eigenvalue after the roots of , as a guard against rounding. The proof does not need it.
Example
Intersect the sphere with the cylinder . The curve is Viviani's curve, a figure eight on the sphere. The quadratic parts are and , so
The root is the cylinder , whose quadratic part is semidefinite of rank 2, so line L5 rejects it. The double root gives
with quadratic part of rank 1, a parabolic cylinder. Its rulings are and : the line of is the line , in the direction of . Here , so , and
so , , , and , real for . The whole curve is
| points | ||
|---|---|---|
| , a double root, the crossing point of the figure eight | ||
| , a double root, the poles | ||
| none |
Each point satisfies both equations: at , and . The code finds the same member, scaled, and the same points; at the crossing point the two roots differ by about , the square root of the rounding error of .
Correctness
The full proof has three parts. First, a member as needed by line L5 always exists, which is Levin's theorem. Let be the middle eigenvalue of . It is continuous in , by Weyl's inequality, and the member at is minus the member at , so and has a zero . There the eigenvalues are with the middle one zero, so the quadratic part is singular and either indefinite or of rank at most 1. The point is a root of , so line L3 meets it, and if line L2 computes directly.
Second, a member of this kind is one of the simple ruled quadrics or empty, by the spectral theorem and completing squares, and its sheets cover its zero set, with every point on the line of a parameter that is an affine function of the point. Third, a common zero of and is a common zero of and and conversely, because line L4 picks the generator whose partner has a coefficient at least in . And is exactly the quadratic of line L7. So for each sample , the output is exactly the intersection on the line of . An empty member means an empty intersection.
What is not proved is the effect of rounding on the roots of and on the rank decisions. The tests check, for the example, for disjoint spheres, for parallel cylinders where , for one input of each member type, and for random pairs of quadrics through a common point, that every output point satisfies both quadrics to a relative residual of . They also check that more than points of the intersection, found independently by Newton steps, each lie on a sheet with a root of the quadratic at their , and that for random pencils some real root of gives a simple ruled member.
Proof: Every pencil of two quadrics holds a member that is a plane, two planes, a hyperbolic or parabolic cylinder, a hyperbolic paraboloid or empty, and its rulings reduce the intersection to quadratic equationsfull
A quadric is a nonzero real symmetric matrix , with for , . Write for its upper left block, the quadratic part, for its linear part and , so that . The input is two quadrics and that are not proportional, and the pencil is the set of members with . Every member is a nonzero matrix. Call a symmetric matrix semidefinite of rank 2 if it has exactly one eigenvalue and the other two have the same sign.
Claim 1 (a member with a good quadratic part). Put with eigenvalues . There is a with . The quadratic part of the member is singular and is not semidefinite of rank 2.
Proof. By Weyl's inequality, for symmetric and , so each is a continuous function of . Since , the eigenvalues at are , so . Either , or changes sign on and vanishes at some by the intermediate value theorem. At the eigenvalues are , so is singular. If or , it has rank at most . Otherwise and it is indefinite. In neither case is it semidefinite of rank 2.
Consequence for lines L1 to L3. Let , a binary form of degree . If is not the zero form, the point is one of its real projective roots, since is singular. Line L2 lists all real projective roots: it finds the roots of for and of for , which together cover every direction . So the loop of line L3 meets a member that passes the test of line L5. If is the zero form, line L2 finds itself, by bisection on the sign of , which keeps an interval at whose ends has opposite signs, and so converges to a zero of the continuous function .
Claim 2 (the zero set and its sheets). Let be a member whose quadratic part is singular and not semidefinite of rank 2, with linear part and constant . Then the zero set is a hyperbolic paraboloid, a hyperbolic cylinder, two intersecting planes, a parabolic cylinder, two parallel planes, one plane, or empty. Each nonempty case is the union of the sheets of line L5, each sheet is a map with , every point of the sheet satisfies , and every point of lies on a sheet at the parameter that the sheet assigns to .
Proof. By the spectral theorem, with an orthonormal basis . Write .
Rank 2. Let be the nonzero eigenvalues, which have opposite signs by the hypothesis, and the null vector. Put , , the center , and . The map is an affine bijection between and , and completing the squares gives
If , put and . Then , and exactly when . So is a hyperbolic paraboloid, and it is the image of with the point with and : moving along adds to and to , and to . A point of lies on the line of , which is affine in , at .
If and , then does not depend on , and means with . So and , that is and , and is free. is a hyperbolic cylinder, the image of for , and a point lies on the line of .
If and , then , and is the two planes and through , with normals and .
Rank 1. Let with unit vector , put , , , which is orthogonal to , and . Then , and . If , put , and , so that is orthonormal and with . Then exactly when , so is a parabolic cylinder, the image of with , and a point lies on the line of . If , then , and is the two planes when , the one plane when , and empty otherwise.
Rank 0. Then . If , is the plane through with normal . If , then because , and is empty.
A plane through with unit normal is one sheet: line L5 picks a unit vector in the plane and puts , so is an orthonormal basis of the plane, , and a point of the plane lies on the line of at .
The member found in Claim 1 is nonzero, so Claim 2 applies to it. This is the theorem of Levin, in the form given by Dupont, Lazard, Lazard and Petitjean (Theorem 3.1): the pencil of two distinct quadrics contains a simple ruled quadric or the empty set. If is empty, then and have no common real point, since every common zero of and is a zero of every member; so line L5 returns no sheets and the output is correctly empty.
Claim 3 (the quadratic on a ruling). Let line L4 choose if and otherwise. Then , and for every line , with , and , where is the linear part of .
Proof. If , then and , so exactly when . The other case is the same with the roles of and exchanged. The formula follows from expanding and using the symmetry of .
Conclusion. By Claims 2 and 3, for a sample of a sheet, the points of on the line are exactly the points at the real roots of , or the whole line when . Lines L7 and L8 return these. Every point of is on some sheet at the parameter that the sheet assigns to it, so it is returned whenever that is a sample. With exact arithmetic the output is therefore exactly the intersection restricted to the sampled lines.
What is not proved is the effect of rounding: the roots of are found in floating point, the rank and signs of the eigenvalues are decided with a relative tolerance of , and a double root is found only to about the square root of the rounding error. The tests measure the residuals of the output points in both quadrics, and check, for points of the intersection found independently by Newton steps, that each lies on a sheet and that its value of is a root of the quadratic of its line.
Complexity
All matrices have fixed size. Line L1 takes four determinants, line L2 finds at most three roots of a cubic by bisection, or runs a bisection on with one eigenvalue problem per step, and line L5 one Jacobi eigenvalue computation per candidate. This is work for a fixed precision. Each sample costs for the quadratic, so the total is time for samples, and space for the output.
The output is more than a set of points: the curve is with , a closed form in that can be evaluated anywhere. The points where split the axis into intervals on which the curve has a fixed number of branches.
Properties
- Closed form. The curve is given by a formula with one square root of a function of of low degree, polynomial for a paraboloid or a parabolic cylinder, and no iteration on the curve itself.
- Complete for each line. Every intersection point on a sampled line is found, and an empty member proves that the intersection is empty.
- Not rational. The square root makes the parametrization irrational even when a rational one exists, for example when the curve is singular or splits into conics and lines.
- Algebraic numbers. The member comes from a root of a cubic and the sheets from square roots of eigenvalues. In exact arithmetic the numbers grow fast, and in floating point the classification of the member can be wrong near a type boundary.
Variants and improvements
- Elliptic cylinders. An elliptic cylinder is also ruled, by lines parallel to its axis, and a parametrization of the ellipse gives a sheet linear in . The method of this page does not use it, because the theorem does not need it.
- Enhanced versions. Wang, Goldman and Tu (2003) added a classification of the curve in the singular and reducible cases, where it can be given by rational functions.
- Near optimal parametrizations. Dupont, Lazard, Lazard and Petitjean work in projective space with exact arithmetic and find a member with the smallest possible number of square roots in its coefficients. In the generic case their parametrization has at most one square root more than needed.
- Geometric special cases. Many modelers intersect natural quadrics, such as planes, spheres, cylinders and cones, by special geometric formulas, which are faster and more stable for those cases.
- General surfaces. For surfaces of higher degree no member with a linear parametrization need exist. Then algebraic surface intersection or implicitization followed by substitution are the analytic alternatives.
When to use it
Use it for the intersection of two quadric faces in a solid modeler, where the inputs are often planes, spheres, cylinders and cones, and a closed form curve with all its branches is wanted. It also gives the number of branches over each interval of , from the sign of . For two natural quadrics in special position, prefer the geometric formulas, and for exact results with rational input, prefer the projective method of Dupont and others.
Pitfalls
- Wrong type near a boundary. In floating point a member with a nearly zero eigenvalue can be classified as the wrong type, for example a nearly parabolic cylinder as a hyperbolic one, and then the sheets are wrong. Use a tolerance relative to the size of the matrix, and prefer members whose eigenvalues are well separated from zero.
- Double roots. At a tangency or a crossing point of the curve, is zero and rounding makes it slightly negative or positive. Clamp small negative values to zero, and expect the two branches to separate by about the square root of the rounding error.
- The wrong partner. If is almost a multiple of and the code uses as the partner, the two equations are almost the same, and the points are poorly fixed. Line L4 avoids this by taking the generator with the smaller coefficient in .
- Lines of the curve. When the curve contains a line of a sheet, for one value of only, and sampling misses it. A curve that contains a line is reducible, and the exact methods detect such cases from the multiple roots of .
- The sampling in u. Near the ends of a branch, where goes to zero, the points crowd in but spread in space, like . Refine the samples there, or use the ends as extra samples.
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/levin-quadric-intersection/. The authors are listed in prov/NA927X.jsonl.
"""Levin's pencil method for the intersection of two quadrics.
A quadric is a symmetric 4 x 4 matrix Q, with the surface X^T Q X = 0 for
X = (x, y, z, 1). Its upper left 3 x 3 block Q_u is the quadratic part, the
vector g = (Q[0][3], Q[1][3], Q[2][3]) the linear part, so that
Q(x) = x^T Q_u x + 2 g . x + Q[3][3].
The method finds a member R = alpha S + beta T of the pencil whose quadratic
part is singular and not semidefinite of rank 2. Its zero set is a plane, two
planes, a hyperbolic or parabolic cylinder, a hyperbolic paraboloid, or empty,
and it has sheets x = p(u) + v d(u), linear in v. On each line of a sheet the
partner quadric G (S or T) is a quadratic a v^2 + b v + c, whose real roots
give the points of the intersection.
"""
from math import cos, pi, sin, sqrt
from si1geom import add, cross, det, dot, jacobi_eigen, norm, real_roots, scale, solve, sub
TOL = 1e-9
def quadric_value(Q, x):
X = (x[0], x[1], x[2], 1.0)
return sum(Q[i][j] * X[i] * X[j] for i in range(4) for j in range(4))
def _upper(Q):
return [[Q[i][j] for j in range(3)] for i in range(3)]
def _lin(Q):
return (Q[0][3], Q[1][3], Q[2][3])
def _combo(a, S, b, T):
return [[a * S[i][j] + b * T[i][j] for j in range(4)] for i in range(4)]
def _mat_vec(A, x):
return tuple(A[i][0] * x[0] + A[i][1] * x[1] + A[i][2] * x[2] for i in range(3))
def _unit(x):
return scale(1.0 / norm(x), x)
def _normalized(Q):
m = max(abs(float(Q[i][j])) for i in range(4) for j in range(4))
return [[float(Q[i][j]) / m for j in range(4)] for i in range(4)]
class Sheet:
"""One sheet x = point(u) + v * direction(u) of the ruled member, with
param(x) the value of u of a point x on the sheet."""
def __init__(self, kind, point, direction, param):
self.kind = kind
self.point = point
self.direction = direction
self.param = param
def pencil_cubic(S, T):
"""Coefficients c0, c1, c2, c3 of f(1, lam) = det(S_u + lam T_u)."""
nodes = [-1.0, 0.0, 1.0, 2.0]
vals = [det([[S[i][j] + t * T[i][j] for j in range(3)] for i in range(3)]) for t in nodes]
return solve([[t ** k for k in range(4)] for t in nodes], vals)
def middle_eigenvalue_zero(S, T):
"""A point (cos th, sin th) where the middle eigenvalue of the quadratic
part of the member changes sign. It exists because the member at th + pi
is minus the member at th."""
def mid(th):
return jacobi_eigen(_upper(_combo(cos(th), S, sin(th), T)))[0][1]
lo, hi = 0.0, pi
flo = mid(lo)
if flo == 0:
return (1.0, 0.0)
for _ in range(64):
m = 0.5 * (lo + hi)
fm = mid(m)
if (fm > 0) == (flo > 0):
lo, flo = m, fm
else:
hi = m
th = 0.5 * (lo + hi)
return (cos(th), sin(th))
def pencil_candidates(S, T, c):
"""The real projective roots of f(alpha, beta) = det(alpha S_u + beta T_u),
with c the coefficients of f(1, lam), as unit vectors, or the middle
eigenvalue zero when f vanishes."""
if max(abs(x) for x in c) <= TOL:
return [middle_eigenvalue_zero(S, T)]
raw = [(1.0, t) for t in real_roots(c, -1.0, 1.0)]
raw += [(t, 1.0) for t in real_roots(list(reversed(c)), -1.0, 1.0)]
out = []
for a, b in raw:
n = sqrt(a * a + b * b)
a, b = a / n, b / n
if all(abs(a * b2 - b * a2) > 1e-7 for a2, b2 in out):
out.append((a, b))
return out
def _plane_sheet(x0, nrm, G):
"""The plane through x0 with normal nrm, with the ruling direction chosen
so that G restricted to a ruling is not constant whenever possible."""
nrm = _unit(nrm)
e = _unit(cross(nrm, (1.0, 0.0, 0.0)) if abs(nrm[0]) < 0.9 else cross(nrm, (0.0, 1.0, 0.0)))
f = cross(nrm, e)
Gu = _upper(G)
def q(d):
return dot(d, _mat_vec(Gu, d))
d = max([e, f, _unit(add(e, f))], key=lambda w: abs(q(w)))
if abs(q(d)) <= TOL:
grad = add(_mat_vec(Gu, x0), _lin(G))
gp = sub(grad, scale(dot(grad, nrm), nrm))
d = _unit(gp) if norm(gp) > TOL else e
eu = cross(nrm, d)
return Sheet("plane", lambda u: add(x0, scale(u, eu)), lambda u: d, lambda x: dot(sub(x, x0), eu))
def ruled_sheets(R, G):
"""Return (kind, sheets) for the member R, or None when its quadratic part
is regular or semidefinite of rank 2. kind is 'empty' when R = 0 has no
real point."""
vals, vecs = jacobi_eigen(_upper(R))
vecs = [tuple(v) for v in vecs]
big = max(1.0, max(abs(v) for v in vals))
zero = [abs(v) <= TOL * big for v in vals]
rank = 3 - sum(zero)
r, c = _lin(R), R[3][3]
if rank == 3:
return None
if rank == 2:
i0 = zero.index(True)
ia, ib = [i for i in range(3) if i != i0]
if vals[ia] * vals[ib] > 0:
return None
if vals[ia] < 0:
ia, ib = ib, ia
ma, mb = vals[ia], vals[ib]
ea, eb, e3 = vecs[ia], vecs[ib], vecs[i0]
ra, rb, r3 = dot(r, ea), dot(r, eb), dot(r, e3)
center = add(scale(-ra / ma, ea), scale(-rb / mb, eb))
cp = c - ra * ra / ma - rb * rb / mb
sa, sb = sqrt(ma), sqrt(-mb)
def at(p, q, w):
return add(center, add(scale(p / sa, ea), add(scale(q / sb, eb), scale(w, e3))))
def pmq(x):
y = sub(x, center)
return sa * dot(y, ea) - sb * dot(y, eb)
if abs(r3) > TOL * big:
# p^2 - q^2 + 2 r3 w + cp = 0 with u = p - q and v = p + q
sheet = Sheet("hyperbolic paraboloid",
lambda u: at(u / 2, -u / 2, -cp / (2 * r3)),
lambda u: add(add(scale(0.5 / sa, ea), scale(0.5 / sb, eb)), scale(-u / (2 * r3), e3)),
pmq)
return "hyperbolic paraboloid", [sheet]
if abs(cp) > TOL * big:
k = -cp # p^2 - q^2 = k, with p - q = t and p + q = k / t
sheet = Sheet("hyperbolic cylinder",
lambda t: at((t + k / t) / 2, (k / t - t) / 2, 0.0),
lambda t: e3,
pmq)
return "hyperbolic cylinder", [sheet]
n1 = sub(scale(sa, ea), scale(sb, eb))
n2 = add(scale(sa, ea), scale(sb, eb))
return "intersecting planes", [_plane_sheet(center, n1, G), _plane_sheet(center, n2, G)]
if rank == 1:
i1 = zero.index(False)
m1, e1 = vals[i1], vecs[i1]
r1 = dot(r, e1)
c0 = scale(-r1 / m1, e1)
cp = c - r1 * r1 / m1
rn = sub(r, scale(r1, e1))
n = norm(rn)
if n > TOL * big:
g = scale(1.0 / n, rn)
h = cross(e1, g)
sheet = Sheet("parabolic cylinder",
lambda u: add(c0, add(scale(u, e1), scale(-(m1 * u * u + cp) / (2 * n), g))),
lambda u: h,
lambda x: dot(sub(x, c0), e1))
return "parabolic cylinder", [sheet]
if abs(cp) <= TOL * big:
return "double plane", [_plane_sheet(c0, e1, G)]
s2 = -cp / m1
if s2 < 0:
return "empty", []
s = sqrt(s2)
return "parallel planes", [_plane_sheet(add(c0, scale(s, e1)), e1, G),
_plane_sheet(add(c0, scale(-s, e1)), e1, G)]
n = norm(r)
if n <= TOL * big:
return "empty", []
return "plane", [_plane_sheet(scale(-c / (2 * n * n), r), r, G)]
def ruling_quadratic(G, p, d):
"""G(p + v d) = a v^2 + b v + c."""
Gu = _upper(G)
a = dot(d, _mat_vec(Gu, d))
b = 2 * dot(d, add(_mat_vec(Gu, p), _lin(G)))
return a, b, quadric_value(G, p)
def ruling_roots(G, p, d):
"""Real roots v of G(p + v d) = 0, or None when the whole line lies in G."""
a, b, c = ruling_quadratic(G, p, d)
m = max(abs(a), abs(b), abs(c))
if m <= TOL:
return None
if abs(a) > 1e-12 * m:
disc = b * b - 4 * a * c
if disc < 0:
if disc < -1e-12 * (b * b + abs(4 * a * c)):
return []
disc = 0.0
q = -0.5 * (b + (sqrt(disc) if b >= 0 else -sqrt(disc)))
if q == 0:
return [0.0]
return sorted({q / a, c / q})
if abs(b) > 1e-12 * m:
return [-c / b]
return []
def levin_intersection(S, T, us):
S, T = _normalized(S), _normalized(T)
c = pencil_cubic(S, T) # @line L1
cands = pencil_candidates(S, T, c) # @line L2
cands.append(middle_eigenvalue_zero(S, T)) # a safeguard against rounding; the proof needs no more
for alpha, beta in cands: # @line L3
R = _combo(alpha, S, beta, T)
G = S if abs(beta) >= abs(alpha) else T # @line L4
found = ruled_sheets(R, G) # @line L5
if found is not None:
break
kind, sheets = found
points, lines = [], []
for sheet in sheets: # @line L6
for u in us:
if sheet.kind == "hyperbolic cylinder" and u == 0:
continue
p, d = sheet.point(u), sheet.direction(u)
roots = ruling_roots(G, p, d) # @line L7
if roots is None:
lines.append((p, d))
continue
for v in roots: # @line L8
points.append(add(p, scale(v, d)))
return {"member": R, "kind": kind, "partner": G, "sheets": sheets, "points": points, "lines": lines} # @line L9
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_levin_quadric_intersection.py 172 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/levin-quadric-intersection/. The authors are listed in prov/NA927X.jsonl.
import random
import unittest
from math import sqrt
from levin_quadric_intersection import (
_normalized, _upper, levin_intersection, pencil_candidates, pencil_cubic,
quadric_value, ruled_sheets, ruling_roots, _combo,
)
from si1geom import add, dot, jacobi_eigen, norm, scale, solve, sub
SPHERE2 = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, -4]]
US = [i / 20 for i in range(-60, 61)]
def residual(Q, p):
return abs(quadric_value(_normalized(Q), p)) / (1 + dot(p, p))
def gradient(Q, x):
return tuple(2 * (sum(Q[i][j] * x[j] for j in range(3)) + Q[i][3]) for i in range(3))
def point_on_both(S, T, x, steps=60):
"""A point of S = T = 0 near x, by minimum norm Newton steps, or None."""
for _ in range(steps):
F = (quadric_value(S, x), quadric_value(T, x))
if max(abs(F[0]), abs(F[1])) < 1e-14:
return x
gs, gt = gradient(S, x), gradient(T, x)
try:
y = solve([[dot(gs, gs), dot(gs, gt)], [dot(gt, gs), dot(gt, gt)]], list(F))
except ZeroDivisionError:
return None
x = sub(x, add(scale(y[0], gs), scale(y[1], gt)))
if norm(x) > 50:
return None
return None
def covered(res, x):
"""True when x lies on a sheet of the member and the quadratic of its
ruling has a root at x, or the whole ruling is in both quadrics."""
G = res["partner"]
for sh in res["sheets"]:
u = sh.param(x)
if sh.kind == "hyperbolic cylinder" and abs(u) < 1e-12:
continue
p, d = sh.point(u), sh.direction(u)
v = dot(sub(x, p), d) / dot(d, d)
if norm(sub(add(p, scale(v, d)), x)) > 1e-7 * (1 + norm(x)):
continue
roots = ruling_roots(G, p, d)
if roots is None or any(abs(r - v) <= 1e-6 * (1 + abs(v)) for r in roots):
return True
return False
def random_pair(rng):
"""Two random quadrics through a common random point."""
A = [[0.0] * 4 for _ in range(4)]
B = [[0.0] * 4 for _ in range(4)]
for i in range(4):
for j in range(i, 4):
A[i][j] = A[j][i] = rng.uniform(-1, 1)
B[i][j] = B[j][i] = rng.uniform(-1, 1)
x0 = (rng.uniform(-1, 1), rng.uniform(-1, 1), rng.uniform(-1, 1))
A[3][3] -= quadric_value(A, x0)
B[3][3] -= quadric_value(B, x0)
return A, B, x0
class TestLevin(unittest.TestCase):
def test_example_viviani(self):
T = [[1, 0, 0, -1], [0, 1, 0, 0], [0, 0, 0, 0], [-1, 0, 0, 0]]
res = levin_intersection(SPHERE2, T, [-2, -1, 0, 1, 2])
self.assertEqual(res["kind"], "parabolic cylinder")
# the member is a multiple of S - T = z^2 + 2x - 4
R = res["member"]
k = R[0][3]
self.assertGreater(abs(k), 0.1)
self.assertAlmostEqual(R[2][2] / k, 1.0)
self.assertAlmostEqual(R[3][3] / k, -4.0)
self.assertAlmostEqual(R[0][0] / k, 0.0)
for p in res["points"]:
self.assertLess(residual(SPHERE2, p), 1e-12)
self.assertLess(residual(T, p), 1e-12)
h = sqrt(3) / 2
for want in ((1.5, h, 1.0), (1.5, -h, 1.0), (1.5, h, -1.0), (1.5, -h, -1.0), (2.0, 0.0, 0.0), (0.0, 0.0, 2.0)):
self.assertLess(min(norm(sub(p, want)) for p in res["points"]), 1e-5)
def test_disjoint_spheres(self):
# radius 1 about (3, 0, 0), against radius 2 about the origin
T = [[1, 0, 0, -3], [0, 1, 0, 0], [0, 0, 1, 0], [-3, 0, 0, 8]]
res = levin_intersection(SPHERE2, T, US)
self.assertEqual(res["kind"], "plane")
self.assertEqual(res["points"], [])
def test_parallel_cylinders_vanishing_cubic(self):
S = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 0], [0, 0, 0, -1]]
T = [[1, 0, 0, -1], [0, 1, 0, 0], [0, 0, 0, 0], [-1, 0, 0, 0]]
self.assertLess(max(abs(c) for c in pencil_cubic(_normalized(S), _normalized(T))), 1e-12)
res = levin_intersection(S, T, [-1, 0, 1])
self.assertEqual(res["kind"], "plane")
self.assertEqual(len(res["points"]), 6)
for p in res["points"]:
self.assertAlmostEqual(p[0], 0.5)
self.assertAlmostEqual(abs(p[1]), sqrt(3) / 2)
def test_each_kind_of_member(self):
cases = {
"hyperbolic cylinder": [[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, 0, 0], [0, 0, 0, -1]],
"intersecting planes": [[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]],
"parallel planes": [[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, -1]],
"double plane": [[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]],
"hyperbolic paraboloid": [[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, 0, -0.5], [0, 0, -0.5, 0]],
}
rng = random.Random(3)
for kind, S in cases.items():
res = levin_intersection(S, SPHERE2, US)
self.assertEqual(res["kind"], kind)
self.assertTrue(res["points"])
for p in res["points"]:
self.assertLess(residual(S, p), 1e-11)
self.assertLess(residual(SPHERE2, p), 1e-11)
for _ in range(20):
x = (rng.uniform(-2, 2), rng.uniform(-2, 2), rng.uniform(-2, 2))
y = point_on_both(_normalized(S), _normalized(SPHERE2), x)
if y is not None:
self.assertTrue(covered(res, y), (kind, y))
def test_pencil_has_a_simple_ruled_root(self):
# the theorem: some real root of the cubic gives a member that is not
# semidefinite of rank 2, without the safeguard
rng = random.Random(11)
for _ in range(300):
A, B, _x0 = random_pair(rng)
S, T = _normalized(A), _normalized(B)
cands = pencil_candidates(S, T, pencil_cubic(S, T))
self.assertTrue(cands)
good = 0
for a, b in cands:
R = _combo(a, S, b, T)
vals = jacobi_eigen(_upper(R))[0]
self.assertLess(min(abs(v) for v in vals), 1e-8)
good += ruled_sheets(R, S) is not None
self.assertGreater(good, 0)
def test_random_points_satisfy_both_and_all_are_found(self):
rng = random.Random(7)
found = 0
for _ in range(60):
A, B, x0 = random_pair(rng)
res = levin_intersection(A, B, US)
for p in res["points"]:
self.assertLess(residual(A, p), 1e-9)
self.assertLess(residual(B, p), 1e-9)
self.assertTrue(covered(res, x0))
S, T = _normalized(A), _normalized(B)
for _ in range(4):
x = add(x0, (rng.uniform(-1, 1), rng.uniform(-1, 1), rng.uniform(-1, 1)))
y = point_on_both(S, T, x)
if y is not None:
found += 1
self.assertTrue(covered(res, y))
self.assertGreater(found, 100)
if __name__ == "__main__":
unittest.main()
History
Levin (1976) gave the pencil method as part of an algorithm to draw pictures of solids bounded by quadric patches, and extended it in 1979 into a method for the intersection of any two quadrics, with an analysis of the pencil. His method was for a long time the only general one. Later work studied its weak points: the classification by Wilf and Manor with the Segre characteristic, the enhancement of Wang, Goldman and Tu (2003) for singular and reducible curves, and the exact projective algorithm of Dupont, Lazard, Lazard and Petitjean, which gives near optimal parametrizations and removes the numerical trouble of the floating point method.
References
- Joshua Levin, A parametric algorithm for drawing pictures of solid objects composed of quadric surfaces, Communications of the ACM 19(10), 555 to 563, 1976, the whole paper (the pencil of two quadrics, a member with a parametrization linear in one parameter, and the quadratic equation along each line of it)
- L. Dupont, D. Lazard, S. Lazard and S. Petitjean, Near-optimal parameterization of the intersection of quadrics, I, The generic algorithm, INRIA Research Report 5667, 2005, Section 3, Levin's pencil method (Theorem 3.1, the existence of a simple ruled quadric or the empty set in the pencil, the steps of the method, and the sources of numerical trouble)
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 NA927X Edit this page History Report an error Markdown