Algorithm Search⌘K

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
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 mm polynomials f1,…,fmf_1, \dots, f_m in nn variables, a box X0=∏j[aj,bj]X_0 = \prod_j [a_j, b_j] and a tolerance ε>0\varepsilon > 0. The output is a list of boxes with sides shorter than ε\varepsilon that together contain every x∈X0x \in X_0 with f1(x)=⋯=fm(x)=0f_1(x) = \dots = f_m(x) = 0. 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 XX with local coordinates u∈[0,1]nu \in [0, 1]^n, an equation with degree djd_j in xjx_j has the tensor product form

f(x)=∑IbI BI(u),BI(u)=∏j=1nBij,dj(uj),f(x) = \sum_I b_I \, B_I(u), \qquad B_I(u) = \prod_{j=1}^{n} B_{i_j, d_j}(u_j),

with the Bernstein polynomials Bi,dB_{i,d}. The points (i1/d1,…,in/dn,bI)(i_1 / d_1, \dots, i_n / d_n, b_I) are the control points, and they span the control polyhedron of the graph of ff.

The algorithm

  1. IPP(f₁, …, f_m, X₀, ε)
  2. 1B_k ← the Bernstein coefficients of f_k on X₀, each rounded outward to a float interval
  3. 2S ← {(X₀, B)}; out ← ∅
  4. 3while S ≠ ∅: take (X, B) from S
  5. 4for 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
  6. 5if some [s_j, t_j] is empty: discard X and continue
  7. 6if every side of X is shorter than ε: out ← out ∪ {X} and continue
  8. 7X, B ← the part of X over ∏_j [s_j, t_j], by de Casteljau subdivision in interval arithmetic
  9. 8if 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
  10. 9else put (X, B) in S
  11. 10return out, with boxes that are at most ε apart grouped together

Line L4 is the projection. For axis jj the control points of fkf_k project to the points (i/dj,bI)(i / d_j, b_I) of a plane, one column of points for each ii. With interval coefficients each column becomes the segment from its lowest lower end mim_i to its highest upper end MiM_i. The part of the axis f=0f = 0 inside the convex hull of these 2(dj+1)2(d_j + 1) ends is an interval whose ends are among the points with f=0f = 0 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 xjx_j 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 f1=x2+y2−1f_1 = x^2 + y^2 - 1 with the line f2=x−yf_2 = x - y in the box [12,1]2[\tfrac12, 1]^2. The one root is (1/2,1/2)(1/\sqrt2, 1/\sqrt2). With x=12+u2x = \tfrac12 + \tfrac{u}{2}, the Bernstein coefficients of x2x^2 are 14,12,1\tfrac14, \tfrac12, 1, so those of f1f_1 are bij=ci+cj−1b_{ij} = c_i + c_j - 1 with c=(14,12,1)c = (\tfrac14, \tfrac12, 1):

j=0j = 0 j=1j = 1 j=2j = 2
i=0i = 0 −12-\tfrac12 −14-\tfrac14 14\tfrac14
i=1i = 1 −14-\tfrac14 00 12\tfrac12
i=2i = 2 14\tfrac14 12\tfrac12 11

Projected onto the uu axis, the columns are [−12,14][-\tfrac12, \tfrac14] at u=0u = 0, [−14,12][-\tfrac14, \tfrac12] at u=12u = \tfrac12 and [14,1][\tfrac14, 1] at u=1u = 1. The convex hull meets the axis from u=0u = 0, where the first column crosses zero, to the crossing of the segment from (12,−14)(\tfrac12, -\tfrac14) to (1,14)(1, \tfrac14), at u=34u = \tfrac34. The same holds for vv. The line has coefficients 0,−12,12,00, -\tfrac12, \tfrac12, 0, whose projections cover the whole axis. So line L7 shrinks the box to [12,78]2[\tfrac12, \tfrac78]^2, which maps back u=34u = \tfrac34 to x=78x = \tfrac78.

