Algorithmadvanced
Interval projected polyhedron algorithm
Also called IPP algorithm, projected polyhedron solver.
Sherbrooke and Patrikalakis's solver that finds all roots of a polynomial system in a box by projecting Bernstein control polyhedra and subdividing, robust with intervals.
- Time
- O(K m n N d) worst
- Space
- O(D m N) extra
- Where
- D = the depth bound n (1 + log2(W / ε)) + 1 of the tree of boxes; K = the number of boxes processed; N = the number of Bernstein coefficients of one equation; W = the widest side of the input box; d = the largest degree in one variable; m = the number of equations; n = the number of variables; ε = the box size at which a root is reported
- Properties
- deterministicnot exactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Evan C. Sherbrooke, Nicholas M. Patrikalakis, 1993
The interval projected polyhedron method finds all real roots of a system of polynomial equations inside a box. It writes each equation in the Bernstein basis of the box, and uses the convex hull of the control points, projected onto one axis at a time, to cut away parts of the box that hold no root. It splits the box when the cuts do not shrink it enough, and stops on boxes smaller than a tolerance. All arithmetic on the coefficients rounds outward, so no root is lost to rounding.
In plain words
Think of a search for lost keys in a field. A quick test can say for certain "the keys are not in this strip", but never where they are. So you mark off the strips the test clears, look only at what is left, and, when the test clears nothing, cut the field in two and test each half.
Here the keys are the points where all the equations are zero, and the field is a box. The test looks at a few numbers that describe each equation over the box, the control points. If a whole region is on one side of zero for some equation, it holds no solution.
The method repeats the test on smaller and smaller boxes. Every answer it gives is a tiny box, and every solution is inside one of them. Intervals take care of rounding, so no solution slips away.
The problem
The input is polynomials in variables, a box and a tolerance . The output is a list of boxes with sides shorter than that together contain every with . This is the real, bounded case of polynomial system solving, and the form in which CAD meets it: intersections, closest points, extrema of curvature and singular points of curves and surfaces become a few polynomial equations in the parameters of patches, and only the roots inside the parameter box matter.
On a box with local coordinates , an equation with degree in has the tensor product form
with the Bernstein polynomials . The points are the control points, and they span the control polyhedron of the graph of .
The algorithm
IPP(f₁, …, f_m, X₀, ε)- 1
B_k ← the Bernstein coefficients of f_k on X₀, each rounded outward to a float interval - 2
S ← {(X₀, B)}; out ← ∅ - 3
while S ≠ ∅: take (X, B) from S - 4
for each axis j: [s_j, t_j] ← ∩_k the part of the u_j axis inside the convex hull of the control points of B_k projected onto the (u_j, f) plane - 5
if some [s_j, t_j] is empty: discard X and continue - 6
if every side of X is shorter than ε: out ← out ∪ {X} and continue - 7
X, B ← the part of X over ∏_j [s_j, t_j], by de Casteljau subdivision in interval arithmetic - 8
if the side j* that was the widest before line L7 is still longer than half its old width: split X and B in the middle of side j* and put both halves in S - 9
else put (X, B) in S - 10
return out, with boxes that are at most ε apart grouped together
Line L4 is the projection. For axis the control points of project to the points of a plane, one column of points for each . With interval coefficients each column becomes the segment from its lowest lower end to its highest upper end . The part of the axis inside the convex hull of these ends is an interval whose ends are among the points with and the crossings of the segments from a point above the axis to a point below. The code takes the least and the greatest of these, exactly in rational arithmetic, and rounds them outward. This gives the same interval as a convex hull of the projected points, without building it. An equation that does not depend on gives the whole axis or nothing.
Line L7 restricts the coefficients to the new box with the de Casteljau algorithm along each axis, in interval arithmetic where each operation is widened by one float step down and up. The box ends are kept as exact rational numbers, so the coefficients always describe the box they are stored with. Line L8 splits when the box does not shrink well, which happens near several roots or near a root where the hulls are wide.
Example
Intersect the unit circle with the line in the box . The one root is . With , the Bernstein coefficients of are , so those of are with :
Projected onto the axis, the columns are at , at and at . The convex hull meets the axis from , where the first column crosses zero, to the crossing of the segment from to , at . The same holds for . The line has coefficients , whose projections cover the whole axis. So line L7 shrinks the box to , which maps back to .
The side shrank from to , which is more than half, so line L8 splits it at . Line L5 later discards the left half , and on the right half the projections of the line now help. In the run of the code, the widest side of the box that holds the root after each of the steps of line L7 is
with a split after each step that does not halve the side. The output is one box of side around , and no other box survives.
Correctness
The full proof shows that every root in lies in an output box. The key fact is the convex hull property of the Bernstein basis: the are nonnegative on , sum to , and . So at a root with local coordinates ,
is a convex combination of the projected control points, and lies in their convex hull; see the convex hull property. With intervals each point lies on the segment of its column, so it is in the hull of the column ends. A short lemma shows that a point in the hull of a finite set lies between the least and the greatest of the zero points and the crossings, and line L4 rounds those outward. So line L5 discards only boxes with no root, and line L7 keeps every root of the box.
The de Casteljau scheme gives the exact coefficients on the parts of a box. In rounded interval arithmetic each computed interval contains the exact value, because with round to nearest the exact result of an operation lies between the two floats next to the computed one. The split parameters are floats and the box ends are exact rationals, so the coefficients always belong to their box. Termination follows because every step that keeps a box at least halves a side of width at least , so a path in the tree of boxes has at most steps.
What is not proved is the converse. An output box need not contain a root, a root can give several boxes, and the number of groups need not be the number of roots. The tests check, on systems with known simple roots (a circle and a line, products of linear factors with six roots, a sphere and two planes in three variables, five roots of one polynomial, the three close roots of the book example, random pairs of line pairs), that every root is in a box and that each group holds exactly one root. They also check the projection step alone on random polynomials, and that the interval subdivision encloses the exact pieces.
Proof: The interval projected polyhedron method keeps every root of the system in the box and stopsfull
The input is polynomials in variables and a box with rational ends. A root is a point with . Every box of the method has exact rational ends, and its local coordinates are when . Let be the degree of in . On , has the tensor product Bernstein form
over the multi-indices with ; see Bernstein polynomials. The method stores, for each and , a float interval . The invariant is that for the exact coefficients of on the box the intervals are stored with.
Claim 1 (three facts on the basis). For : , , and if , .
Proof. Each factor is a product of nonnegative numbers. By the binomial theorem , and the sum over is the product of these sums. For the last fact, for , so
and the sums over the other indices are .
Claim 2 (the hull and the axis). Let be a finite set of points in the plane, and let be the set made of the of the points with and of the crossings
of the segments from a point with to a point with . If is in the convex hull of , then is not empty and .
Proof. Write with and , and split into , and by the sign of . The second coordinate gives . If , all the weight is on , so is a convex combination of the of the points of , which are in . If , put for , . Then
and in the same way . So with nonnegative weights of sum , a convex combination of elements of . In both cases and lies between and .
Claim 3 (line L4 keeps every root). Assume the invariant on a box , and let be a zero of with local coordinates . Then for every axis the interval that line L4 computes from exists and contains .
Proof. For each column of axis the code takes and over the with . If , the polynomial does not depend on , and is a convex combination of the by Claim 1, so , and the code returns . If , Claim 1 gives
a convex combination of the projected control points. By the invariant each point lies on the segment from to , so is in the convex hull of the set of these ends. By Claim 2, the set is not empty and . The code computes and exactly in rational arithmetic, rounds the first down and the second up to floats, and clips to , which contains .
So a box that line L5 discards has no root: either some gives no interval on some axis, or the intervals of two equations on one axis are disjoint, and in both cases Claim 3 rules out a root. If the box is kept, every root in it has local coordinates in , the intersection over .
Claim 4 (lines L7 and L8 keep the invariant and the roots). The de Casteljau scheme at a parameter along axis maps the Bernstein coefficients on a box to those on its two parts at the local value of ; this is the subdivision property of the de Casteljau algorithm, applied to each line of the tensor along axis (cited, not proved here). The code runs it in interval arithmetic where each sum and product is computed in round to nearest and then widened by one float step down and up. With round to nearest, the exact value of an operation lies between the two floats next to the rounded value, so each computed interval contains the exact result of the same operation on any numbers in the input intervals, provided that no operation overflows. The value is also enclosed in an interval. By induction over the steps of the scheme, the new intervals contain the exact coefficients on the parts, and the invariant holds.
Line L7 first keeps the part , at the float . Then it keeps the part of that, with the float rounded down, so that the kept local range is . The new ends are computed exactly from and in rational arithmetic, so the coefficients belong to the stored box and every root of is in the new box. Line L8 splits at the local value into two closed halves whose union is the box, and each root is in one of them.
Claim 5 (termination). Let and . Every path from in the tree of boxes has at most steps, and the method stops.
Proof. A step that does not discard or output its box has a widest side of width , by line L6. Line L7 only shrinks the sides. If side is then still longer than , line L8 halves it; otherwise it is already at most . So each such step at least halves one side of width at least . A side of initial width that has been halved times in this way had width at most before the last of them, and at least , so . Summing over the sides and adding the last step bounds the path length. Each box has at most two children, so the tree is finite, and the stack is empty after finitely many steps.
Conclusion. By induction over the tree, with Claims 3 and 4 as the step: every root in stays in some box on a path of the tree, and the path ends at line L6, since line L5 never discards a box that holds a root. So every root lies in an output box, every output box passed the test of line L4 and has all sides shorter than , and line L10, which only groups boxes, keeps them all.
What is not proved is the converse: an output box need not hold a root, near a root the method can return several boxes, and the number of groups need not be the number of roots. Nor is a rate of convergence proved. The tests measure, for systems with known simple roots, that each group holds exactly one root, and that the boxes of a tangent root form one group.
Complexity
One step costs to find the column ranges, for the crossings, and for the de Casteljau restrictions, since each of the lines along axis takes operations. With boxes processed the time is . The stack holds at most two boxes per level of the tree, so the extra space is .
By the termination bound the tree has depth at most and at most boxes. This worst case is reached in order of magnitude when the roots form a curve or a surface, where the method covers it with boxes of side . For isolated simple roots, few boxes are processed in practice. Patrikalakis and Maekawa state that the method converges quadratically in one variable and at best linearly in several. In the example above the sides shrank faster than linearly near the root, but that is one measured input.
The box ends are exact rationals whose size grows with the depth. The float coefficients keep the cost of the heavy steps fixed, and only the ends grow.
Properties
- Complete. No root in the box is lost, also under rounding, as long as no operation overflows.
- Not certified as existing. A reported box is a box where the test could not exclude a root. It is not a proof that a root is there.
- Global in the box. No start point is needed, unlike Newton's method.
- Any number of equations. The test works for , although a system with a curve of roots gives many boxes.
- Affine invariant in each axis. The Bernstein form and the hulls do not change under an affine change of each variable.
Variants and improvements
- Plain floats. The original projected polyhedron method of Sherbrooke and Patrikalakis uses floating point arithmetic. Patrikalakis and Maekawa show an example with roots , and where plain floats lose the root and rounded intervals keep it. The tests run the same polynomial and find all three roots.
- Exact rational arithmetic. With rational coefficients the same steps can run without rounding. The numbers grow with each subdivision.
- Bézier clipping. For one equation in one variable, or two plane curves, the projection step is Bézier clipping of Sederberg and Nishita.
- Preconditioning. Mourrain and Pavone (2009) replace the equations by linear combinations of them that are close to the coordinate functions near a root. Then the projections are narrow, and the method cuts much more per step in several variables.
- Other bases. Reuter, Mikkelsen, Sherbrooke, Maekawa and Patrikalakis (2008) run the method in the barycentric Bernstein basis of a simplex, for triangular domains.
- Certification. After a box is small, an interval Newton method step on it can prove that it holds exactly one root.
When to use it
Use it when all roots in a parameter box are needed, which is the case for the characteristic points of surface surface intersection, for curve surface intersection, and for the stationary points of distance and curvature functions. It is a good choice for small systems of low degree, since the number of coefficients grows like the product of the degrees. For one polynomial in one variable, use real root isolation, and for a large system with many complex roots, use homotopy continuation or algebraic methods.
Pitfalls
- Curves of roots. If the system has a curve or a surface of solutions in the box, the number of boxes grows like a power of . Detect this from the count of boxes, and treat the case with a tracing method.
- Multiple roots. At a tangent or a multiple root the hulls stay wide, the method splits often, and it returns many boxes near the root. The test with a double root gives boxes that form one group.
- Spurious boxes. A box can survive with no root in it, in particular near a root or a near miss. Group nearby boxes, and verify each group, for example with interval Newton or with the residuals.
- Rounding of the parameters. If the box ends are kept in floats and the coefficients are restricted with rounded split parameters, the coefficients belong to a slightly different box, and a root near a box end can be lost. Keep the ends exact, or round them outward and widen the coefficients.
- Scaling. The test is affine invariant in each variable but not under a change of the equations. Equations with very different sizes are fine, but equations that are nearly dependent near a root make all projections wide.
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/interval-projected-polyhedron/. The authors are listed in prov/V244NY.jsonl.
"""The interval projected polyhedron solver for polynomial systems in a box.
A polynomial in n variables is a dict that maps an exponent tuple to a
rational coefficient. The box is a list of n pairs (a_j, b_j). The solver
writes every equation in the tensor product Bernstein basis of the box, with
each coefficient held as a float interval that contains the exact value. For
each axis j it projects the control points (i_j / d_j, b_I) of each equation
onto the plane of u_j and f, and keeps the part of the axis f = 0 inside the
convex hull of the projection. The box shrinks to the product of these parts,
or is split in two when it does not shrink enough, until its sides are shorter
than eps.
Boxes are kept with exact rational ends, so that the interval coefficients
always belong to the box they are stored with. All float operations on the
coefficients round outward by one unit in the last place.
"""
from fractions import Fraction
from math import comb, inf, nextafter, prod
# ---- outward rounded interval arithmetic -----------------------------------
def down(x):
return nextafter(x, -inf)
def up(x):
return nextafter(x, inf)
def enclose(q):
"""The smallest float interval that contains the rational number q."""
f = float(q)
F = Fraction(f)
if F == q:
return (f, f)
if F < q:
return (f, up(f))
return (down(f), f)
def i_add(a, b):
return (down(a[0] + b[0]), up(a[1] + b[1]))
def i_mul(a, b):
p = (a[0] * b[0], a[0] * b[1], a[1] * b[0], a[1] * b[1])
return (down(min(p)), up(max(p)))
# ---- tensors of Bernstein coefficients, stored flat in row major order -----
def strides(shape):
out = [1] * len(shape)
for j in range(len(shape) - 2, -1, -1):
out[j] = out[j + 1] * shape[j + 1]
return out
def fibers(shape, axis):
"""The lists of flat indices of the lines of the tensor along an axis."""
st = strides(shape)
out = []
for base in range(prod(shape)):
if (base // st[axis]) % shape[axis] == 0:
out.append([base + i * st[axis] for i in range(shape[axis])])
return out
def bernstein_tensor(poly, box):
"""Exact Bernstein coefficients of poly on the box, as (shape, flat list)."""
n = len(box)
degs = [max((e[j] for e in poly), default=0) for j in range(n)]
shape = tuple(d + 1 for d in degs)
st = strides(shape)
flat = [Fraction(0)] * prod(shape)
for e, c in poly.items():
flat[sum(e[j] * st[j] for j in range(n))] += Fraction(c)
for j in range(n):
a, b = Fraction(box[j][0]), Fraction(box[j][1])
h, d = b - a, degs[j]
for fib in fibers(shape, j):
c = [flat[k] for k in fib]
# c(a + h u) in powers of u, then u^k = sum_i C(i, k) / C(d, k) B_i(u)
cs = [sum(c[m] * comb(m, k) * a ** (m - k) for m in range(k, d + 1)) * h ** k for k in range(d + 1)]
bs = [sum(Fraction(comb(i, k), comb(d, k)) * cs[k] for k in range(i + 1)) for i in range(d + 1)]
for i, k in enumerate(fib):
flat[k] = bs[i]
return shape, flat
def split(coefs, shape, axis, t):
"""De Casteljau subdivision at the float t in [0, 1] along an axis, in
interval arithmetic: the coefficients on [0, t] and on [t, 1]."""
T = (t, t)
S = enclose(1 - Fraction(t))
left, right = list(coefs), list(coefs)
for fib in fibers(shape, axis):
row = [coefs[k] for k in fib]
L, R = [row[0]], [row[-1]]
while len(row) > 1:
row = [i_add(i_mul(S, row[i]), i_mul(T, row[i + 1])) for i in range(len(row) - 1)]
L.append(row[0])
R.append(row[-1])
R.reverse()
for i, k in enumerate(fib):
left[k], right[k] = L[i], R[i]
return left, right
# ---- the projection step ---------------------------------------------------
def hull_axis_interval(points):
"""The interval of t with (t, 0) in the convex hull of the points (t, f),
exactly, from the zero points and the crossings of the segments between a
point with f > 0 and a point with f < 0. None when it is empty."""
cands = [t for t, f in points if f == 0]
pos = [p for p in points if p[1] > 0]
neg = [p for p in points if p[1] < 0]
cands += [(fp * tq - fq * tp) / (fp - fq) for tp, fp in pos for tq, fq in neg]
if not cands:
return None
return min(cands), max(cands)
def project(coefs, shape, axis):
"""The local interval [s, t] of u_axis outside of which this equation has
no zero in the box, rounded outward to floats, or None."""
d = shape[axis] - 1
st = strides(shape)[axis]
lo = [inf] * (d + 1)
hi = [-inf] * (d + 1)
for k, (a, b) in enumerate(coefs):
i = (k // st) % (d + 1)
lo[i] = min(lo[i], a)
hi[i] = max(hi[i], b)
if d == 0: # the equation does not depend on this variable
return (0.0, 1.0) if lo[0] <= 0 <= hi[0] else None
pts = []
for i in range(d + 1):
pts.append((Fraction(i, d), Fraction(lo[i])))
pts.append((Fraction(i, d), Fraction(hi[i])))
r = hull_axis_interval(pts)
if r is None:
return None
return max(0.0, enclose(r[0])[0]), min(1.0, enclose(r[1])[1])
def restrict(X, Bs, shapes, lo, hi):
"""The box and the coefficients over the local box prod [lo_j, hi_j], or
over a slightly larger box with float split parameters."""
X = list(X)
for j in range(len(X)):
s, t = lo[j], hi[j]
a, b = X[j]
h = b - a
start, end = Fraction(0), Fraction(1)
if t < 1:
Bs = [split(B, sh, j, t)[0] for B, sh in zip(Bs, shapes)]
end = Fraction(t)
if s > 0 and t > 0:
r = enclose(Fraction(s) / end)[0] # r * end <= s
if r > 0:
Bs = [split(B, sh, j, r)[1] for B, sh in zip(Bs, shapes)]
start = Fraction(r) * end
X[j] = (a + h * start, a + h * end)
return X, Bs
def merge(boxes, gap):
"""Group boxes whose distance in the max norm is at most gap, and return
the bounding box of each group as float intervals rounded outward."""
parent = list(range(len(boxes)))
def find(i):
while parent[i] != i:
parent[i] = parent[parent[i]]
i = parent[i]
return i
for i in range(len(boxes)):
for k in range(i):
if all(boxes[i][j][0] <= boxes[k][j][1] + gap and boxes[k][j][0] <= boxes[i][j][1] + gap for j in range(len(boxes[i]))):
parent[find(i)] = find(k)
groups = {}
for i, X in enumerate(boxes):
groups.setdefault(find(i), []).append(X)
out = []
for g in groups.values():
n = len(g[0])
out.append(tuple((enclose(min(X[j][0] for X in g))[0], enclose(max(X[j][1] for X in g))[1]) for j in range(n)))
return sorted(out)
def ipp(polys, box, eps=1e-9, max_steps=100000):
"""All roots of the system polys = 0 in the box, as a sorted list of small
boxes, each the bounding box of a group of boxes at most eps apart. Every
root in the box lies in one of them. Also returns the raw boxes, with
exact rational ends; each passed the projection test and has all sides
shorter than eps."""
n = len(box)
X0 = [(Fraction(a), Fraction(b)) for a, b in box]
shapes, B0 = [], []
for p in polys:
shape, flat = bernstein_tensor(p, X0) # @line L1
shapes.append(shape)
B0.append([enclose(x) for x in flat])
stack, out = [(X0, B0)], [] # @line L2
steps = 0
while stack: # @line L3
steps += 1
if steps > max_steps:
raise RuntimeError("too many steps")
X, Bs = stack.pop()
widths = [b - a for a, b in X]
jstar = max(range(n), key=lambda j: widths[j])
lo, hi = [0.0] * n, [1.0] * n
empty = False
for j in range(n): # @line L4
for B, sh in zip(Bs, shapes):
r = project(B, sh, j)
if r is None:
empty = True
break
lo[j], hi[j] = max(lo[j], r[0]), min(hi[j], r[1])
if empty or lo[j] > hi[j]:
empty = True
break
if empty: # @line L5
continue
if max(widths) < eps: # @line L6
out.append(X)
continue
X, Bs = restrict(X, Bs, shapes, lo, hi) # @line L7
if X[jstar][1] - X[jstar][0] > widths[jstar] / 2: # @line L8
a, b = X[jstar]
m = (a + b) / 2
halves = [split(B, sh, jstar, 0.5) for B, sh in zip(Bs, shapes)]
for side, (lo_, hi_) in ((0, (a, m)), (1, (m, b))):
Y = list(X)
Y[jstar] = (lo_, hi_)
stack.append((Y, [hv[side] for hv in halves]))
else:
stack.append((X, Bs)) # @line L9
return merge(out, Fraction(eps)), out # @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_interval_projected_polyhedron.py 218 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/interval-projected-polyhedron/. The authors are listed in prov/V244NY.jsonl.
import random
import unittest
from fractions import Fraction as F
from itertools import product
from math import sqrt
from interval_projected_polyhedron import (
bernstein_tensor, enclose, hull_axis_interval, ipp, project, split, strides,
)
from si1geom import bernstein
def evaluate(poly, x):
total = F(0)
for e, c in poly.items():
term = F(c)
for xj, k in zip(x, e):
term *= F(xj) ** k
total += term
return total
def bernstein_value(shape, flat, u):
st = strides(shape)
bs = [bernstein(d - 1, uj) for d, uj in zip(shape, u)]
total = F(0)
for idx in product(*[range(d) for d in shape]):
w = F(1)
for j, i in enumerate(idx):
w *= bs[j][i]
total += w * flat[sum(i * s for i, s in zip(idx, st))]
return total
def random_poly(rng, degs):
return {e: F(rng.randint(-9, 9), rng.randint(1, 5)) for e in product(*[range(d + 1) for d in degs])}
def inside(x, box):
return all(a <= xj <= b for xj, (a, b) in zip(x, box))
def linear(a, b, c):
"""a x + b y + c."""
return {(1, 0): a, (0, 1): b, (0, 0): c}
def times(p, q):
out = {}
for e1, c1 in p.items():
for e2, c2 in q.items():
e = tuple(x + y for x, y in zip(e1, e2))
out[e] = out.get(e, 0) + F(c1) * F(c2)
return out
class TestBernsteinForm(unittest.TestCase):
def test_conversion_is_exact(self):
rng = random.Random(1)
for _ in range(20):
poly = random_poly(rng, (rng.randint(0, 3), rng.randint(0, 3)))
box = [(F(rng.randint(-5, 0), 2), F(rng.randint(1, 5), 3)) for _ in range(2)]
shape, flat = bernstein_tensor(poly, box)
for _ in range(5):
u = (F(rng.randint(0, 12), 12), F(rng.randint(0, 7), 7))
x = [a + (b - a) * uj for (a, b), uj in zip(box, u)]
self.assertEqual(bernstein_value(shape, flat, u), evaluate(poly, x))
def test_interval_split_encloses_the_exact_pieces(self):
rng = random.Random(2)
for _ in range(20):
poly = random_poly(rng, (3, 2))
shape, flat = bernstein_tensor(poly, [(0, 1), (0, 1)])
coefs = [enclose(x) for x in flat]
axis = rng.randint(0, 1)
t = rng.random()
left, right = split(coefs, shape, axis, t)
for _ in range(4):
u = [F(rng.randint(0, 10), 10), F(rng.randint(0, 10), 10)]
for piece, lo_end, width in ((left, F(0), F(t)), (right, F(t), 1 - F(t))):
x = list(u)
x[axis] = lo_end + width * u[axis]
exact = evaluate(poly, x)
lo = bernstein_value(shape, [F(a) for a, _ in piece], u)
hi = bernstein_value(shape, [F(b) for _, b in piece], u)
self.assertLessEqual(lo, exact)
self.assertLessEqual(exact, hi)
self.assertLess(hi - lo, 1e-12)
class TestProjection(unittest.TestCase):
def test_hull_interval_of_a_small_set(self):
pts = [(F(0), F(2)), (F(1, 2), F(-1)), (F(1), F(3))]
lo, hi = hull_axis_interval(pts)
# the edges from (1/2, -1) to (0, 2) and to (1, 3) cross f = 0 at 1/3 and 5/8
self.assertEqual((lo, hi), (F(1, 3), F(5, 8)))
self.assertIsNone(hull_axis_interval([(F(0), F(1)), (F(1), F(2))]))
def test_projection_keeps_every_zero(self):
# g = f - f(u) has the zero u, and the projection must keep u_j
rng = random.Random(3)
for _ in range(60):
poly = random_poly(rng, (rng.randint(1, 3), rng.randint(1, 3)))
u = (F(rng.randint(0, 20), 20), F(rng.randint(0, 20), 20))
poly[(0, 0)] = poly[(0, 0)] - evaluate(poly, u)
shape, flat = bernstein_tensor(poly, [(0, 1), (0, 1)])
coefs = [enclose(x) for x in flat]
for j in range(2):
r = project(coefs, shape, j)
self.assertIsNotNone(r)
self.assertLessEqual(r[0], u[j])
self.assertLessEqual(u[j], r[1])
class TestSolver(unittest.TestCase):
def check(self, clusters, raw, roots, eps=1e-8):
"""Each root is in a raw box, each cluster holds exactly one root."""
for x in roots:
self.assertTrue(any(inside([F(v) for v in x], X) for X in raw), x)
self.assertEqual(len(clusters), len(roots))
for C in clusters:
self.assertEqual(sum(inside(x, C) for x in roots), 1, C)
self.assertLess(max(b - a for a, b in C), eps)
def test_example_circle_and_line(self):
circle = {(2, 0): 1, (0, 2): 1, (0, 0): -1}
clusters, raw = ipp([circle, linear(1, -1, 0)], [(-2, 2), (-2, 2)])
h = sqrt(0.5)
self.assertEqual(len(clusters), 2)
for C, s in zip(clusters, (-1, 1)):
for a, b in C:
self.assertLess(abs(a - s * h), 1e-9)
self.assertLess(abs(b - s * h), 1e-9)
def test_products_of_linear_factors(self):
f1 = times(linear(1, 0, -F(2, 10)), linear(1, 0, -F(7, 10)))
f2 = times(times(linear(0, 1, -F(3, 10)), linear(0, 1, -F(6, 10))), linear(0, 1, -F(9, 10)))
clusters, raw = ipp([f1, f2], [(0, 1), (0, 1)])
roots = [(F(a, 10), F(b, 10)) for a in (2, 7) for b in (3, 6, 9)]
self.check(clusters, raw, roots)
def test_three_variables(self):
sphere = {(2, 0, 0): 1, (0, 2, 0): 1, (0, 0, 2): 1, (0, 0, 0): -1}
p1 = {(1, 0, 0): 1, (0, 1, 0): -1}
p2 = {(0, 1, 0): 1, (0, 0, 1): -1}
clusters, raw = ipp([sphere, p1, p2], [(-1, 1)] * 3)
self.assertEqual(len(clusters), 2)
r = 1 / sqrt(3)
for C, s in zip(clusters, (-1, 1)):
for a, b in C:
self.assertLessEqual(a, s * r + 1e-15)
self.assertLessEqual(s * r - 1e-15, b)
def test_one_variable_degree_five(self):
p = {(0,): 1}
for k in range(1, 6):
p = times(p, {(1,): 1, (0,): -F(k, 10)})
clusters, raw = ipp([p], [(0, 1)])
self.check(clusters, raw, [(F(k, 10),) for k in range(1, 6)])
def test_close_roots_of_the_book_example(self):
# (x - 0.1)(x - 0.6)(x - 0.7), where plain floats can lose 0.7
p = {(0,): 1}
for r in (F(1, 10), F(6, 10), F(7, 10)):
p = times(p, {(1,): 1, (0,): -r})
clusters, raw = ipp([p], [(0, 1)], eps=1e-12)
self.check(clusters, raw, [(F(1, 10),), (F(6, 10),), (F(7, 10),)], eps=1e-11)
def test_no_roots(self):
positive = {(2, 0): 1, (0, 2): 1, (0, 0): 1}
self.assertEqual(ipp([positive, linear(1, -1, 0)], [(-2, 2), (-2, 2)]), ([], []))
small = {(2, 0): 1, (0, 2): 1, (0, 0): -F(1, 4)}
self.assertEqual(ipp([small, linear(1, -1, 0)], [(1, 2), (1, 2)]), ([], []))
def test_double_root_is_enclosed(self):
tangent = {(2, 0): 1, (1, 0): -1, (0, 0): F(1, 4)} # (x - 1/2)^2
clusters, raw = ipp([tangent, linear(0, 1, -F(1, 2))], [(0, 1), (0, 1)])
self.assertTrue(any(inside((F(1, 2), F(1, 2)), X) for X in raw))
self.assertEqual(len(clusters), 1)
def test_random_pairs_of_line_pairs(self):
# f1 = L1 L2 and f2 = L3 L4 have the four roots Li = Lj = 0, i < 3 <= j
rng = random.Random(5)
total = 0
for _ in range(30):
lines = [(F(rng.randint(-9, 9)), F(rng.randint(-9, 9)), F(rng.randint(-9, 9), 3)) for _ in range(4)]
if any(a == 0 and b == 0 for a, b, _ in lines):
continue
f1 = times(linear(*lines[0]), linear(*lines[1]))
f2 = times(linear(*lines[2]), linear(*lines[3]))
roots = []
for a1, b1, c1 in lines[:2]:
for a2, b2, c2 in lines[2:]:
d = a1 * b2 - a2 * b1
if d != 0:
x = ((-c1) * b2 - (-c2) * b1) / d
y = (a1 * (-c2) - a2 * (-c1)) / d
if -1 <= x <= 1 and -1 <= y <= 1:
roots.append((x, y))
if any(a1 * b2 == a2 * b1 for a1, b1, _ in lines[:2] for a2, b2, _ in lines[2:]):
continue # a parallel pair may share a whole line
clusters, raw = ipp([f1, f2], [(-1, 1), (-1, 1)])
for x in roots:
self.assertTrue(any(inside(x, X) for X in raw), x)
distinct = set(roots)
total += len(distinct)
# measured: every group holds a root, and distinct roots give distinct groups
for C in clusters:
self.assertTrue(any(inside(x, C) for x in distinct), C)
self.assertEqual(len(clusters), len(distinct))
self.assertGreater(total, 20)
if __name__ == "__main__":
unittest.main()
History
Sherbrooke and Patrikalakis (1993) introduced the projected polyhedron method for systems of polynomial equations in the multivariate Bernstein basis. It extends to several variables the convex hull idea of Bézier clipping, which Sederberg and Nishita had used in 1990 for curves. Maekawa and Patrikalakis ran the method in rounded interval arithmetic for robustness, and Patrikalakis and Maekawa's book of 2002 uses it as the general solver for the shape interrogation problems of CAD.
References
- Evan C. Sherbrooke and Nicholas M. Patrikalakis, Computation of the solutions of nonlinear polynomial systems, Computer Aided Geometric Design 10(5), 379 to 405, 1993, the whole paper (the multivariate Bernstein form, the projected polyhedron method, and subdivision of the box)
- Nicholas M. Patrikalakis and Takashi Maekawa, Shape Interrogation for Computer Aided Design and Manufacturing, Springer, 2002, Chapter 4, Section 4.4 (the projected polyhedron algorithm, its steps and its rate of convergence), Sections 4.7 and 4.8 (rounded interval arithmetic) and Section 4.9 (the interval projected polyhedron algorithm and its example with three roots)
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 V244NY Edit this page History Report an error Markdown