Algorithm Search⌘K

Algorithmadvanced

Algebraic surface intersection

Also called implicit-parametric surface intersection.

Substitutes a parametric surface into the implicit equation of the other, so the intersection becomes a plane algebraic curve in the parameter domain that is then traced.

Time
O(T k^3 m^2 n^2 + B b D^3 + A S b D^2) worst
Space
O(d D^2 + A S) extra
Where
A = the number of arcs; B = the number of boxes; D = the larger degree of the substituted polynomial; S = the samples per arc; T = the number of its terms; b = the bisection steps; d = the depth limit; k = the degree of the implicit polynomial; m = the first degree of the patch; n = the second degree of the patch
Properties
deterministicnot exactrecursive
Origin
Nicholas M. Patrikalakis, P. V. Prakash, 1990

Algebraic surface intersection computes the curve where a parametric patch r(u,v)r(u, v) meets an implicit surface f(x,y,z)=0f(x, y, z) = 0 by substitution: g(u,v)=f(r(u,v))g(u, v) = f(r(u, v)) is one polynomial in two unknowns, and its zero set in the parameter box is the intersection curve. The three dimensional problem becomes the problem of finding all branches of a plane algebraic curve. This page writes gg exactly in Bernstein form, subdivides the box until each piece is empty or holds a curve that is a graph over one parameter, and traces each piece. Unlike lattice evaluation and marching, it finds every closed loop, however small, and it boxes the singular points that it cannot trace.

In plain words

One surface is drawn by a formula with two numbers, like a map. The other is a rule that says which points are on it. Put the map formula into the rule, and you get one rule on the map: the crossing line is where this rule gives zero. Now the problem is flat, a curve on a square of paper.

To find all of that curve, cut the square into pieces. A piece where the rule is clearly positive everywhere, or clearly negative, holds no curve, and you drop it. A piece where the curve can only run left to right, never turning back, is easy: you find where it enters and leaves and follow it across. Any other piece is cut into four again. Only near a point where the curve crosses itself do the pieces become tiny, and those are reported as special.

The problem

The input is a tensor product Bézier patch rr of bidegree (m,n)(m, n) on Ω=[0,1]2\Omega = [0, 1]^2, given by its control net, an implicit surface f=0f = 0 with ff a polynomial of degree kk, a depth limit dd and a number SS of samples per arc. Rational patches work the same way after multiplying by a power of the weight, see Variants.

The output is a set of polylines in the parameter box, with every vertex on the curve Z={g=0}Z = \{g = 0\} to the precision of a bisection, the closed ones repeated at the end, and a list of boxes of side 2−d2^{-d} that may hold a singular point of ZZ, where g=gu=gv=0g = g_u = g_v = 0.

Since ff has degree kk and each coordinate of rr has bidegree (m,n)(m, n), gg has bidegree at most (M,N)=(km,kn)(M, N) = (km, kn). For a bicubic patch and a quadric that is (6,6)(6, 6).

The algorithm

  1. ALGEBRAIC-INTERSECT(r, f, d, S)
  2. 1G ← the Bernstein coefficients of g = f ∘ r on Ω, computed exactly
  3. 2stack ← [(G, Ω, 0)]
  4. 3while stack is not empty: pop (G, Q, depth)
  5. 4if all G_ij > 0 or all G_ij < 0 then continue ▷ no curve in Q
  6. 5if all G_i,j+1 − G_ij have one strict sign, or all G_i+1,j − G_ij do then
  7. 6find the roots of g on the edges of Q, sort them along the free parameter, pair neighbors, trace each pair with S bisections, and continue if the count is even
  8. 7if depth < d then split Q and G into four by de Casteljau and push them with depth + 1
  9. 8else report Q as a possible singular point
  10. 9chain the arcs at their common ends into curves
  11. 10return the curves and the reported boxes

Line L1 computes the products of the coordinate polynomials in the Bernstein basis by the product rule Bi,pBj,q=(pi)(qj)(p+qi+j)Bi+j,p+qB_{i, p} B_{j, q} = \frac{\binom{p}{i} \binom{q}{j}}{\binom{p + q}{i + j}} B_{i + j, p + q} in each parameter, with rational numbers, so the sign tests of lines L4 and L5 are exact. Line L4 drops a box by the convex hull property: gg lies between the least and the largest coefficient. Line L5 tests the coefficients of a derivative, which are the differences of neighboring coefficients. If gvg_v has a strict sign, each line u=constu = \text{const} meets the curve at most once in the box, so the curve there is a graph v=φ(u)v = \varphi(u), with no loop and no turning point. Line L6 finds the edge points as roots of univariate polynomials, pairs them in order of uu, and computes SS points between the ends of each pair by bisection on the monotone function v↦g(u,v)v \mapsto g(u, v). An odd count, from a tangency to an edge or a point at a corner, sends the box to line L7. Line L7 is the de Casteljau algorithm at 12\tfrac12 in each parameter.

Example

Take the bicubic bump r(u,v)=(3u,3v,27u(1−u)v(1−v))r(u, v) = (3u, 3v, 27 u (1 - u) v (1 - v)), with control points (i,j,zij)(i, j, z_{ij}), zij=3z_{ij} = 3 at the four inner points and 00 elsewhere, and the plane z=1z = 1. Then f=z−1f = z - 1 has degree 11, g=h−1g = h - 1 has bidegree (3,3)(3, 3), and its Bernstein coefficients are the control heights minus 11:

G=(−1−1−1−1−122−1−122−1−1−1−1−1).G = \begin{pmatrix} -1 & -1 & -1 & -1 \\ -1 & 2 & 2 & -1 \\ -1 & 2 & 2 & -1 \\ -1 & -1 & -1 & -1 \end{pmatrix}.

The signs are mixed, and both difference tables contain 00, so line L7 splits Ω\Omega. The quarter [0,12]2[0, \tfrac12]^2 has the coefficients

(−1−1−1−1−1−141818−11811161116−11811161116),\begin{pmatrix} -1 & -1 & -1 & -1 \\ -1 & -\tfrac14 & \tfrac18 & \tfrac18 \\ -1 & \tfrac18 & \tfrac{11}{16} & \tfrac{11}{16} \\ -1 & \tfrac18 & \tfrac{11}{16} & \tfrac{11}{16} \end{pmatrix},