The side shrank from 12\tfrac12 to 38\tfrac38, which is more than half, so line L8 splits it at x=1116x = \tfrac{11}{16}. Line L5 later discards the left half [12,1116]×[12,78][\tfrac12, \tfrac{11}{16}] \times [\tfrac12, \tfrac78], 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 1212 steps of line L7 is

0.375, 0.18, 0.040, 0.039, 0.019, 5.3⋅10−4, 5.3⋅10−4, 2.6⋅10−4, 9.9⋅10−8, 9.9⋅10−8, 4.9⋅10−8, 3.4⋅10−15,0.375, \ 0.18, \ 0.040, \ 0.039, \ 0.019, \ 5.3 \cdot 10^{-4}, \ 5.3 \cdot 10^{-4}, \ 2.6 \cdot 10^{-4}, \ 9.9 \cdot 10^{-8}, \ 9.9 \cdot 10^{-8}, \ 4.9 \cdot 10^{-8}, \ 3.4 \cdot 10^{-15},

with a split after each step that does not halve the side. The output is one box of side 3.4⋅10−153.4 \cdot 10^{-15} around (0.70710678118654…,0.70710678118654…)(0.70710678118654\ldots, 0.70710678118654\ldots), and no other box survives.

Correctness

The full proof shows that every root in X0X_0 lies in an output box. The key fact is the convex hull property of the Bernstein basis: the BIB_I are nonnegative on [0,1]n[0, 1]^n, sum to 11, and ∑I(ij/dj)BI(u)=uj\sum_I (i_j / d_j) B_I(u) = u_j. So at a root with local coordinates uu,

(uj,0)=∑IBI(u)(ijdj,bI)(u_j, 0) = \sum_I B_I(u) \left(\tfrac{i_j}{d_j}, b_I\right)

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 (τ,0)(\tau, 0) 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 ε\varepsilon, so a path in the tree of boxes has at most n(1+log⁡2(W/ε))+1n (1 + \log_2(W / \varepsilon)) + 1 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, 3030 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 6060 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 mm polynomials f1,…,fmf_1, \dots, f_m in nn variables and a box X0=∏j[aj,bj]X_0 = \prod_j [a_j, b_j] with rational ends. A root is a point x∈X0x \in X_0 with f1(x)=⋯=fm(x)=0f_1(x) = \dots = f_m(x) = 0. Every box X=∏j[αj,βj]X = \prod_j [\alpha_j, \beta_j] of the method has exact rational ends, and its local coordinates are uj=(xj−αj)/(βj−αj)u_j = (x_j - \alpha_j) / (\beta_j - \alpha_j) when βj>αj\beta_j > \alpha_j. Let djd_j be the degree of fkf_k in xjx_j. On XX, fkf_k has the tensor product Bernstein form

fk(x)=∑IbI BI(u),BI(u)=∏j=1nBij,dj(uj),Bi,d(t)=(di)ti(1−t)d−i,f_k(x) = \sum_I b_I \, B_I(u), \qquad B_I(u) = \prod_{j=1}^{n} B_{i_j, d_j}(u_j), \qquad B_{i, d}(t) = \binom{d}{i} t^i (1 - t)^{d - i},

over the multi-indices I=(i1,…,in)I = (i_1, \dots, i_n) with 0≤ij≤dj0 \le i_j \le d_j; see Bernstein polynomials. The method stores, for each kk and II, a float interval [ℓI,hI][\ell_I, h_I]. The invariant is that ℓI≤bI≤hI\ell_I \le b_I \le h_I for the exact coefficients bIb_I of fkf_k on the box the intervals are stored with.

Claim 1 (three facts on the basis). For u∈[0,1]nu \in [0, 1]^n: BI(u)≥0B_I(u) \ge 0, ∑IBI(u)=1\sum_I B_I(u) = 1, and if dj≥1d_j \ge 1, ∑IijdjBI(u)=uj\sum_I \tfrac{i_j}{d_j} B_I(u) = u_j.

Proof. Each factor is a product of nonnegative numbers. By the binomial theorem ∑i=0dBi,d(t)=(t+1−t)d=1\sum_{i=0}^{d} B_{i,d}(t) = (t + 1 - t)^d = 1, and the sum over II is the product of these nn sums. For the last fact, id(di)=(d−1i−1)\tfrac{i}{d} \binom{d}{i} = \binom{d - 1}{i - 1} for i≥1i \ge 1, so

