Algorithmadvanced
Algebraic surface intersection
Also called implicit-parametric surface intersection.
Substitutes a parametric surface into the implicit equation of the other, so the intersection becomes a plane algebraic curve in the parameter domain that is then traced.
- Time
- O(T k^3 m^2 n^2 + B b D^3 + A S b D^2) worst
- Space
- O(d D^2 + A S) extra
- Where
- A = the number of arcs; B = the number of boxes; D = the larger degree of the substituted polynomial; S = the samples per arc; T = the number of its terms; b = the bisection steps; d = the depth limit; k = the degree of the implicit polynomial; m = the first degree of the patch; n = the second degree of the patch
- Model
- Real RAM
- Properties
- deterministicnot exactrecursive
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Nicholas M. Patrikalakis, P. V. Prakash, 1990
Algebraic surface intersection computes the curve where a parametric patch meets an implicit surface by substitution: is one polynomial in two unknowns, and its zero set in the parameter box is the intersection curve. The three dimensional problem becomes the problem of finding all branches of a plane algebraic curve. This page writes exactly in Bernstein form, subdivides the box until each piece is empty or holds a curve that is a graph over one parameter, and traces each piece. Unlike lattice evaluation and marching, it finds every closed loop, however small, and it boxes the singular points that it cannot trace.
In plain words
One surface is drawn by a formula with two numbers, like a map. The other is a rule that says which points are on it. Put the map formula into the rule, and you get one rule on the map: the crossing line is where this rule gives zero. Now the problem is flat, a curve on a square of paper.
To find all of that curve, cut the square into pieces. A piece where the rule is clearly positive everywhere, or clearly negative, holds no curve, and you drop it. A piece where the curve can only run left to right, never turning back, is easy: you find where it enters and leaves and follow it across. Any other piece is cut into four again. Only near a point where the curve crosses itself do the pieces become tiny, and those are reported as special.
The problem
The input is a tensor product Bézier patch of bidegree on , given by its control net, an implicit surface with a polynomial of degree , a depth limit and a number of samples per arc. Rational patches work the same way after multiplying by a power of the weight, see Variants.
The output is a set of polylines in the parameter box, with every vertex on the curve to the precision of a bisection, the closed ones repeated at the end, and a list of boxes of side that may hold a singular point of , where .
Since has degree and each coordinate of has bidegree , has bidegree at most . For a bicubic patch and a quadric that is .
The algorithm
ALGEBRAIC-INTERSECT(r, f, d, S)- 1
G ← the Bernstein coefficients of g = f ∘ r on Ω, computed exactly - 2
stack ← [(G, Ω, 0)] - 3
while stack is not empty: pop (G, Q, depth) - 4
if all G_ij > 0 or all G_ij < 0 then continue ▷ no curve in Q - 5
if all G_i,j+1 − G_ij have one strict sign, or all G_i+1,j − G_ij do then - 6
find the roots of g on the edges of Q, sort them along the free parameter, pair neighbors, trace each pair with S bisections, and continue if the count is even - 7
if depth < d then split Q and G into four by de Casteljau and push them with depth + 1 - 8
else report Q as a possible singular point - 9
chain the arcs at their common ends into curves - 10
return the curves and the reported boxes
Line L1 computes the products of the coordinate polynomials in the Bernstein basis by the product rule in each parameter, with rational numbers, so the sign tests of lines L4 and L5 are exact. Line L4 drops a box by the convex hull property: lies between the least and the largest coefficient. Line L5 tests the coefficients of a derivative, which are the differences of neighboring coefficients. If has a strict sign, each line meets the curve at most once in the box, so the curve there is a graph , with no loop and no turning point. Line L6 finds the edge points as roots of univariate polynomials, pairs them in order of , and computes points between the ends of each pair by bisection on the monotone function . An odd count, from a tangency to an edge or a point at a corner, sends the box to line L7. Line L7 is the de Casteljau algorithm at in each parameter.
Example
Take the bicubic bump , with control points , at the four inner points and elsewhere, and the plane . Then has degree , has bidegree , and its Bernstein coefficients are the control heights minus :
The signs are mixed, and both difference tables contain , so line L7 splits . The quarter has the coefficients
again mixed, with zero differences in the last row and column, so it is split as well, and so are the other three quarters. Of the boxes of side , the at the corners of have only negative coefficients and are dropped. The boxes along the edges of the inner square are monotone, and each holds one arc. For instance on the curve is a graph over from to . The boxes and its mirror images are split once more, and of their children are dropped and hold one arc each. In all, boxes are visited and arcs found, and line L9 chains them into one closed curve. With it has vertices, each with .
With the plane the curve is a loop of width in around the top. Lattice evaluation with lines in each direction misses it. Here the subdivision visits boxes and returns it as one closed curve. On the saddle cut by , the curve is the two lines and , which cross at a singular point. With the method returns four curves, each from an edge of to the reported boxes, and the four boxes of side around .
Correctness
The full proof has five parts. A box dropped by line L4 holds no point of the curve, because is a convex combination of its Bernstein coefficients. The differences that line L5 tests are positive multiples of the Bernstein coefficients of or , so a strict sign there means a strict sign of the derivative on the whole box. In such a box the curve is a graph over the other parameter, its ends are exactly the edge roots, and pairing them in sorted order gives the arcs, provided the edge roots are simple and the curve does not touch the box only at a corner. Together, the arcs and the boxes of line L8 cover the whole curve, and every closed loop is returned as a closed curve.
The last part is termination. If a box of side is split, then , and are all at most a constant times at every point of it, with constants computed from the coefficients of the derivatives on . So if the curve has no singular point, every box smaller than a positive number is decided, and only boxes around singular points reach the depth limit. The proof uses only Bernstein facts that it proves. What is not exact are the edge roots and the traced points, which are floating point bisections from exact coefficients. The tests check the substitution exactly with rational numbers, and check on random bicubic patches cut by planes and spheres that the number of times the polylines cross fixed parameter lines equals the number of sign changes of in samples on each line.
Proof: The subdivision of the substituted polynomial loses no piece of the intersection, pairs the boundary points of each monotone box correctly, and stops near every regular pointfull
Let be a polynomial patch of bidegree on and let be a polynomial of degree . Then is a polynomial of bidegree at most , and line L1 writes it in tensor product Bernstein form,
exactly, with rational coefficients. On a box the coefficients are those of in the local coordinates , . Line L7 obtains them by de Casteljau halving, which replaces each list of coefficients by averages of its entries, so every coefficient on is a convex combination of the coefficients on . Write .
Claim 1 (the convex hull bound). For every , . So a box excluded by line L4 holds no point of .
Proof. The Bernstein polynomials are nonnegative on and sum to , since . So the products are nonnegative and sum to , and is a convex combination of the . If all of them are positive, so is on , and the same for negative.
Claim 2 (the monotone test). The differences , which line L5 tests, are times the Bernstein coefficients of degree of on . So if they all have one strict sign, has that sign on all of . The same holds for .
Proof. Differentiating gives , and collecting terms gives . Since , the first statement follows, and Claim 1 applied to gives the second.
Claim 3 (the arcs of a monotone box). Let have a strict sign on , and assume that every root of on the bottom and top edges of is simple and that no point of is a corner of at which does not enter . Sort the points of on the boundary of by , as line L6 does, into . Then consists of exactly disjoint arcs, the th from to , and each is the graph of a continuous function over the interval between the values of its ends. The same holds with and exchanged.
Proof. Let and say . For each the function is strictly increasing, so it has at most one zero in , and it has one exactly when . Let be the set of such and the zero. By the implicit function theorem, which applies because , is continuous on , and is the graph of over .
The set is defined by two polynomial inequalities, so it is a finite union of disjoint closed intervals with . Over each interval the graph is an arc, and its two ends are its points at and . An end at is a point where or changes sign, so it is a root on the bottom or top edge, and conversely a simple root on the bottom or top edge is such a change of sign, so it is an end. An end at is the zero of on the left edge, and the same at . The assumption on the corners excludes , which would be an isolated point of at a corner. So the boundary points of on are exactly the ends, their values are , and two ends never share a value, because a line meets at most once. Sorting by and pairing neighbors gives the arcs.
The tracing of line L6 computes, for values between the ends of an arc, the zero by bisection on the monotone function . So every vertex of the output lies on to the bisection tolerance, and since is convex, every edge of the polyline lies in , as does the arc it replaces. The distance between them is at most the diagonal of , which is all that is proved about it.
Claim 4 (nothing is lost). Every point of lies in a box excluded by no test, that is, in a monotone box handled by line L6 or in a box of line L8. Under the assumptions of Claim 3 on every monotone box, the arcs of line L6 together with the boxes of line L8 cover , and line L9 chains the arcs into the components of outside the boxes of line L8.
Proof. The leaves of the subdivision cover . A leaf is excluded only by line L4, which holds no point of by Claim 1. In a monotone leaf, Claim 3 gives all of there as arcs. A point where two leaves meet that is on is the end of an arc in each leaf that enters, so the arcs that share an end are consecutive pieces of one component, and line L9 joins them. A closed component of is cut by the leaves into arcs whose ends join in a cycle, so it is returned as a closed curve, however small it is.
Claim 5 (termination near regular points). Let and be the largest absolute values of the Bernstein coefficients of and on , and put . Define and the same way from the second derivatives. If a box of side is split, then at every point of it,
Hence, if has no singular point in , that is, no point where , the number is positive, and no box of side less than is split, except for a box rejected at line L6 by the assumptions of Claim 3.
Proof. On , by Claim 2, , where is a coefficient of on , a convex combination of the coefficients on , so . The same holds in . Walking from to in at most steps in and steps in gives . Since and , on by Claim 1, for . So every coefficient is within of . If , all coefficients are positive and line L4 excludes , and the same for . The same argument for and shows that if or , line L5 finds a strict sign. A box that is split therefore has all three bounds at every point. If , some point of the box has one of the three ratios above , a contradiction. The minimum is attained because is compact, and it is exactly at a singular point of .
So, with no singular point and no tangency of to the lines and , the depth of the subdivision is at most , and boxes reach line L8 only around singular points or such tangencies. At a singular point every box that contains it is split, so with a depth limit line L8 returns the boxes of side that contain it, which isolates it.
Complexity
Line L1 makes, for each of the terms of , at most products of Bernstein arrays of size at most by arrays of size , which costs operations on rational numbers. Each box costs for the split, with , and for the sign tests. A monotone box costs for the roots on its four edges, and each arc for the tracing, with about bisection steps. With boxes and arcs, the total is operations. The proof of termination bounds the depth by when the curve has no singular point, so , a bound that is far from tight: boxes away from the curve are dropped early, and for a regular curve the number of boxes grows with its length divided by the box size. The stack is depth first, so it holds at most boxes per level, coefficients for the depth limit , and the output takes . The cost of the rational numbers grows with the depth, since each halving adds a factor of to the denominators.
Properties
- Complete. Every point of the curve is in a returned arc or a returned box, with the conditions of the proof. Small loops are not lost.
- Exact decisions. The tests that drop boxes and that find monotone boxes use exact rational arithmetic, so they are never wrong because of rounding.
- Isolates singular points. Boxes around a crossing of the curve reach the depth limit, so the method reports where it could not decide.
- Local work. Boxes are independent, and the work is spent near the curve.
Variants and improvements
- Characteristic points first. Patrikalakis and Prakash compute the border points, the turning points where or , and the singular points, and then split the box at them into parts that are traced one at a time. The monotone boxes of this page play the role of those parts: a box with a strict sign of holds no point where . The characteristic points can be found with the interval projected polyhedron method.
- Rational patches. For use the numerator , the homogenized at . It has the same zeros where .
- Marching on the plane curve. Trace the curve from the border and turning points with a predictor and corrector step in the plane, as in marching, using the characteristic points to guarantee that all branches are found.
- Two parametric patches. When both surfaces are parametric, the implicitization of one of them gives an implicit equation, and this method applies. The degree of the implicit form, up to , makes this practical only for low degrees.
- Quadrics. When both surfaces are quadrics, Levin's method gives a parametrization of the curve instead of a traced one.
When to use it
Use it when one surface is implicit, such as a plane, a quadric, a torus or an offset of one, and the other is a patch: plane sections for slicing and contouring, cuts by cylinders and spheres in machining, and Booleans between primitives and freeform faces. It is the method of choice when no loop may be lost. When both surfaces are freeform of high degree, use subdivision or marching instead.
Pitfalls
- Coefficient growth. The degree of is times that of the patch. A bicubic and a quartic, such as a torus, give bidegree , coefficients, and the rationals grow with the depth.
- Tangential intersections. Where the two surfaces touch, has a double zero along the curve, so , and all vanish there, and every box along the curve reaches the depth limit. The method then returns a chain of boxes, not a curve. See tangential surface intersection.
- Dyadic coincidences. A curve that passes through a corner of the dyadic subdivision without entering a box, or is tangent to a line , gives an odd count in a monotone box, and that box is split down to the depth limit. Symmetric test cases hit this often.
- Parameter space only. The curve is computed in the parameter box of . Points in space are , and a short distance in the box can be a long one in space where the patch is stretched.
- Floating point coefficients. Running the sign tests in floating point makes them unreliable when coefficients are near , which is exactly near the curve. Exact or interval arithmetic keeps line L4 from dropping a box that holds the curve.
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/algebraic-surface-intersection/. The authors are listed in prov/38DDQS.jsonl.
"""Intersection of a Bezier patch with an implicit algebraic surface.
The patch r(u, v) on [0, 1] x [0, 1] is given by its control net, the second
surface by a polynomial f(x, y, z), a dictionary that maps an exponent triple
(a, b, c) to the coefficient of x^a y^b z^c. Substituting r into f gives one
polynomial g(u, v) = f(r(u, v)), whose zero set in the parameter box is the
intersection curve. The code forms g in tensor product Bernstein form with
exact rational arithmetic, subdivides the box until each piece either holds no
zero of g, by the signs of its coefficients, or holds a curve that is a graph
over one parameter, by the signs of the coefficients of a derivative. In such
a piece the boundary points of the curve are paired in order and each arc is
traced by bisection. The arcs are chained into curves. Pieces smaller than
2^-max_depth that are neither are returned as candidates for singular points.
"""
from fractions import Fraction
from math import comb
from typing import Sequence
from si1geom import Vec, bernstein, pmul, ppow, pscale, padd, real_roots
Grid = list # a (p + 1) x (q + 1) list of lists of Bernstein coefficients
def bern_product(A: Grid, B: Grid) -> Grid:
"""Bernstein coefficients of the product of two tensor product polynomials."""
p, q, r, s = len(A) - 1, len(A[0]) - 1, len(B) - 1, len(B[0]) - 1
C = [[Fraction(0)] * (q + s + 1) for _ in range(p + r + 1)]
for a in range(p + 1):
for b in range(q + 1):
x = A[a][b] * comb(p, a) * comb(q, b)
if x == 0:
continue
for c in range(r + 1):
for d in range(s + 1):
if B[c][d] != 0:
C[a + c][b + d] += x * B[c][d] * comb(r, c) * comb(s, d)
return [[C[i][j] / (comb(p + r, i) * comb(q + s, j)) for j in range(q + s + 1)] for i in range(p + r + 1)]
def substitute(P: Sequence[Sequence[Vec]], f: dict) -> Grid:
"""Exact Bernstein coefficients of g = f(r(u, v)), of bidegree (k m, k n)."""
m, n = len(P) - 1, len(P[0]) - 1
coords = [[[Fraction(P[i][j][c]) for j in range(n + 1)] for i in range(m + 1)] for c in range(3)]
ones = [[Fraction(1)] * (n + 1) for _ in range(m + 1)]
k = max(sum(e) for e in f)
powers = [{0: [[Fraction(1)]]} for _ in range(3)]
def power(c: int, e: int) -> Grid:
if e not in powers[c]:
powers[c][e] = bern_product(power(c, e - 1), coords[c])
return powers[c][e]
G = [[Fraction(0)] * (k * n + 1) for _ in range(k * m + 1)]
for (a, b, c), coef in f.items():
T = bern_product(bern_product(power(0, a), power(1, b)), power(2, c))
for _ in range(k - a - b - c):
T = bern_product(T, ones)
cf = Fraction(coef)
for i in range(k * m + 1):
for j in range(k * n + 1):
G[i][j] += cf * T[i][j]
return G
def _halves(c: list) -> tuple:
left, right, cur = [c[0]], [c[-1]], list(c)
while len(cur) > 1:
cur = [(cur[i] + cur[i + 1]) / 2 for i in range(len(cur) - 1)]
left.append(cur[0])
right.append(cur[-1])
return left, right[::-1]
def _split(G: Grid) -> list:
"""The four quarters of G, in the order (low u, low v), (low u, high v), (high u, low v), (high u, high v)."""
M, N = len(G) - 1, len(G[0]) - 1
lo = [[None] * (N + 1) for _ in range(M + 1)]
hi = [[None] * (N + 1) for _ in range(M + 1)]
for j in range(N + 1):
a, b = _halves([G[i][j] for i in range(M + 1)])
for i in range(M + 1):
lo[i][j], hi[i][j] = a[i], b[i]
out = []
for H in (lo, hi):
rows = [_halves(H[i]) for i in range(M + 1)]
out.append([rows[i][0] for i in range(M + 1)])
out.append([rows[i][1] for i in range(M + 1)])
return out
def _strict_sign(vals) -> int:
vals = list(vals)
if all(x > 0 for x in vals):
return 1
if all(x < 0 for x in vals):
return -1
return 0
def _edge_roots(c: list) -> list:
"""Roots in [0, 1] of the univariate Bernstein polynomial with coefficients c."""
d = len(c) - 1
poly = [Fraction(0)]
for i, x in enumerate(c):
if x != 0:
poly = padd(poly, pscale(x * comb(d, i), pmul(ppow([0, 1], i), ppow([1, -1], d - i))))
return real_roots(poly, 0.0, 1.0)
def _eval(Gf: Grid, s: float, t: float) -> float:
bs, bt = bernstein(len(Gf) - 1, s), bernstein(len(Gf[0]) - 1, t)
return sum(bs[i] * sum(bt[j] * Gf[i][j] for j in range(len(bt))) for i in range(len(bs)))
def _root_in(Gf: Grid, s: float, along_t: bool) -> float:
"""The root of the monotone function t -> g(s, t) (or s -> g(t, s)) in [0, 1], by bisection."""
def h(t):
return _eval(Gf, s, t) if along_t else _eval(Gf, t, s)
a, b = 0.0, 1.0
ha = h(a)
for _ in range(60):
mid = 0.5 * (a + b)
hm = h(mid)
if hm == 0:
return mid
if (hm < 0) == (ha < 0):
a, ha = mid, hm
else:
b = mid
return 0.5 * (a + b)
def _box_arcs(G: Grid, box: tuple, mono_v: bool, samples: int):
"""Arcs of g = 0 in a box where g is strictly monotone in v (mono_v) or in u.
Returns None when the boundary points cannot be paired (an odd count)."""
u0, u1, v0, v1 = box
M, N = len(G) - 1, len(G[0]) - 1
found = []
for t in _edge_roots([G[i][0] for i in range(M + 1)]):
found.append((u0 + t * (u1 - u0), v0))
for t in _edge_roots([G[i][N] for i in range(M + 1)]):
found.append((u0 + t * (u1 - u0), v1))
for t in _edge_roots(G[0]):
found.append((u0, v0 + t * (v1 - v0)))
for t in _edge_roots(G[M]):
found.append((u1, v0 + t * (v1 - v0)))
pts = []
for p in found:
if all(abs(p[0] - q[0]) + abs(p[1] - q[1]) > 1e-10 for q in pts):
pts.append(p)
if len(pts) % 2:
return None
axis = 0 if mono_v else 1
pts.sort(key=lambda p: p[axis])
Gf = [[float(x) for x in row] for row in G]
arcs = []
for a, b in zip(pts[0::2], pts[1::2]):
line = [a]
for k in range(1, samples + 1):
if mono_v:
u = a[0] + (b[0] - a[0]) * k / (samples + 1)
s = (u - u0) / (u1 - u0)
line.append((u, v0 + (v1 - v0) * _root_in(Gf, s, True)))
else:
v = a[1] + (b[1] - a[1]) * k / (samples + 1)
t = (v - v0) / (v1 - v0)
line.append((u0 + (u1 - u0) * _root_in(Gf, t, False), v))
line.append(b)
arcs.append(line)
return arcs
def algebraic_surface_intersection(P: Sequence[Sequence[Vec]], f: dict, max_depth: int = 10,
samples: int = 4, stats: dict = None) -> tuple:
"""Return (curves, singular): polylines of (u, v) on g = 0, a closed one
repeating its first point at the end, and the boxes (u0, u1, v0, v1) left
unresolved at depth max_depth."""
G0 = substitute(P, f) # @line L1
stack = [(G0, (0.0, 1.0, 0.0, 1.0), 0)] # @line L2
arcs, singular = [], []
boxes = 0
while stack: # @line L3
G, box, depth = stack.pop()
boxes += 1
if _strict_sign(x for row in G for x in row): # @line L4
continue
M, N = len(G) - 1, len(G[0]) - 1
sv = _strict_sign(G[i][j + 1] - G[i][j] for i in range(M + 1) for j in range(N)) # @line L5
su = 0 if sv else _strict_sign(G[i + 1][j] - G[i][j] for i in range(M) for j in range(N + 1))
if sv or su:
got = _box_arcs(G, box, bool(sv), samples) # @line L6
if got is not None:
arcs += got
continue
if depth < max_depth: # @line L7
u0, u1, v0, v1 = box
um, vm = 0.5 * (u0 + u1), 0.5 * (v0 + v1)
subs = ((u0, um, v0, vm), (u0, um, vm, v1), (um, u1, v0, vm), (um, u1, vm, v1))
for Q, b in zip(_split(G), subs):
stack.append((Q, b, depth + 1))
else:
singular.append(box) # @line L8
if stats is not None:
stats["boxes"] = boxes
ends = [] # @line L9
def node(p) -> int:
for k, q in enumerate(ends):
if abs(p[0] - q[0]) + abs(p[1] - q[1]) <= 1e-8:
return k
ends.append(p)
return len(ends) - 1
adj = {}
for e, line in enumerate(arcs):
a, b = node(line[0]), node(line[-1])
adj.setdefault(a, []).append((e, b, False))
adj.setdefault(b, []).append((e, a, True))
used = [False] * len(arcs)
curves = []
for s in [a for a in adj if len(adj[a]) % 2] + list(adj):
while any(not used[e] for e, _, _ in adj[s]):
cur, curve = s, [ends[s]]
while True:
nxt = next(((e, b, rev) for e, b, rev in adj[cur] if not used[e]), None)
if nxt is None:
break
e, b, rev = nxt
used[e] = True
piece = arcs[e][::-1] if rev else arcs[e]
curve += piece[1:-1] + [ends[b]]
cur = b
curves.append(curve)
return curves, singular # @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_algebraic_surface_intersection.py 104 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/algebraic-surface-intersection/. The authors are listed in prov/38DDQS.jsonl.
import random
import unittest
from fractions import Fraction
from algebraic_surface_intersection import algebraic_surface_intersection, substitute
from si1geom import bernstein, patch_point
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)]
SADDLE = [[(i, j, (i - 1.5) * (j - 1.5)) for j in range(4)] for i in range(4)]
def eval_f(f, q):
return sum(c * q[0] ** a * q[1] ** b * q[2] ** e for (a, b, e), c in f.items())
def random_case(rng):
P = [[(i + rng.randint(-3, 3) / 8, j + rng.randint(-3, 3) / 8, rng.randint(-24, 24) / 8)
for j in range(4)] for i in range(4)]
if rng.random() < 0.5:
f = {(1, 0, 0): rng.randint(-8, 8) / 8, (0, 1, 0): rng.randint(-8, 8) / 8, (0, 0, 1): 1,
(0, 0, 0): rng.randint(-8, 8) / 8}
else:
cx, cy, cz, R = rng.randint(0, 12) / 4, rng.randint(0, 12) / 4, rng.randint(-4, 4) / 4, rng.randint(4, 8) / 4
f = {(2, 0, 0): 1, (0, 2, 0): 1, (0, 0, 2): 1, (1, 0, 0): -2 * cx, (0, 1, 0): -2 * cy,
(0, 0, 1): -2 * cz, (0, 0, 0): cx * cx + cy * cy + cz * cz - R * R}
return P, f
def crossings(curves, along_v, c):
"""Number of times the polylines cross the line u = c (along_v) or v = c."""
k = 0 if along_v else 1
return sum(1 for line in curves for a, b in zip(line, line[1:]) if (a[k] - c) * (b[k] - c) < 0)
def sign_changes(P, f, along_v, c, samples):
vals = [eval_f(f, patch_point(P, c, t / samples) if along_v else patch_point(P, t / samples, c))
for t in range(samples + 1)]
return sum(1 for a, b in zip(vals, vals[1:]) if a * b < 0)
class TestAlgebraicSurfaceIntersection(unittest.TestCase):
def test_substitution_is_exact(self):
rng = random.Random(1)
for _ in range(5):
P, f = random_case(rng)
G = substitute(P, f)
for _ in range(4):
u, v = Fraction(rng.randint(0, 64), 64), Fraction(rng.randint(0, 64), 64)
bu, bv = bernstein(len(G) - 1, u), bernstein(len(G[0]) - 1, v)
g = sum(bu[i] * bv[j] * G[i][j] for i in range(len(bu)) for j in range(len(bv)))
q = patch_point([[tuple(Fraction(x) for x in p) for p in row] for row in P], u, v)
self.assertEqual(g, eval_f({e: Fraction(c) for e, c in f.items()}, q))
def test_example_plane_and_bump(self):
G = substitute(BUMP, {(0, 0, 1): 1, (0, 0, 0): -1})
self.assertEqual(G, [[-1, -1, -1, -1], [-1, 2, 2, -1], [-1, 2, 2, -1], [-1, -1, -1, -1]])
stats = {}
curves, singular = algebraic_surface_intersection(BUMP, {(0, 0, 1): 1, (0, 0, 0): -1}, stats=stats)
self.assertEqual(stats["boxes"], 37)
self.assertEqual(singular, [])
self.assertEqual(len(curves), 1)
self.assertEqual(curves[0][0], curves[0][-1])
for u, v in curves[0]:
self.assertAlmostEqual(27 * u * (1 - u) * v * (1 - v), 1.0, places=12)
def test_small_loop_is_found(self):
curves, singular = algebraic_surface_intersection(BUMP, {(0, 0, 1): 1, (0, 0, 0): -1.68})
self.assertEqual((len(curves), singular), (1, []))
self.assertEqual(curves[0][0], curves[0][-1])
us = [u for u, v in curves[0]]
self.assertAlmostEqual(max(us) - min(us), 1 / 15, places=6)
def test_singular_point_is_boxed(self):
curves, singular = algebraic_surface_intersection(SADDLE, {(0, 0, 1): 1}, max_depth=6)
self.assertEqual(len(singular), 4)
for u0, u1, v0, v1 in singular:
self.assertTrue(u0 <= 0.5 <= u1 and v0 <= 0.5 <= v1)
self.assertEqual(len(curves), 4)
def test_against_grid_sign_changes(self):
rng = random.Random(23)
lines = [k / 10 + 0.0123 for k in range(10)]
total = 0
for _ in range(16):
P, f = random_case(rng)
curves, singular = algebraic_surface_intersection(P, f, samples=12)
self.assertEqual(singular, [])
for line in curves:
for u, v in line:
self.assertLess(abs(eval_f(f, patch_point(P, u, v))), 1e-9)
for c in lines:
for along_v in (True, False):
want = sign_changes(P, f, along_v, c, 2000)
self.assertEqual(crossings(curves, along_v, c), want)
total += want
self.assertGreater(total, 100)
if __name__ == "__main__":
unittest.main()
History
Farouki (1986) studied the sections of polynomial patches by algebraic surfaces as plane algebraic curves in the parameter domain. Patrikalakis and Prakash (1990) combined the Bernstein form of that curve over a rectangle, adaptive subdivision, and the computation of turning and singular points, so that each part of the domain could be traced independently, and the approach was extended by Kriezis, Prakash and Patrikalakis in the same year. Patrikalakis and Maekawa (2002) give it as the method for a rational patch against an implicit algebraic surface in their book.
References
- Nicholas M. Patrikalakis and Takashi Maekawa, Shape Interrogation for Computer Aided Design and Manufacturing, Springer, 2002, Chapter 5, Section 5.8.1, the intersection of a rational polynomial parametric surface with an implicit algebraic surface (substitution, the plane algebraic curve in the parameter box, its border, turning and singular points, and tracing)
- N. M. Patrikalakis and P. V. Prakash, Surface intersections for geometric modeling, Journal of Mechanical Design 112(1), 100 to 107, 1990, the method of the abstract (the curve in the Bernstein basis over a rectangle, adaptive subdivision, turning and singular points, and tracing of the parts; general locator)
- Rida T. Farouki, The characterization of parametric surface sections, Computer Vision, Graphics, and Image Processing 33(2), 209 to 236, 1986, the whole paper (sections of polynomial patches by an algebraic surface as plane algebraic curves in the parameter domain; general locator)
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 38DDQS Edit this page History Report an error Markdown