again mixed, with zero differences in the last row and column, so it is split as well, and so are the other three quarters. Of the 1616 boxes of side 14\tfrac14, the 44 at the corners of Ω\Omega have only negative coefficients and are dropped. The 88 boxes along the edges of the inner square are monotone, and each holds one arc. For instance on [0.5,0.75]×[0,0.25][0.5, 0.75] \times [0, 0.25] the curve is a graph over uu from (0.5,0.180858)(0.5, 0.180858) to (0.729061,0.25)(0.729061, 0.25). The 44 boxes [0.25,0.5]×[0.25,0.5][0.25, 0.5] \times [0.25, 0.5] and its mirror images are split once more, and of their 1616 children 1212 are dropped and 44 hold one arc each. In all, 3737 boxes are visited and 1212 arcs found, and line L9 chains them into one closed curve. With S=4S = 4 it has 6161 vertices, each with ∣27u(1−u)v(1−v)−1∣<10−14|27 u (1 - u) v (1 - v) - 1| < 10^{-14}.

With the plane z=1.68z = 1.68 the curve is a loop of width 115\tfrac{1}{15} in uu around the top. Lattice evaluation with 33 lines in each direction misses it. Here the subdivision visits 8585 boxes and returns it as one closed curve. On the saddle z=9(u−12)(v−12)z = 9 (u - \tfrac12)(v - \tfrac12) cut by z=0z = 0, the curve is the two lines u=12u = \tfrac12 and v=12v = \tfrac12, which cross at a singular point. With d=6d = 6 the method returns four curves, each from an edge of Ω\Omega to the reported boxes, and the four boxes of side 164\tfrac{1}{64} around (12,12)(\tfrac12, \tfrac12).

Correctness

The full proof has five parts. A box dropped by line L4 holds no point of the curve, because gg is a convex combination of its Bernstein coefficients. The differences that line L5 tests are positive multiples of the Bernstein coefficients of gvg_v or gug_u, so a strict sign there means a strict sign of the derivative on the whole box. In such a box the curve is a graph over the other parameter, its ends are exactly the edge roots, and pairing them in sorted order gives the arcs, provided the edge roots are simple and the curve does not touch the box only at a corner. Together, the arcs and the boxes of line L8 cover the whole curve, and every closed loop is returned as a closed curve.

The last part is termination. If a box of side hh is split, then ∣g∣|g|, ∣gu∣|g_u| and ∣gv∣|g_v| are all at most a constant times hh at every point of it, with constants computed from the coefficients of the derivatives on Ω\Omega. So if the curve has no singular point, every box smaller than a positive number μ\mu is decided, and only boxes around singular points reach the depth limit. The proof uses only Bernstein facts that it proves. What is not exact are the edge roots and the traced points, which are floating point bisections from exact coefficients. The tests check the substitution exactly with rational numbers, and check on random bicubic patches cut by planes and spheres that the number of times the polylines cross 2020 fixed parameter lines equals the number of sign changes of gg in 20002000 samples on each line.

Proof: The subdivision of the substituted polynomial loses no piece of the intersection, pairs the boundary points of each monotone box correctly, and stops near every regular pointfull

Let rr be a polynomial patch of bidegree (m,n)(m, n) on Ω=[0,1]2\Omega = [0, 1]^2 and let ff be a polynomial of degree kk. Then g=f∘rg = f \circ r is a polynomial of bidegree at most (km,kn)(km, kn), and line L1 writes it in tensor product Bernstein form,

g(u,v)=∑i=0M∑j=0NGij Bi,M(u) Bj,N(v),M=km,  N=kn,g(u, v) = \sum_{i = 0}^{M} \sum_{j = 0}^{N} G_{ij} \, B_{i, M}(u) \, B_{j, N}(v), \qquad M = km, \; N = kn,

exactly, with rational coefficients. On a box Q=[u0,u0+h]×[v0,v0+h]Q = [u_0, u_0 + h] \times [v_0, v_0 + h] the coefficients GijQG^Q_{ij} are those of gg in the local coordinates s=(u−u0)/hs = (u - u_0)/h, t=(v−v0)/ht = (v - v_0)/h. Line L7 obtains them by de Casteljau halving, which replaces each list of coefficients by averages of its entries, so every coefficient on QQ is a convex combination of the coefficients on Ω\Omega. Write Z={x∈Ω:g(x)=0}Z = \{x \in \Omega : g(x) = 0\}.

Claim 1 (the convex hull bound). For every x∈Qx \in Q, min⁡ijGijQ≤g(x)≤max⁡ijGijQ\min_{ij} G^Q_{ij} \le g(x) \le \max_{ij} G^Q_{ij}. So a box excluded by line L4 holds no point of ZZ.

Proof. The Bernstein polynomials are nonnegative on [0,1][0, 1] and sum to 11, since ∑iBi,M(s)=(s+(1−s))M=1\sum_i B_{i, M}(s) = (s + (1 - s))^M = 1. So the products Bi,M(s)Bj,N(t)B_{i, M}(s) B_{j, N}(t) are nonnegative and sum to 11, and g(x)g(x) is a convex combination of the GijQG^Q_{ij}. If all of them are positive, so is gg on QQ, and the same for negative. □\square

Claim 2 (the monotone test). The differences Gi,j+1Q−GijQG^Q_{i, j+1} - G^Q_{ij}, which line L5 tests, are hN\frac{h}{N} times the Bernstein coefficients of degree (M,N−1)(M, N - 1) of gvg_v on QQ. So if they all have one strict sign, gvg_v has that sign on all of QQ. The same holds for uu.

Proof. Differentiating Bj,N(t)B_{j, N}(t) gives N(Bj−1,N−1(t)−Bj,N−1(t))N (B_{j - 1, N - 1}(t) - B_{j, N - 1}(t)), and collecting terms gives ∂t∑ijGijQBi,MBj,N=N∑i,j(Gi,j+1Q−GijQ)Bi,MBj,N−1\partial_t \sum_{ij} G^Q_{ij} B_{i, M} B_{j, N} = N \sum_{i, j} (G^Q_{i, j+1} - G^Q_{ij}) B_{i, M} B_{j, N - 1}. Since ∂t=h ∂v\partial_t = h \, \partial_v, the first statement follows, and Claim 1 applied to gvg_v gives the second. □\square

Claim 3 (the arcs of a monotone box). Let gvg_v have a strict sign on QQ, and assume that every root of gg on the bottom and top edges of QQ is simple and that no point of ZZ is a corner of QQ at which ZZ does not enter QQ. Sort the points of ZZ on the boundary of QQ by uu, as line L6 does, into p1,p2,…,p2qp_1, p_2, \dots, p_{2q}. Then Z∩QZ \cap Q consists of exactly qq disjoint arcs, the ℓ\ellth from p2ℓ−1p_{2\ell - 1} to p2ℓp_{2\ell}, and each is the graph v=φ(u)v = \varphi(u) of a continuous function over the interval between the uu values of its ends. The same holds with uu and vv exchanged.