∑i=0didBi,d(t)=t∑i=1d(d−1i−1)ti−1(1−t)d−i=t,\sum_{i=0}^{d} \tfrac{i}{d} B_{i,d}(t) = t \sum_{i=1}^{d} \binom{d-1}{i-1} t^{i-1} (1 - t)^{d - i} = t,

and the sums over the other indices are 11. □\square

Claim 2 (the hull and the axis). Let EE be a finite set of points (τ,φ)(\tau, \varphi) in the plane, and let CC be the set made of the τ\tau of the points with φ=0\varphi = 0 and of the crossings

cpq=φpτq−φqτpφp−φqc_{pq} = \frac{\varphi_p \tau_q - \varphi_q \tau_p}{\varphi_p - \varphi_q}

of the segments from a point pp with φp>0\varphi_p > 0 to a point qq with φq<0\varphi_q < 0. If (τ,0)(\tau, 0) is in the convex hull of EE, then CC is not empty and min⁡C≤τ≤max⁡C\min C \le \tau \le \max C.

Proof. Write (τ,0)=∑eλee(\tau, 0) = \sum_e \lambda_e e with λe≥0\lambda_e \ge 0 and ∑eλe=1\sum_e \lambda_e = 1, and split EE into E+E_+, E0E_0 and E−E_- by the sign of φ\varphi. The second coordinate gives W:=∑p∈E+λpφp=∑q∈E−λq(−φq)W := \sum_{p \in E_+} \lambda_p \varphi_p = \sum_{q \in E_-} \lambda_q (-\varphi_q). If W=0W = 0, all the weight is on E0E_0, so τ\tau is a convex combination of the τ\tau of the points of E0E_0, which are in CC. If W>0W > 0, put μpq=λpλq(φp−φq)/W≥0\mu_{pq} = \lambda_p \lambda_q (\varphi_p - \varphi_q) / W \ge 0 for p∈E+p \in E_+, q∈E−q \in E_-. Then

∑p,qμpqcpq=1W∑p,qλpλq(φpτq−φqτp)=∑qλqτq+∑pλpτp,\sum_{p, q} \mu_{pq} c_{pq} = \frac{1}{W} \sum_{p, q} \lambda_p \lambda_q (\varphi_p \tau_q - \varphi_q \tau_p) = \sum_q \lambda_q \tau_q + \sum_p \lambda_p \tau_p,

and in the same way ∑p,qμpq=∑qλq+∑pλp\sum_{p,q} \mu_{pq} = \sum_{q} \lambda_q + \sum_p \lambda_p. So τ=∑e∈E0λeτe+∑p,qμpqcpq\tau = \sum_{e \in E_0} \lambda_e \tau_e + \sum_{p,q} \mu_{pq} c_{pq} with nonnegative weights of sum 11, a convex combination of elements of CC. In both cases C≠∅C \ne \emptyset and τ\tau lies between min⁡C\min C and max⁡C\max C. □\square

Claim 3 (line L4 keeps every root). Assume the invariant on a box XX, and let x∈Xx \in X be a zero of fkf_k with local coordinates uu. Then for every axis jj the interval [s,t][s, t] that line L4 computes from fkf_k exists and contains uju_j.

Proof. For each column ii of axis jj the code takes mi=min⁡ℓIm_i = \min \ell_I and Mi=max⁡hIM_i = \max h_I over the II with ij=ii_j = i. If dj=0d_j = 0, the polynomial does not depend on xjx_j, and 0=fk(x)=∑IBI(u)bI0 = f_k(x) = \sum_I B_I(u) b_I is a convex combination of the bIb_I by Claim 1, so m0≤min⁡bI≤0≤max⁡bI≤M0m_0 \le \min b_I \le 0 \le \max b_I \le M_0, and the code returns [0,1]∋uj[0, 1] \ni u_j. If dj≥1d_j \ge 1, Claim 1 gives