Proof. Let Q=[u0,u1]×[v0,v1]Q = [u_0, u_1] \times [v_0, v_1] and say gv>0g_v > 0. For each uu the function v↦g(u,v)v \mapsto g(u, v) is strictly increasing, so it has at most one zero in [v0,v1][v_0, v_1], and it has one exactly when g(u,v0)≤0≤g(u,v1)g(u, v_0) \le 0 \le g(u, v_1). Let UU be the set of such uu and φ(u)\varphi(u) the zero. By the implicit function theorem, which applies because gv≠0g_v \ne 0, φ\varphi is continuous on UU, and Z∩QZ \cap Q is the graph of φ\varphi over UU.

The set UU is defined by two polynomial inequalities, so it is a finite union of disjoint closed intervals [a1,b1],…,[aq,bq][a_1, b_1], \dots, [a_q, b_q] with a1≤b1<a2≤…a_1 \le b_1 < a_2 \le \dots. Over each interval the graph is an arc, and its two ends are its points at u=aℓu = a_\ell and u=bℓu = b_\ell. An end at u=aℓ>u0u = a_\ell > u_0 is a point where g(u,v0)g(u, v_0) or g(u,v1)g(u, v_1) changes sign, so it is a root on the bottom or top edge, and conversely a simple root on the bottom or top edge is such a change of sign, so it is an end. An end at u=u0u = u_0 is the zero of gg on the left edge, and the same at u1u_1. The assumption on the corners excludes aℓ=bℓa_\ell = b_\ell, which would be an isolated point of Z∩QZ \cap Q at a corner. So the boundary points of ZZ on QQ are exactly the 2q2q ends, their uu values are a1<b1<a2<b2<…a_1 < b_1 < a_2 < b_2 < \dots, and two ends never share a uu value, because a line u=constu = \text{const} meets Z∩QZ \cap Q at most once. Sorting by uu and pairing neighbors gives the arcs. □\square

The tracing of line L6 computes, for uu values between the ends of an arc, the zero φ(u)\varphi(u) by bisection on the monotone function v↦g(u,v)v \mapsto g(u, v). So every vertex of the output lies on ZZ to the bisection tolerance, and since QQ is convex, every edge of the polyline lies in QQ, as does the arc it replaces. The distance between them is at most the diagonal of QQ, which is all that is proved about it.

Claim 4 (nothing is lost). Every point of ZZ lies in a box excluded by no test, that is, in a monotone box handled by line L6 or in a box of line L8. Under the assumptions of Claim 3 on every monotone box, the arcs of line L6 together with the boxes of line L8 cover ZZ, and line L9 chains the arcs into the components of ZZ outside the boxes of line L8.

Proof. The leaves of the subdivision cover Ω\Omega. A leaf is excluded only by line L4, which holds no point of ZZ by Claim 1. In a monotone leaf, Claim 3 gives all of ZZ there as arcs. A point where two leaves meet that is on ZZ is the end of an arc in each leaf that ZZ enters, so the arcs that share an end are consecutive pieces of one component, and line L9 joins them. A closed component of ZZ is cut by the leaves into arcs whose ends join in a cycle, so it is returned as a closed curve, however small it is. □\square

Claim 5 (termination near regular points). Let LuL_u and LvL_v be the largest absolute values of the Bernstein coefficients of gug_u and gvg_v on Ω\Omega, and put K0=2(Lu+Lv)K_0 = 2 (L_u + L_v). Define KuK_u and KvK_v the same way from the second derivatives. If a box of side hh is split, then at every point xx of it,

∣g(x)∣≤K0h,∣gu(x)∣≤Kuh,∣gv(x)∣≤Kvh.|g(x)| \le K_0 h, \qquad |g_u(x)| \le K_u h, \qquad |g_v(x)| \le K_v h.

Hence, if ZZ has no singular point in Ω\Omega, that is, no point where g=gu=gv=0g = g_u = g_v = 0, the number μ=min⁡x∈Ωmax⁡(∣g∣/K0,∣gu∣/Ku,∣gv∣/Kv)\mu = \min_{x \in \Omega} \max(|g| / K_0, |g_u| / K_u, |g_v| / K_v) is positive, and no box of side less than μ\mu is split, except for a box rejected at line L6 by the assumptions of Claim 3.

Proof. On QQ, by Claim 2, ∣Gi+1,jQ−GijQ∣=hM∣cij∣|G^Q_{i+1, j} - G^Q_{ij}| = \frac{h}{M} |c_{ij}|, where cijc_{ij} is a coefficient of gug_u on QQ, a convex combination of the coefficients on Ω\Omega, so ∣cij∣≤Lu|c_{ij}| \le L_u. The same holds in vv. Walking from G00QG^Q_{00} to GijQG^Q_{ij} in at most MM steps in ii and NN steps in jj gives ∣GijQ−G00Q∣≤h(Lu+Lv)|G^Q_{ij} - G^Q_{00}| \le h (L_u + L_v). Since G00Q=g(u0,v0)G^Q_{00} = g(u_0, v_0) and ∣gu∣≤Lu|g_u| \le L_u, ∣gv∣≤Lv|g_v| \le L_v on Ω\Omega by Claim 1, ∣g(x)−g(u0,v0)∣≤h(Lu+Lv)|g(x) - g(u_0, v_0)| \le h (L_u + L_v) for x∈Qx \in Q. So every coefficient is within K0hK_0 h of g(x)g(x). If g(x)>K0hg(x) > K_0 h, all coefficients are positive and line L4 excludes QQ, and the same for g(x)<−K0hg(x) < -K_0 h. The same argument for gug_u and gvg_v shows that if ∣gv(x)∣>Kvh|g_v(x)| > K_v h or ∣gu(x)∣>Kuh|g_u(x)| > K_u h, line L5 finds a strict sign. A box that is split therefore has all three bounds at every point. If h<μh < \mu, some point of the box has one of the three ratios above hh, a contradiction. The minimum is attained because Ω\Omega is compact, and it is 00 exactly at a singular point of ZZ. □\square

So, with no singular point and no tangency of ZZ to the lines u=i/2du = i / 2^d and v=j/2dv = j / 2^d, the depth of the subdivision is at most ⌈log⁡2(1/μ)⌉\lceil \log_2 (1 / \mu) \rceil, and boxes reach line L8 only around singular points or such tangencies. At a singular point every box that contains it is split, so with a depth limit dd line L8 returns the boxes of side 2−d2^{-d} that contain it, which isolates it. ■\blacksquare

Complexity

Line L1 makes, for each of the TT terms of ff, at most kk products of Bernstein arrays of size at most (km+1)(kn+1)(km + 1)(kn + 1) by arrays of size (m+1)(n+1)(m + 1)(n + 1), which costs O(Tk3m2n2)O(T k^3 m^2 n^2) operations on rational numbers. Each box costs O(D3)O(D^3) for the split, with D=max⁡(km,kn)D = \max(km, kn), and O(D2)O(D^2) for the sign tests. A monotone box costs O(bD3)O(b D^3) for the roots on its four edges, and each arc O(SbD2)O(S b D^2) for the tracing, with bb about 6060 bisection steps. With BB boxes and AA arcs, the total is O(Tk3m2n2+BbD3+ASbD2)O(T k^3 m^2 n^2 + B b D^3 + A S b D^2) operations. The proof of termination bounds the depth by ⌈log⁡2(1/μ)⌉\lceil \log_2 (1 / \mu) \rceil when the curve has no singular point, so B≤43⋅4⌈log⁡2(1/μ)⌉B \le \frac{4}{3} \cdot 4^{\lceil \log_2 (1 / \mu) \rceil}, a bound that is far from tight: boxes away from the curve are dropped early, and for a regular curve the number of boxes grows with its length divided by the box size. The stack is depth first, so it holds at most 33 boxes per level, O(dD2)O(d D^2) coefficients for the depth limit dd, and the output takes O(AS)O(A S). The cost of the rational numbers grows with the depth, since each halving adds a factor of 22 to the denominators.

Properties

  • Complete. Every point of the curve is in a returned arc or a returned box, with the conditions of the proof. Small loops are not lost.
  • Exact decisions. The tests that drop boxes and that find monotone boxes use exact rational arithmetic, so they are never wrong because of rounding.
  • Isolates singular points. Boxes around a crossing of the curve reach the depth limit, so the method reports where it could not decide.
  • Local work. Boxes are independent, and the work is spent near the curve.

Variants and improvements

  • Characteristic points first. Patrikalakis and Prakash compute the border points, the turning points where g=gu=0g = g_u = 0 or g=gv=0g = g_v = 0, and the singular points, and then split the box at them into parts that are traced one at a time. The monotone boxes of this page play the role of those parts: a box with a strict sign of gvg_v holds no point where gv=0g_v = 0. The characteristic points can be found with the interval projected polyhedron method.
  • Rational patches. For r=(X,Y,Z)/Wr = (X, Y, Z) / W use the numerator Wkf(X/W,Y/W,Z/W)W^k f(X / W, Y / W, Z / W), the homogenized ff at (X,Y,Z,W)(X, Y, Z, W). It has the same zeros where W>0W > 0.
  • Marching on the plane curve. Trace the curve from the border and turning points with a predictor and corrector step in the plane, as in marching, using the characteristic points to guarantee that all branches are found.
  • Two parametric patches. When both surfaces are parametric, the implicitization of one of them gives an implicit equation, and this method applies. The degree of the implicit form, up to 2mn2mn, makes this practical only for low degrees.
  • Quadrics. When both surfaces are quadrics, Levin's method gives a parametrization of the curve instead of a traced one.

When to use it

Use it when one surface is implicit, such as a plane, a quadric, a torus or an offset of one, and the other is a patch: plane sections for slicing and contouring, cuts by cylinders and spheres in machining, and Booleans between primitives and freeform faces. It is the method of choice when no loop may be lost. When both surfaces are freeform of high degree, use subdivision or marching instead.

Pitfalls

  • Coefficient growth. The degree of gg is kk times that of the patch. A bicubic and a quartic, such as a torus, give bidegree (12,12)(12, 12), 169169 coefficients, and the rationals grow with the depth.
  • Tangential intersections. Where the two surfaces touch, gg has a double zero along the curve, so gg, gug_u and gvg_v all vanish there, and every box along the curve reaches the depth limit. The method then returns a chain of boxes, not a curve. See tangential surface intersection.
  • Dyadic coincidences. A curve that passes through a corner of the dyadic subdivision without entering a box, or is tangent to a line u=i/2ju = i / 2^j, gives an odd count in a monotone box, and that box is split down to the depth limit. Symmetric test cases hit this often.
  • Parameter space only. The curve is computed in the parameter box of rr. Points in space are r(u,v)r(u, v), and a short distance in the box can be a long one in space where the patch is stretched.
  • Floating point coefficients. Running the sign tests in floating point makes them unreliable when coefficients are near 00, which is exactly near the curve. Exact or interval arithmetic keeps line L4 from dropping a box that holds the curve.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

algebraic_surface_intersection.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/algebraic-surface-intersection/. The authors are listed in prov/38DDQS.jsonl.

"""Intersection of a Bezier patch with an implicit algebraic surface.

The patch r(u, v) on [0, 1] x [0, 1] is given by its control net, the second
surface by a polynomial f(x, y, z), a dictionary that maps an exponent triple
(a, b, c) to the coefficient of x^a y^b z^c. Substituting r into f gives one
polynomial g(u, v) = f(r(u, v)), whose zero set in the parameter box is the
intersection curve. The code forms g in tensor product Bernstein form with
exact rational arithmetic, subdivides the box until each piece either holds no
zero of g, by the signs of its coefficients, or holds a curve that is a graph
over one parameter, by the signs of the coefficients of a derivative. In such
a piece the boundary points of the curve are paired in order and each arc is
traced by bisection. The arcs are chained into curves. Pieces smaller than
2^-max_depth that are neither are returned as candidates for singular points.
"""

from fractions import Fraction
from math import comb
from typing import Sequence

from si1geom import Vec, bernstein, pmul, ppow, pscale, padd, real_roots

Grid = list  # a (p + 1) x (q + 1) list of lists of Bernstein coefficients


def bern_product(A: Grid, B: Grid) -> Grid:
    """Bernstein coefficients of the product of two tensor product polynomials."""
    p, q, r, s = len(A) - 1, len(A[0]) - 1, len(B) - 1, len(B[0]) - 1
    C = [[Fraction(0)] * (q + s + 1) for _ in range(p + r + 1)]
    for a in range(p + 1):
        for b in range(q + 1):
            x = A[a][b] * comb(p, a) * comb(q, b)
            if x == 0:
                continue
            for c in range(r + 1):
                for d in range(s + 1):
                    if B[c][d] != 0:
                        C[a + c][b + d] += x * B[c][d] * comb(r, c) * comb(s, d)
    return [[C[i][j] / (comb(p + r, i) * comb(q + s, j)) for j in range(q + s + 1)] for i in range(p + r + 1)]