(uj,0)=(uj,fk(x))=∑IBI(u)(ijdj, bI),(u_j, 0) = \big(u_j, f_k(x)\big) = \sum_I B_I(u) \left(\tfrac{i_j}{d_j}, \, b_I\right),

a convex combination of the projected control points. By the invariant each point (i/dj,bI)(i/d_j, b_I) lies on the segment from (i/dj,mi)(i/d_j, m_i) to (i/dj,Mi)(i/d_j, M_i), so (uj,0)(u_j, 0) is in the convex hull of the set EE of these 2(dj+1)2(d_j + 1) ends. By Claim 2, the set CC is not empty and min⁡C≤uj≤max⁡C\min C \le u_j \le \max C. The code computes min⁡C\min C and max⁡C\max C exactly in rational arithmetic, rounds the first down and the second up to floats, and clips to [0,1][0, 1], which contains uju_j. □\square

So a box that line L5 discards has no root: either some fkf_k 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 ∏j[sj,tj]\prod_j [s_j, t_j], the intersection over kk.

Claim 4 (lines L7 and L8 keep the invariant and the roots). The de Casteljau scheme at a parameter τ∈[0,1]\tau \in [0, 1] along axis jj maps the Bernstein coefficients on a box to those on its two parts at the local value τ\tau of uju_j; this is the subdivision property of the de Casteljau algorithm, applied to each line of the tensor along axis jj (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 1−τ1 - \tau 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 [0,tj][0, t_j], at the float tjt_j. Then it keeps the part [r,1][r, 1] of that, with rr the float sj/tjs_j / t_j rounded down, so that the kept local range is [rtj,tj]⊇[sj,tj][r t_j, t_j] \supseteq [s_j, t_j]. The new ends are computed exactly from rr and tjt_j in rational arithmetic, so the coefficients belong to the stored box and every root of XX is in the new box. Line L8 splits at the local value 1/21/2 into two closed halves whose union is the box, and each root is in one of them. □\square

Claim 5 (termination). Let W=max⁡j(bj−aj)W = \max_j (b_j - a_j) and ε>0\varepsilon > 0. Every path from X0X_0 in the tree of boxes has at most n(1+log⁡2(W/ε))+1n (1 + \log_2(W / \varepsilon)) + 1 steps, and the method stops.

Proof. A step that does not discard or output its box has a widest side j∗j^* of width w≥εw \ge \varepsilon, by line L6. Line L7 only shrinks the sides. If side j∗j^* is then still longer than w/2w/2, line L8 halves it; otherwise it is already at most w/2w / 2. So each such step at least halves one side of width at least ε\varepsilon. A side of initial width w0≤Ww_0 \le W that has been halved kk times in this way had width at most w0/2k−1w_0 / 2^{k-1} before the last of them, and at least ε\varepsilon, so k≤1+log⁡2(W/ε)k \le 1 + \log_2(W / \varepsilon). Summing over the nn 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. □\square

Conclusion. By induction over the tree, with Claims 3 and 4 as the step: every root in X0X_0 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 ε\varepsilon, 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. ■\blacksquare

Complexity

One step costs O(mnN)O(m n N) to find the column ranges, O(mnd2)O(m n d^2) for the crossings, and O(mnNd)O(m n N d) for the de Casteljau restrictions, since each of the N/(dj+1)N / (d_j + 1) lines along axis jj takes O(dj2)O(d_j^2) operations. With KK boxes processed the time is O(KmnNd)O(K m n N d). The stack holds at most two boxes per level of the tree, so the extra space is O(DmN)O(D m N).

By the termination bound the tree has depth at most DD and at most 2D+1≤4(2W/ε)n2^{D+1} \le 4 (2W / \varepsilon)^n 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 ε\varepsilon. 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 m≠nm \ne n, 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 0.10.1, 0.60.6 and 0.70.7 where plain floats lose the root 0.70.7 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 1/ε1 / \varepsilon. 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 3232 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.

interval_projected_polyhedron.pyI0RawGitHub
# 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

  1. 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)
  2. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • at least three sources
  • a scene preset for the example