def substitute(P: Sequence[Sequence[Vec]], f: dict) -> Grid:
    """Exact Bernstein coefficients of g = f(r(u, v)), of bidegree (k m, k n)."""
    m, n = len(P) - 1, len(P[0]) - 1
    coords = [[[Fraction(P[i][j][c]) for j in range(n + 1)] for i in range(m + 1)] for c in range(3)]
    ones = [[Fraction(1)] * (n + 1) for _ in range(m + 1)]
    k = max(sum(e) for e in f)
    powers = [{0: [[Fraction(1)]]} for _ in range(3)]

    def power(c: int, e: int) -> Grid:
        if e not in powers[c]:
            powers[c][e] = bern_product(power(c, e - 1), coords[c])
        return powers[c][e]

    G = [[Fraction(0)] * (k * n + 1) for _ in range(k * m + 1)]
    for (a, b, c), coef in f.items():
        T = bern_product(bern_product(power(0, a), power(1, b)), power(2, c))
        for _ in range(k - a - b - c):
            T = bern_product(T, ones)
        cf = Fraction(coef)
        for i in range(k * m + 1):
            for j in range(k * n + 1):
                G[i][j] += cf * T[i][j]
    return G


def _halves(c: list) -> tuple:
    left, right, cur = [c[0]], [c[-1]], list(c)
    while len(cur) > 1:
        cur = [(cur[i] + cur[i + 1]) / 2 for i in range(len(cur) - 1)]
        left.append(cur[0])
        right.append(cur[-1])
    return left, right[::-1]


def _split(G: Grid) -> list:
    """The four quarters of G, in the order (low u, low v), (low u, high v), (high u, low v), (high u, high v)."""
    M, N = len(G) - 1, len(G[0]) - 1
    lo = [[None] * (N + 1) for _ in range(M + 1)]
    hi = [[None] * (N + 1) for _ in range(M + 1)]
    for j in range(N + 1):
        a, b = _halves([G[i][j] for i in range(M + 1)])
        for i in range(M + 1):
            lo[i][j], hi[i][j] = a[i], b[i]
    out = []
    for H in (lo, hi):
        rows = [_halves(H[i]) for i in range(M + 1)]
        out.append([rows[i][0] for i in range(M + 1)])
        out.append([rows[i][1] for i in range(M + 1)])
    return out


def _strict_sign(vals) -> int:
    vals = list(vals)
    if all(x > 0 for x in vals):
        return 1
    if all(x < 0 for x in vals):
        return -1
    return 0


def _edge_roots(c: list) -> list:
    """Roots in [0, 1] of the univariate Bernstein polynomial with coefficients c."""
    d = len(c) - 1
    poly = [Fraction(0)]
    for i, x in enumerate(c):
        if x != 0:
            poly = padd(poly, pscale(x * comb(d, i), pmul(ppow([0, 1], i), ppow([1, -1], d - i))))
    return real_roots(poly, 0.0, 1.0)


def _eval(Gf: Grid, s: float, t: float) -> float:
    bs, bt = bernstein(len(Gf) - 1, s), bernstein(len(Gf[0]) - 1, t)
    return sum(bs[i] * sum(bt[j] * Gf[i][j] for j in range(len(bt))) for i in range(len(bs)))


def _root_in(Gf: Grid, s: float, along_t: bool) -> float:
    """The root of the monotone function t -> g(s, t) (or s -> g(t, s)) in [0, 1], by bisection."""
    def h(t):
        return _eval(Gf, s, t) if along_t else _eval(Gf, t, s)
    a, b = 0.0, 1.0
    ha = h(a)
    for _ in range(60):
        mid = 0.5 * (a + b)
        hm = h(mid)
        if hm == 0:
            return mid
        if (hm < 0) == (ha < 0):
            a, ha = mid, hm
        else:
            b = mid
    return 0.5 * (a + b)


def _box_arcs(G: Grid, box: tuple, mono_v: bool, samples: int):
    """Arcs of g = 0 in a box where g is strictly monotone in v (mono_v) or in u.

    Returns None when the boundary points cannot be paired (an odd count)."""
    u0, u1, v0, v1 = box
    M, N = len(G) - 1, len(G[0]) - 1
    found = []
    for t in _edge_roots([G[i][0] for i in range(M + 1)]):
        found.append((u0 + t * (u1 - u0), v0))
    for t in _edge_roots([G[i][N] for i in range(M + 1)]):
        found.append((u0 + t * (u1 - u0), v1))
    for t in _edge_roots(G[0]):
        found.append((u0, v0 + t * (v1 - v0)))
    for t in _edge_roots(G[M]):
        found.append((u1, v0 + t * (v1 - v0)))
    pts = []
    for p in found:
        if all(abs(p[0] - q[0]) + abs(p[1] - q[1]) > 1e-10 for q in pts):
            pts.append(p)
    if len(pts) % 2:
        return None
    axis = 0 if mono_v else 1
    pts.sort(key=lambda p: p[axis])
    Gf = [[float(x) for x in row] for row in G]
    arcs = []
    for a, b in zip(pts[0::2], pts[1::2]):
        line = [a]
        for k in range(1, samples + 1):
            if mono_v:
                u = a[0] + (b[0] - a[0]) * k / (samples + 1)
                s = (u - u0) / (u1 - u0)
                line.append((u, v0 + (v1 - v0) * _root_in(Gf, s, True)))
            else:
                v = a[1] + (b[1] - a[1]) * k / (samples + 1)
                t = (v - v0) / (v1 - v0)
                line.append((u0 + (u1 - u0) * _root_in(Gf, t, False), v))
        line.append(b)
        arcs.append(line)
    return arcs


def algebraic_surface_intersection(P: Sequence[Sequence[Vec]], f: dict, max_depth: int = 10,
                                   samples: int = 4, stats: dict = None) -> tuple:
    """Return (curves, singular): polylines of (u, v) on g = 0, a closed one
    repeating its first point at the end, and the boxes (u0, u1, v0, v1) left
    unresolved at depth max_depth."""
    G0 = substitute(P, f)  # @line L1
    stack = [(G0, (0.0, 1.0, 0.0, 1.0), 0)]  # @line L2
    arcs, singular = [], []
    boxes = 0
    while stack:  # @line L3
        G, box, depth = stack.pop()
        boxes += 1
        if _strict_sign(x for row in G for x in row):  # @line L4
            continue
        M, N = len(G) - 1, len(G[0]) - 1
        sv = _strict_sign(G[i][j + 1] - G[i][j] for i in range(M + 1) for j in range(N))  # @line L5
        su = 0 if sv else _strict_sign(G[i + 1][j] - G[i][j] for i in range(M) for j in range(N + 1))
        if sv or su:
            got = _box_arcs(G, box, bool(sv), samples)  # @line L6
            if got is not None:
                arcs += got
                continue
        if depth < max_depth:  # @line L7
            u0, u1, v0, v1 = box
            um, vm = 0.5 * (u0 + u1), 0.5 * (v0 + v1)
            subs = ((u0, um, v0, vm), (u0, um, vm, v1), (um, u1, v0, vm), (um, u1, vm, v1))
            for Q, b in zip(_split(G), subs):
                stack.append((Q, b, depth + 1))
        else:
            singular.append(box)  # @line L8
    if stats is not None:
        stats["boxes"] = boxes

    ends = []  # @line L9

    def node(p) -> int:
        for k, q in enumerate(ends):
            if abs(p[0] - q[0]) + abs(p[1] - q[1]) <= 1e-8:
                return k
        ends.append(p)
        return len(ends) - 1

    adj = {}
    for e, line in enumerate(arcs):
        a, b = node(line[0]), node(line[-1])
        adj.setdefault(a, []).append((e, b, False))
        adj.setdefault(b, []).append((e, a, True))
    used = [False] * len(arcs)
    curves = []
    for s in [a for a in adj if len(adj[a]) % 2] + list(adj):
        while any(not used[e] for e, _, _ in adj[s]):
            cur, curve = s, [ends[s]]
            while True:
                nxt = next(((e, b, rev) for e, b, rev in adj[cur] if not used[e]), None)
                if nxt is None:
                    break
                e, b, rev = nxt
                used[e] = True
                piece = arcs[e][::-1] if rev else arcs[e]
                curve += piece[1:-1] + [ends[b]]
                cur = b
            curves.append(curve)
    return curves, singular  # @line L10
si1geom.py 298 lines
# SPDX-License-Identifier: MIT
# Shared helper of the si1 cad pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small geometric and algebraic tools for the si1 pages.

Vectors are tuples of three numbers. A tensor product Bezier patch of bidegree
(m, n) is a list of m + 1 rows of n + 1 control points. Univariate polynomials
are lists of coefficients from the constant term up. Entries may be int,
Fraction or float; exact inputs give exact results where no square root or
division by a float is involved. No function here is the algorithm of a page.
"""

from fractions import Fraction
from math import comb, sqrt
from typing import Sequence

Vec = tuple
Num = float


# ---- vectors ---------------------------------------------------------------

def add(a: Vec, b: Vec) -> Vec:
    return (a[0] + b[0], a[1] + b[1], a[2] + b[2])


def sub(a: Vec, b: Vec) -> Vec:
    return (a[0] - b[0], a[1] - b[1], a[2] - b[2])


def scale(t, a: Vec) -> Vec:
    return (t * a[0], t * a[1], t * a[2])


def dot(a: Vec, b: Vec):
    return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]


def cross(a: Vec, b: Vec) -> Vec:
    return (a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0])


def norm(a: Vec) -> float:
    return sqrt(float(dot(a, a)))


def lincomb(ws: Sequence, ps: Sequence[Vec]) -> Vec:
    """Return sum of ws[i] * ps[i]."""
    x = y = z = 0
    for w, p in zip(ws, ps):
        x += w * p[0]
        y += w * p[1]
        z += w * p[2]
    return (x, y, z)


# ---- Bernstein basis -------------------------------------------------------

def bernstein(n: int, t) -> list:
    """Values B_{i,n}(t) for i = 0..n, by the explicit formula."""
    s = 1 - t
    return [comb(n, i) * t ** i * s ** (n - i) for i in range(n + 1)]


def bernstein_d(n: int, t, k: int) -> list:
    """k-th derivatives of B_{i,n} at t, for k = 0, 1, 2, from the difference formula."""
    if k == 0 or n == 0:
        return bernstein(n, t) if k == 0 else [0] * (n + 1)
    low = bernstein_d(n - 1, t, k - 1)
    out = []
    for i in range(n + 1):
        a = low[i - 1] if i >= 1 else 0
        b = low[i] if i <= n - 1 else 0
        out.append(n * (a - b))
    return out


def patch_point(P: Sequence[Sequence[Vec]], u, v) -> Vec:
    m, n = len(P) - 1, len(P[0]) - 1
    bu, bv = bernstein(m, u), bernstein(n, v)
    x = y = z = 0
    for i in range(m + 1):
        for j in range(n + 1):
            w = bu[i] * bv[j]
            q = P[i][j]
            x += w * q[0]
            y += w * q[1]
            z += w * q[2]
    return (x, y, z)


def patch_derivs(P: Sequence[Sequence[Vec]], u, v) -> tuple:
    """Return (r, r_u, r_v, r_uu, r_uv, r_vv) of a Bezier patch at (u, v)."""
    m, n = len(P) - 1, len(P[0]) - 1
    U = [bernstein_d(m, u, k) for k in range(3)]
    V = [bernstein_d(n, v, k) for k in range(3)]
    out = []
    for a, b in ((0, 0), (1, 0), (0, 1), (2, 0), (1, 1), (0, 2)):
        x = y = z = 0
        for i in range(m + 1):
            ui = U[a][i]
            for j in range(n + 1):
                w = ui * V[b][j]
                q = P[i][j]
                x += w * q[0]
                y += w * q[1]
                z += w * q[2]
        out.append((x, y, z))
    return tuple(out)


def curve_point(C: Sequence[Vec], t) -> Vec:
    return lincomb(bernstein(len(C) - 1, t), C)


# ---- univariate polynomials, coefficient lists from the constant term ------

def ptrim(a: list) -> list:
    a = list(a)
    while len(a) > 1 and a[-1] == 0:
        a.pop()
    return a


def padd(a: list, b: list) -> list:
    n = max(len(a), len(b))
    return ptrim([(a[i] if i < len(a) else 0) + (b[i] if i < len(b) else 0) for i in range(n)])


def pscale(c, a: list) -> list:
    return ptrim([c * x for x in a])


def pmul(a: list, b: list) -> list:
    out = [0] * (len(a) + len(b) - 1)
    for i, x in enumerate(a):
        if x == 0:
            continue
        for j, y in enumerate(b):
            out[i + j] += x * y
    return ptrim(out)


def ppow(a: list, k: int) -> list:
    out = [1]
    for _ in range(k):
        out = pmul(out, a)
    return out


def peval(a: list, t):
    s = 0
    for c in reversed(a):
        s = s * t + c
    return s


def pderiv(a: list) -> list:
    return ptrim([i * a[i] for i in range(1, len(a))]) if len(a) > 1 else [0]


def real_roots(a: list, lo: float, hi: float, tol: float = 1e-13) -> list:
    """Real roots of a polynomial in [lo, hi], each once, in increasing order.

    The roots of the derivative split [lo, hi] into pieces on which the
    polynomial is monotone; each piece holds at most one root, found by
    bisection. A root of even multiplicity is found when the polynomial is
    zero (to within the rounding of a float) at a critical point.
    """
    a = ptrim([float(c) for c in a])
    if len(a) == 1:
        return []
    crit = real_roots(pderiv(a), lo, hi, tol) if len(a) > 2 else []
    knots = [lo] + [c for c in crit if lo < c < hi] + [hi]
    scale_ = max(abs(c) for c in a)
    roots = []
    for x0, x1 in zip(knots, knots[1:]):
        f0, f1 = peval(a, x0), peval(a, x1)
        if f0 == 0 or abs(f0) <= 1e-14 * scale_:
            if not roots or abs(roots[-1] - x0) > 1e-9:
                roots.append(x0)
            continue
        if f0 * f1 > 0:
            continue
        if f1 == 0 or abs(f1) <= 1e-14 * scale_:
            continue
        a0, a1 = x0, x1
        while a1 - a0 > tol:
            mid = 0.5 * (a0 + a1)
            fm = peval(a, mid)
            if (fm < 0) == (f0 < 0):
                a0, f0 = mid, fm
            else:
                a1 = mid
        roots.append(0.5 * (a0 + a1))
    f_hi = peval(a, hi)
    if abs(f_hi) <= 1e-14 * scale_ and (not roots or abs(roots[-1] - hi) > 1e-9):
        roots.append(hi)
    return roots


# ---- dense linear algebra --------------------------------------------------

def solve(A: list, b: list) -> list:
    """Solve A x = b by Gaussian elimination with partial pivoting.

    Works for Fraction entries (exact, pivot = first nonzero) and for floats.
    Raises ZeroDivisionError when A is singular (exactly, or to the pivot test
    1e-300 for floats).
    """
    n = len(A)
    M = [list(A[i]) + [b[i]] for i in range(n)]
    for c in range(n):
        piv = max(range(c, n), key=lambda r: abs(M[r][c]))
        if M[piv][c] == 0 or (isinstance(M[piv][c], float) and abs(M[piv][c]) < 1e-300):
            raise ZeroDivisionError("singular matrix")
        M[c], M[piv] = M[piv], M[c]
        for r in range(c + 1, n):
            f = M[r][c] / M[c][c]
            if f != 0:
                for k in range(c, n + 1):
                    M[r][k] -= f * M[c][k]
    x = [0] * n
    for i in range(n - 1, -1, -1):
        s = M[i][n] - sum(M[i][k] * x[k] for k in range(i + 1, n))
        x[i] = s / M[i][i]
    return x


def det(A: list):
    """Determinant by fraction free Bareiss elimination for int and Fraction
    entries, and by Gaussian elimination for floats."""
    n = len(A)
    if n == 0:
        return 1
    if any(isinstance(x, float) for row in A for x in row):
        M = [list(map(float, row)) for row in A]
        d = 1.0
        for c in range(n):
            piv = max(range(c, n), key=lambda r: abs(M[r][c]))
            if M[piv][c] == 0:
                return 0.0
            if piv != c:
                M[c], M[piv] = M[piv], M[c]
                d = -d
            d *= M[c][c]
            for r in range(c + 1, n):
                f = M[r][c] / M[c][c]
                for k in range(c, n):
                    M[r][k] -= f * M[c][k]
        return d
    M = [[Fraction(x) for x in row] for row in A]
    sign = 1
    prev = Fraction(1)
    for c in range(n - 1):
        if M[c][c] == 0:
            piv = next((r for r in range(c + 1, n) if M[r][c] != 0), None)
            if piv is None:
                return Fraction(0)
            M[c], M[piv] = M[piv], M[c]
            sign = -sign
        for r in range(c + 1, n):
            for k in range(c + 1, n):
                M[r][k] = (M[r][k] * M[c][c] - M[r][c] * M[c][k]) / prev
            M[r][c] = Fraction(0)
        prev = M[c][c]
    return sign * M[n - 1][n - 1]


def jacobi_eigen(A: list, sweeps: int = 60) -> tuple:
    """Eigenvalues and eigenvectors of a small symmetric float matrix by the
    cyclic Jacobi method. Returns (values, vectors) with vectors[k] the unit
    eigenvector of values[k], sorted by increasing value."""
    n = len(A)
    M = [[float(x) for x in row] for row in A]
    V = [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]
    for _ in range(sweeps):
        off = sum(M[i][j] ** 2 for i in range(n) for j in range(n) if i != j)
        if off < 1e-30:
            break
        for p in range(n - 1):
            for q in range(p + 1, n):
                if abs(M[p][q]) < 1e-300:
                    continue
                theta = (M[q][q] - M[p][p]) / (2 * M[p][q])
                t = (1.0 if theta >= 0 else -1.0) / (abs(theta) + sqrt(theta * theta + 1))
                c = 1 / sqrt(t * t + 1)
                s = t * c
                for k in range(n):
                    mkp, mkq = M[k][p], M[k][q]
                    M[k][p], M[k][q] = c * mkp - s * mkq, s * mkp + c * mkq
                for k in range(n):
                    mpk, mqk = M[p][k], M[q][k]
                    M[p][k], M[q][k] = c * mpk - s * mqk, s * mpk + c * mqk
                for k in range(n):
                    vkp, vkq = V[k][p], V[k][q]
                    V[k][p], V[k][q] = c * vkp - s * vkq, s * vkp + c * vkq
    order = sorted(range(n), key=lambda i: M[i][i])
    return [M[i][i] for i in order], [[V[k][i] for k in range(n)] for i in order]
test_algebraic_surface_intersection.py 104 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/algebraic-surface-intersection/. The authors are listed in prov/38DDQS.jsonl.

import random
import unittest
from fractions import Fraction

from algebraic_surface_intersection import algebraic_surface_intersection, substitute
from si1geom import bernstein, patch_point

Z = [[0, 0, 0, 0], [0, 3, 3, 0], [0, 3, 3, 0], [0, 0, 0, 0]]
BUMP = [[(i, j, Z[i][j]) for j in range(4)] for i in range(4)]
SADDLE = [[(i, j, (i - 1.5) * (j - 1.5)) for j in range(4)] for i in range(4)]


def eval_f(f, q):
    return sum(c * q[0] ** a * q[1] ** b * q[2] ** e for (a, b, e), c in f.items())


def random_case(rng):
    P = [[(i + rng.randint(-3, 3) / 8, j + rng.randint(-3, 3) / 8, rng.randint(-24, 24) / 8)
          for j in range(4)] for i in range(4)]
    if rng.random() < 0.5:
        f = {(1, 0, 0): rng.randint(-8, 8) / 8, (0, 1, 0): rng.randint(-8, 8) / 8, (0, 0, 1): 1,
             (0, 0, 0): rng.randint(-8, 8) / 8}
    else:
        cx, cy, cz, R = rng.randint(0, 12) / 4, rng.randint(0, 12) / 4, rng.randint(-4, 4) / 4, rng.randint(4, 8) / 4
        f = {(2, 0, 0): 1, (0, 2, 0): 1, (0, 0, 2): 1, (1, 0, 0): -2 * cx, (0, 1, 0): -2 * cy,
             (0, 0, 1): -2 * cz, (0, 0, 0): cx * cx + cy * cy + cz * cz - R * R}
    return P, f


def crossings(curves, along_v, c):
    """Number of times the polylines cross the line u = c (along_v) or v = c."""
    k = 0 if along_v else 1
    return sum(1 for line in curves for a, b in zip(line, line[1:]) if (a[k] - c) * (b[k] - c) < 0)


def sign_changes(P, f, along_v, c, samples):
    vals = [eval_f(f, patch_point(P, c, t / samples) if along_v else patch_point(P, t / samples, c))
            for t in range(samples + 1)]
    return sum(1 for a, b in zip(vals, vals[1:]) if a * b < 0)


class TestAlgebraicSurfaceIntersection(unittest.TestCase):
    def test_substitution_is_exact(self):
        rng = random.Random(1)
        for _ in range(5):
            P, f = random_case(rng)
            G = substitute(P, f)
            for _ in range(4):
                u, v = Fraction(rng.randint(0, 64), 64), Fraction(rng.randint(0, 64), 64)
                bu, bv = bernstein(len(G) - 1, u), bernstein(len(G[0]) - 1, v)
                g = sum(bu[i] * bv[j] * G[i][j] for i in range(len(bu)) for j in range(len(bv)))
                q = patch_point([[tuple(Fraction(x) for x in p) for p in row] for row in P], u, v)
                self.assertEqual(g, eval_f({e: Fraction(c) for e, c in f.items()}, q))

    def test_example_plane_and_bump(self):
        G = substitute(BUMP, {(0, 0, 1): 1, (0, 0, 0): -1})
        self.assertEqual(G, [[-1, -1, -1, -1], [-1, 2, 2, -1], [-1, 2, 2, -1], [-1, -1, -1, -1]])
        stats = {}
        curves, singular = algebraic_surface_intersection(BUMP, {(0, 0, 1): 1, (0, 0, 0): -1}, stats=stats)
        self.assertEqual(stats["boxes"], 37)
        self.assertEqual(singular, [])
        self.assertEqual(len(curves), 1)
        self.assertEqual(curves[0][0], curves[0][-1])
        for u, v in curves[0]:
            self.assertAlmostEqual(27 * u * (1 - u) * v * (1 - v), 1.0, places=12)

    def test_small_loop_is_found(self):
        curves, singular = algebraic_surface_intersection(BUMP, {(0, 0, 1): 1, (0, 0, 0): -1.68})
        self.assertEqual((len(curves), singular), (1, []))
        self.assertEqual(curves[0][0], curves[0][-1])
        us = [u for u, v in curves[0]]
        self.assertAlmostEqual(max(us) - min(us), 1 / 15, places=6)

    def test_singular_point_is_boxed(self):
        curves, singular = algebraic_surface_intersection(SADDLE, {(0, 0, 1): 1}, max_depth=6)
        self.assertEqual(len(singular), 4)
        for u0, u1, v0, v1 in singular:
            self.assertTrue(u0 <= 0.5 <= u1 and v0 <= 0.5 <= v1)
        self.assertEqual(len(curves), 4)

    def test_against_grid_sign_changes(self):
        rng = random.Random(23)
        lines = [k / 10 + 0.0123 for k in range(10)]
        total = 0
        for _ in range(16):
            P, f = random_case(rng)
            curves, singular = algebraic_surface_intersection(P, f, samples=12)
            self.assertEqual(singular, [])
            for line in curves:
                for u, v in line:
                    self.assertLess(abs(eval_f(f, patch_point(P, u, v))), 1e-9)
            for c in lines:
                for along_v in (True, False):
                    want = sign_changes(P, f, along_v, c, 2000)
                    self.assertEqual(crossings(curves, along_v, c), want)
                    total += want
        self.assertGreater(total, 100)


if __name__ == "__main__":
    unittest.main()

History

Farouki (1986) studied the sections of polynomial patches by algebraic surfaces as plane algebraic curves in the parameter domain. Patrikalakis and Prakash (1990) combined the Bernstein form of that curve over a rectangle, adaptive subdivision, and the computation of turning and singular points, so that each part of the domain could be traced independently, and the approach was extended by Kriezis, Prakash and Patrikalakis in the same year. Patrikalakis and Maekawa (2002) give it as the method for a rational patch against an implicit algebraic surface in their book.

References

  1. Nicholas M. Patrikalakis and Takashi Maekawa, Shape Interrogation for Computer Aided Design and Manufacturing, Springer, 2002, Chapter 5, Section 5.8.1, the intersection of a rational polynomial parametric surface with an implicit algebraic surface (substitution, the plane algebraic curve in the parameter box, its border, turning and singular points, and tracing)
  2. N. M. Patrikalakis and P. V. Prakash, Surface intersections for geometric modeling, Journal of Mechanical Design 112(1), 100 to 107, 1990, the method of the abstract (the curve in the Bernstein basis over a rectangle, adaptive subdivision, turning and singular points, and tracing of the parts; general locator)
  3. Rida T. Farouki, The characterization of parametric surface sections, Computer Vision, Graphics, and Image Processing 33(2), 209 to 236, 1986, the whole paper (sections of polynomial patches by an algebraic surface as plane algebraic curves in the parameter domain; general locator)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

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
  • a scene preset for the example