Algorithm Search⌘K

Algorithmadvanced

Levin's quadric intersection method

Also called Levin pencil method, quadric surface intersection.

Intersects two quadrics by finding a ruled quadric in their pencil, parameterizing it, and solving a quadratic along each ruling, after Levin in 1976.

Time
O(N) worst
Space
O(N) extra
Where
N = the number of sample values of the ruling parameter u
Properties
deterministicnot exactiterative
Origin
Joshua Levin, 1976

Levin's method computes the intersection curve of two quadric surfaces S=0S = 0 and T=0T = 0. Every surface αS+βT=0\alpha S + \beta T = 0 of their pencil passes through the curve, and the method picks a member RR that is ruled in a simple way: it has a parametrization p(u)+v d(u)p(u) + v \, d(u) that is linear in vv. On each line of RR the other quadric becomes a quadratic equation in vv, so the curve is found by solving one quadratic per value of uu, in closed form.

In plain words

Two curved surfaces of the simplest kind, such as a sphere and a cylinder, cross along a curve. Mixing their equations in any proportion gives a new surface that still passes through that curve. Among these mixtures there is always one that is made of straight lines, like a sheet of paper that is bent but not stretched, or a saddle that can be built from straight sticks. The method finds that one.

Now walk along the straight lines of that surface, one by one. Each line meets the other surface in at most two points, and finding them is only a school quadratic equation. Collect the points for many lines and you have the whole curve, as a formula in the line number.

The only hard step is to find the right mixture, and that is a cubic equation.

The problem

A quadric is a surface Q(x)=xTQux+2q⋅x+q0=0Q(x) = x^T Q_u x + 2 q \cdot x + q_0 = 0 in R3\mathbb{R}^3, stored as the symmetric 4×44 \times 4 matrix QQ with upper left block QuQ_u, last column (q,q0)(q, q_0), so that Q(x)=XTQXQ(x) = X^T Q X for X=(x,1)X = (x, 1) in homogeneous coordinates. Spheres, ellipsoids, cylinders, cones, paraboloids, hyperboloids and pairs of planes are quadrics. The input is two quadrics SS and TT that are not multiples of each other, and a list UU of sample values. The output is a description of their real intersection curve: a member RR of the pencil, its sheets p(u)+v d(u)p(u) + v \, d(u), and for each sample uu the points of the curve on the line of uu, at most two per line, or the whole line when it lies in both quadrics. The intersection of two quadrics is a curve of degree at most 44, so this is the closed form case of surface surface intersection.

The algorithm

The quadratic part αSu+βTu\alpha S_u + \beta T_u of a member is a symmetric 3×33 \times 3 matrix. The method needs a member whose quadratic part is singular and not semidefinite of rank 2, that is, not with one zero eigenvalue and two of the same sign. Such a member is a plane, two planes, a hyperbolic or parabolic cylinder, a hyperbolic paraboloid, or empty, a simple ruled quadric in Levin's sense. The members with a singular quadratic part are the roots of the cubic f(α,β)=det⁡(αSu+βTu)f(\alpha, \beta) = \det(\alpha S_u + \beta T_u).

  1. LEVIN(S, T, U)
  2. 1f ← the binary cubic det(α S_u + β T_u), from its values at four points
  3. 2C ← the real roots (α, β) of f on the unit circle, or, if f ≡ 0, a zero of the middle eigenvalue of α S_u + β T_u
  4. 3for each (α, β) ∈ C: R ← α S + β T
  5. 4G ← S if |β| ≥ |α| else T
  6. 5if R_u is singular and not semidefinite of rank 2: sheets ← the rulings p(u) + v d(u) of R = 0 from the principal axes of R_u, and stop
  7. 6for each sheet and each u ∈ U
  8. 7a ← dᵀ G_u d, b ← 2 d · (G_u p + g), c ← G(p); if a = b = c = 0, record the whole line
  9. 8for each real root v of a v² + b v + c = 0: output p(u) + v d(u)
  10. 9return R, its sheets, the points and the lines

Line L5 diagonalizes RuR_u with the Jacobi eigenvalue algorithm, completes the squares, and reads the type of RR from the signs of the eigenvalues and the linear part. In the principal coordinates P,Q,wP, Q, w, a hyperbolic paraboloid is P2−Q2+2ρw+c′=0P^2 - Q^2 + 2 \rho w + c' = 0, and with u=P−Qu = P - Q, v=P+Qv = P + Q it becomes w=−(uv+c′)/(2ρ)w = -(u v + c') / (2 \rho), linear in vv. A hyperbolic cylinder P2−Q2=kP^2 - Q^2 = k uses P−Q=uP - Q = u, P+Q=k/uP + Q = k / u and the free axis w=vw = v. A parabolic cylinder μs2+2nz+c′=0\mu s^2 + 2 n z + c' = 0 uses s=us = u and its free axis as vv. A plane uses two directions in it, with vv along a direction on which GG is not constant. Line L4 keeps the generator that, with RR, still defines the same curve. The code also tries the zero of the middle eigenvalue after the roots of ff, as a guard against rounding. The proof does not need it.

Example

Intersect the sphere S=x2+y2+z2−4S = x^2 + y^2 + z^2 - 4 with the cylinder T=(x−1)2+y2−1=x2+y2−2xT = (x - 1)^2 + y^2 - 1 = x^2 + y^2 - 2x. The curve is Viviani's curve, a figure eight on the sphere. The quadratic parts are Su=IS_u = I and Tu=diag(1,1,0)T_u = \mathrm{diag}(1, 1, 0), so

f(α,β)=det⁡diag(α+β,α+β,α)=α(α+β)2.f(\alpha, \beta) = \det \mathrm{diag}(\alpha + \beta, \alpha + \beta, \alpha) = \alpha (\alpha + \beta)^2.

The root (0,1)(0, 1) is the cylinder TT, whose quadratic part diag(1,1,0)\mathrm{diag}(1, 1, 0) is semidefinite of rank 2, so line L5 rejects it. The double root (1,−1)(1, -1) gives

R=S−T=z2+2x−4,R = S - T = z^2 + 2x - 4,

with quadratic part diag(0,0,1)\mathrm{diag}(0, 0, 1) of rank 1, a parabolic cylinder. Its rulings are p(u)=(2−u2/2, 0, u)p(u) = (2 - u^2/2, \, 0, \, u) and d=(0,1,0)d = (0, 1, 0): the line of uu is the line z=uz = u, x=2−u2/2x = 2 - u^2/2 in the direction of yy. Here ∣β∣≥∣α∣|\beta| \ge |\alpha|, so G=SG = S, and

S(p+vd)=v2+(2−u22)2+u2−4=v2−u2+u44,S(p + v d) = v^2 + \left(2 - \tfrac{u^2}{2}\right)^2 + u^2 - 4 = v^2 - u^2 + \tfrac{u^4}{4},

so a=1a = 1, b=0b = 0, c=u4/4−u2c = u^4/4 - u^2, and v=±u1−u2/4v = \pm u \sqrt{1 - u^2/4}, real for ∣u∣≤2|u| \le 2. The whole curve is

x=2−u22,y=±u1−u24,z=u,−2≤u≤2.x = 2 - \tfrac{u^2}{2}, \qquad y = \pm u \sqrt{1 - \tfrac{u^2}{4}}, \qquad z = u, \qquad -2 \le u \le 2.
uu cc points
00 00 (2,0,0)(2, 0, 0), a double root, the crossing point of the figure eight
±1\pm 1 −34-\tfrac34 (32,±32,±1)(\tfrac32, \pm\tfrac{\sqrt3}{2}, \pm 1)
±2\pm 2 00 (0,0,±2)(0, 0, \pm 2), a double root, the poles
∣u∣>2\lvert u \rvert > 2 >0> 0 none

Each point satisfies both equations: at (32,32,1)(\tfrac32, \tfrac{\sqrt3}{2}, 1), 94+34+1=4\tfrac94 + \tfrac34 + 1 = 4 and 14+34=1\tfrac14 + \tfrac34 = 1. The code finds the same member, scaled, and the same points; at the crossing point the two roots differ by about 10−610^{-6}, the square root of the rounding error of cc.

Correctness

The full proof has three parts. First, a member as needed by line L5 always exists, which is Levin's theorem. Let λ2(θ)\lambda_2(\theta) be the middle eigenvalue of cos⁡θ Su+sin⁡θ Tu\cos\theta \, S_u + \sin\theta \, T_u. It is continuous in θ\theta, by Weyl's inequality, and the member at θ+π\theta + \pi is minus the member at θ\theta, so λ2(π)=−λ2(0)\lambda_2(\pi) = -\lambda_2(0) and λ2\lambda_2 has a zero θ∗\theta^*. There the eigenvalues are λ1≤0≤λ3\lambda_1 \le 0 \le \lambda_3 with the middle one zero, so the quadratic part is singular and either indefinite or of rank at most 1. The point θ∗\theta^* is a root of ff, so line L3 meets it, and if f≡0f \equiv 0 line L2 computes θ∗\theta^* directly.

Second, a member of this kind is one of the simple ruled quadrics or empty, by the spectral theorem and completing squares, and its sheets cover its zero set, with every point on the line of a parameter uu that is an affine function of the point. Third, a common zero of SS and TT is a common zero of GG and RR and conversely, because line L4 picks the generator whose partner has a coefficient at least 1/21/\sqrt2 in RR. And G(p+vd)G(p + v d) is exactly the quadratic of line L7. So for each sample uu, the output is exactly the intersection on the line of uu. An empty member means an empty intersection.

What is not proved is the effect of rounding on the roots of ff and on the rank decisions. The tests check, for the example, for disjoint spheres, for parallel cylinders where f≡0f \equiv 0, for one input of each member type, and for 6060 random pairs of quadrics through a common point, that every output point satisfies both quadrics to a relative residual of 10−910^{-9}. They also check that more than 100100 points of the intersection, found independently by Newton steps, each lie on a sheet with a root of the quadratic at their vv, and that for 300300 random pencils some real root of ff gives a simple ruled member.

Proof: Every pencil of two quadrics holds a member that is a plane, two planes, a hyperbolic or parabolic cylinder, a hyperbolic paraboloid or empty, and its rulings reduce the intersection to quadratic equationsfull

A quadric is a nonzero real symmetric 4×44 \times 4 matrix QQ, with Q(x)=XTQXQ(x) = X^T Q X for X=(x,1)X = (x, 1), x∈R3x \in \mathbb{R}^3. Write QuQ_u for its upper left 3×33 \times 3 block, the quadratic part, q=(Q14,Q24,Q34)q = (Q_{14}, Q_{24}, Q_{34}) for its linear part and q0=Q44q_0 = Q_{44}, so that Q(x)=xTQux+2q⋅x+q0Q(x) = x^T Q_u x + 2 q \cdot x + q_0. The input is two quadrics SS and TT that are not proportional, and the pencil is the set of members R=αS+βTR = \alpha S + \beta T with (α,β)≠(0,0)(\alpha, \beta) \ne (0, 0). Every member is a nonzero matrix. Call a symmetric 3×33 \times 3 matrix semidefinite of rank 2 if it has exactly one eigenvalue 00 and the other two have the same sign.

Claim 1 (a member with a good quadratic part). Put M(θ)=cos⁡θ Su+sin⁡θ TuM(\theta) = \cos\theta \, S_u + \sin\theta \, T_u with eigenvalues λ1(θ)≤λ2(θ)≤λ3(θ)\lambda_1(\theta) \le \lambda_2(\theta) \le \lambda_3(\theta). There is a θ∗∈[0,π]\theta^* \in [0, \pi] with λ2(θ∗)=0\lambda_2(\theta^*) = 0. The quadratic part M(θ∗)M(\theta^*) of the member R∗=cos⁡θ∗S+sin⁡θ∗TR^* = \cos\theta^* S + \sin\theta^* T is singular and is not semidefinite of rank 2.

Proof. By Weyl's inequality, ∣λk(A)−λk(B)∣≤∥A−B∥2|\lambda_k(A) - \lambda_k(B)| \le \|A - B\|_2 for symmetric AA and BB, so each λk(θ)\lambda_k(\theta) is a continuous function of θ\theta. Since M(θ+π)=−M(θ)M(\theta + \pi) = -M(\theta), the eigenvalues at θ+π\theta + \pi are −λ3(θ)≤−λ2(θ)≤−λ1(θ)-\lambda_3(\theta) \le -\lambda_2(\theta) \le -\lambda_1(\theta), so λ2(π)=−λ2(0)\lambda_2(\pi) = -\lambda_2(0). Either λ2(0)=0\lambda_2(0) = 0, or λ2\lambda_2 changes sign on [0,π][0, \pi] and vanishes at some θ∗\theta^* by the intermediate value theorem. At θ∗\theta^* the eigenvalues are λ1≤0=λ2≤λ3\lambda_1 \le 0 = \lambda_2 \le \lambda_3, so M(θ∗)M(\theta^*) is singular. If λ1=0\lambda_1 = 0 or λ3=0\lambda_3 = 0, it has rank at most 11. Otherwise λ1<0<λ3\lambda_1 < 0 < \lambda_3 and it is indefinite. In neither case is it semidefinite of rank 2. □\square

Consequence for lines L1 to L3. Let f(α,β)=det⁡(αSu+βTu)f(\alpha, \beta) = \det(\alpha S_u + \beta T_u), a binary form of degree 33. If ff is not the zero form, the point (cos⁡θ∗,sin⁡θ∗)(\cos\theta^*, \sin\theta^*) is one of its real projective roots, since M(θ∗)M(\theta^*) is singular. Line L2 lists all real projective roots: it finds the roots of f(1,λ)f(1, \lambda) for ∣λ∣≤1|\lambda| \le 1 and of f(μ,1)f(\mu, 1) for ∣μ∣≤1|\mu| \le 1, which together cover every direction (α,β)(\alpha, \beta). So the loop of line L3 meets a member that passes the test of line L5. If ff is the zero form, line L2 finds θ∗\theta^* itself, by bisection on the sign of λ2\lambda_2, which keeps an interval at whose ends λ2\lambda_2 has opposite signs, and so converges to a zero of the continuous function λ2\lambda_2.

Claim 2 (the zero set and its sheets). Let RR be a member whose quadratic part A=RuA = R_u is singular and not semidefinite of rank 2, with linear part rr and constant cc. Then the zero set Z(R)={x:R(x)=0}Z(R) = \{x : R(x) = 0\} is a hyperbolic paraboloid, a hyperbolic cylinder, two intersecting planes, a parabolic cylinder, two parallel planes, one plane, or empty. Each nonempty case is the union of the sheets of line L5, each sheet is a map (u,v)↦p(u)+v d(u)(u, v) \mapsto p(u) + v \, d(u) with d(u)≠0d(u) \ne 0, every point of the sheet satisfies R=0R = 0, and every point xx of Z(R)Z(R) lies on a sheet at the parameter uu that the sheet assigns to xx.

Proof. By the spectral theorem, A=∑iμieieiTA = \sum_i \mu_i e_i e_i^T with an orthonormal basis e1,e2,e3e_1, e_2, e_3. Write ρi=r⋅ei\rho_i = r \cdot e_i.

Rank 2. Let μa>0>μb\mu_a > 0 > \mu_b be the nonzero eigenvalues, which have opposite signs by the hypothesis, and e3e_3 the null vector. Put sa=μas_a = \sqrt{\mu_a}, sb=−μbs_b = \sqrt{-\mu_b}, the center m=−(ρa/μa)ea−(ρb/μb)ebm = -(\rho_a / \mu_a) e_a - (\rho_b / \mu_b) e_b, and c′=c−ρa2/μa−ρb2/μbc' = c - \rho_a^2 / \mu_a - \rho_b^2 / \mu_b. The map x=m+(P/sa)ea+(Q/sb)eb+we3x = m + (P / s_a) e_a + (Q / s_b) e_b + w e_3 is an affine bijection between xx and (P,Q,w)(P, Q, w), and completing the squares gives

R(x)=P2−Q2+2ρ3w+c′.R(x) = P^2 - Q^2 + 2 \rho_3 w + c'.

If ρ3≠0\rho_3 \ne 0, put u=P−Qu = P - Q and v=P+Qv = P + Q. Then P2−Q2=uvP^2 - Q^2 = u v, and R=0R = 0 exactly when w=−(uv+c′)/(2ρ3)w = -(u v + c') / (2 \rho_3). So Z(R)Z(R) is a hyperbolic paraboloid, and it is the image of p(u)+v d(u)p(u) + v \, d(u) with p(u)p(u) the point with (P,Q,w)=(u/2,−u/2,−c′/(2ρ3))(P, Q, w) = (u/2, -u/2, -c' / (2\rho_3)) and d(u)=12saea+12sbeb−u2ρ3e3d(u) = \tfrac{1}{2 s_a} e_a + \tfrac{1}{2 s_b} e_b - \tfrac{u}{2 \rho_3} e_3: moving vv along d(u)d(u) adds v/2v/2 to PP and to QQ, and −uv/(2ρ3)-u v / (2 \rho_3) to ww. A point xx of Z(R)Z(R) lies on the line of u=P−Qu = P - Q, which is affine in xx, at v=P+Qv = P + Q.

If ρ3=0\rho_3 = 0 and c′≠0c' \ne 0, then RR does not depend on ww, and R=0R = 0 means (P−Q)(P+Q)=k(P - Q)(P + Q) = k with k=−c′≠0k = -c' \ne 0. So t=P−Q≠0t = P - Q \ne 0 and P+Q=k/tP + Q = k / t, that is P=(t+k/t)/2P = (t + k/t) / 2 and Q=(k/t−t)/2Q = (k/t - t) / 2, and ww is free. Z(R)Z(R) is a hyperbolic cylinder, the image of p(t)+ve3p(t) + v e_3 for t≠0t \ne 0, and a point xx lies on the line of t=P−Qt = P - Q.

If ρ3=0\rho_3 = 0 and c′=0c' = 0, then R=(P−Q)(P+Q)R = (P - Q)(P + Q), and Z(R)Z(R) is the two planes P=QP = Q and P=−QP = -Q through mm, with normals saea−sbebs_a e_a - s_b e_b and saea+sbebs_a e_a + s_b e_b.

Rank 1. Let μ1≠0\mu_1 \ne 0 with unit vector e1e_1, put m=−(ρ1/μ1)e1m = -(\rho_1 / \mu_1) e_1, c′=c−ρ12/μ1c' = c - \rho_1^2 / \mu_1, rn=r−ρ1e1r_n = r - \rho_1 e_1, which is orthogonal to e1e_1, and s=(x−m)⋅e1s = (x - m) \cdot e_1. Then R(x)=μ1s2+2rn⋅x+c′R(x) = \mu_1 s^2 + 2 r_n \cdot x + c', and rn⋅m=0r_n \cdot m = 0. If rn≠0r_n \ne 0, put n=∣rn∣n = |r_n|, g=rn/ng = r_n / n and h=e1×gh = e_1 \times g, so that e1,g,he_1, g, h is orthonormal and x=m+se1+zg+yhx = m + s e_1 + z g + y h with rn⋅x=nzr_n \cdot x = n z. Then R=0R = 0 exactly when z=−(μ1s2+c′)/(2n)z = -(\mu_1 s^2 + c') / (2n), so Z(R)Z(R) is a parabolic cylinder, the image of p(u)+vhp(u) + v h with p(u)=m+ue1−μ1u2+c′2ngp(u) = m + u e_1 - \tfrac{\mu_1 u^2 + c'}{2n} g, and a point xx lies on the line of u=(x−m)⋅e1u = (x - m) \cdot e_1. If rn=0r_n = 0, then R=μ1s2+c′R = \mu_1 s^2 + c', and Z(R)Z(R) is the two planes s=±−c′/μ1s = \pm\sqrt{-c'/\mu_1} when −c′/μ1>0-c'/\mu_1 > 0, the one plane s=0s = 0 when c′=0c' = 0, and empty otherwise.

Rank 0. Then R(x)=2r⋅x+cR(x) = 2 r \cdot x + c. If r≠0r \ne 0, Z(R)Z(R) is the plane through −cr/(2∣r∣2)-c r / (2 |r|^2) with normal rr. If r=0r = 0, then c≠0c \ne 0 because R≠0R \ne 0, and Z(R)Z(R) is empty.

A plane through x0x_0 with unit normal ν\nu is one sheet: line L5 picks a unit vector dd in the plane and puts e=ν×de = \nu \times d, so e,de, d is an orthonormal basis of the plane, p(u)=x0+uep(u) = x_0 + u e, and a point xx of the plane lies on the line of u=(x−x0)⋅eu = (x - x_0) \cdot e at v=(x−x0)⋅dv = (x - x_0) \cdot d. □\square

The member found in Claim 1 is nonzero, so Claim 2 applies to it. This is the theorem of Levin, in the form given by Dupont, Lazard, Lazard and Petitjean (Theorem 3.1): the pencil of two distinct quadrics contains a simple ruled quadric or the empty set. If Z(R)Z(R) is empty, then SS and TT have no common real point, since every common zero of SS and TT is a zero of every member; so line L5 returns no sheets and the output is correctly empty.

Claim 3 (the quadratic on a ruling). Let line L4 choose G=SG = S if ∣β∣≥∣α∣|\beta| \ge |\alpha| and G=TG = T otherwise. Then Z(S)∩Z(T)=Z(G)∩Z(R)Z(S) \cap Z(T) = Z(G) \cap Z(R), and for every line p+vdp + v d, G(p+vd)=av2+bv+cG(p + v d) = a v^2 + b v + c with a=dTGuda = d^T G_u d, b=2d⋅(Gup+g)b = 2 d \cdot (G_u p + g) and c=G(p)c = G(p), where gg is the linear part of GG.

Proof. If ∣β∣≥∣α∣|\beta| \ge |\alpha|, then β≠0\beta \ne 0 and T=(R−αS)/βT = (R - \alpha S) / \beta, so S(x)=T(x)=0S(x) = T(x) = 0 exactly when S(x)=R(x)=0S(x) = R(x) = 0. The other case is the same with the roles of SS and TT exchanged. The formula follows from expanding (p+vd)TGu(p+vd)+2g⋅(p+vd)+g0(p + v d)^T G_u (p + v d) + 2 g \cdot (p + v d) + g_0 and using the symmetry of GuG_u. □\square

Conclusion. By Claims 2 and 3, for a sample uu of a sheet, the points of Z(S)∩Z(T)Z(S) \cap Z(T) on the line p(u)+v d(u)p(u) + v \, d(u) are exactly the points at the real roots vv of av2+bv+ca v^2 + b v + c, or the whole line when a=b=c=0a = b = c = 0. Lines L7 and L8 return these. Every point xx of Z(S)∩Z(T)Z(S) \cap Z(T) is on some sheet at the parameter uu that the sheet assigns to it, so it is returned whenever that uu is a sample. With exact arithmetic the output is therefore exactly the intersection restricted to the sampled lines.

What is not proved is the effect of rounding: the roots of ff are found in floating point, the rank and signs of the eigenvalues are decided with a relative tolerance of 10−910^{-9}, and a double root vv is found only to about the square root of the rounding error. The tests measure the residuals of the output points in both quadrics, and check, for points of the intersection found independently by Newton steps, that each lies on a sheet and that its value of vv is a root of the quadratic of its line. ■\blacksquare

Complexity

All matrices have fixed size. Line L1 takes four 3×33 \times 3 determinants, line L2 finds at most three roots of a cubic by bisection, or runs a bisection on θ\theta with one 3×33 \times 3 eigenvalue problem per step, and line L5 one Jacobi eigenvalue computation per candidate. This is O(1)O(1) work for a fixed precision. Each sample uu costs O(1)O(1) for the quadratic, so the total is O(N)O(N) time for NN samples, and O(N)O(N) space for the output.

The output is more than a set of points: the curve is p(u)+v±(u) d(u)p(u) + v_\pm(u) \, d(u) with v±(u)=(−b±b2−4ac)/(2a)v_\pm(u) = (-b \pm \sqrt{b^2 - 4ac}) / (2a), a closed form in uu that can be evaluated anywhere. The points where b2−4ac=0b^2 - 4ac = 0 split the uu axis into intervals on which the curve has a fixed number of branches.

Properties

  • Closed form. The curve is given by a formula with one square root of a function of uu of low degree, polynomial for a paraboloid or a parabolic cylinder, and no iteration on the curve itself.
  • Complete for each line. Every intersection point on a sampled line is found, and an empty member proves that the intersection is empty.
  • Not rational. The square root makes the parametrization irrational even when a rational one exists, for example when the curve is singular or splits into conics and lines.
  • Algebraic numbers. The member comes from a root of a cubic and the sheets from square roots of eigenvalues. In exact arithmetic the numbers grow fast, and in floating point the classification of the member can be wrong near a type boundary.

Variants and improvements

  • Elliptic cylinders. An elliptic cylinder is also ruled, by lines parallel to its axis, and a parametrization of the ellipse gives a sheet linear in vv. The method of this page does not use it, because the theorem does not need it.
  • Enhanced versions. Wang, Goldman and Tu (2003) added a classification of the curve in the singular and reducible cases, where it can be given by rational functions.
  • Near optimal parametrizations. Dupont, Lazard, Lazard and Petitjean work in projective space with exact arithmetic and find a member with the smallest possible number of square roots in its coefficients. In the generic case their parametrization has at most one square root more than needed.
  • Geometric special cases. Many modelers intersect natural quadrics, such as planes, spheres, cylinders and cones, by special geometric formulas, which are faster and more stable for those cases.
  • General surfaces. For surfaces of higher degree no member with a linear parametrization need exist. Then algebraic surface intersection or implicitization followed by substitution are the analytic alternatives.

When to use it

Use it for the intersection of two quadric faces in a solid modeler, where the inputs are often planes, spheres, cylinders and cones, and a closed form curve with all its branches is wanted. It also gives the number of branches over each interval of uu, from the sign of b2−4acb^2 - 4ac. For two natural quadrics in special position, prefer the geometric formulas, and for exact results with rational input, prefer the projective method of Dupont and others.

Pitfalls

  • Wrong type near a boundary. In floating point a member with a nearly zero eigenvalue can be classified as the wrong type, for example a nearly parabolic cylinder as a hyperbolic one, and then the sheets are wrong. Use a tolerance relative to the size of the matrix, and prefer members whose eigenvalues are well separated from zero.
  • Double roots. At a tangency or a crossing point of the curve, b2−4acb^2 - 4ac is zero and rounding makes it slightly negative or positive. Clamp small negative values to zero, and expect the two branches to separate by about the square root of the rounding error.
  • The wrong partner. If RR is almost a multiple of SS and the code uses SS as the partner, the two equations are almost the same, and the points are poorly fixed. Line L4 avoids this by taking the generator with the smaller coefficient in RR.
  • Lines of the curve. When the curve contains a line of a sheet, a=b=c=0a = b = c = 0 for one value of uu only, and sampling misses it. A curve that contains a line is reducible, and the exact methods detect such cases from the multiple roots of det⁡(αS+βT)\det(\alpha S + \beta T).
  • The sampling in u. Near the ends of a branch, where b2−4acb^2 - 4ac goes to zero, the points crowd in uu but spread in space, like u−u0\sqrt{u - u_0}. Refine the samples there, or use the ends as extra samples.

Implementations

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

levin_quadric_intersection.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/levin-quadric-intersection/. The authors are listed in prov/NA927X.jsonl.

"""Levin's pencil method for the intersection of two quadrics.

A quadric is a symmetric 4 x 4 matrix Q, with the surface X^T Q X = 0 for
X = (x, y, z, 1). Its upper left 3 x 3 block Q_u is the quadratic part, the
vector g = (Q[0][3], Q[1][3], Q[2][3]) the linear part, so that
Q(x) = x^T Q_u x + 2 g . x + Q[3][3].

The method finds a member R = alpha S + beta T of the pencil whose quadratic
part is singular and not semidefinite of rank 2. Its zero set is a plane, two
planes, a hyperbolic or parabolic cylinder, a hyperbolic paraboloid, or empty,
and it has sheets x = p(u) + v d(u), linear in v. On each line of a sheet the
partner quadric G (S or T) is a quadratic a v^2 + b v + c, whose real roots
give the points of the intersection.
"""

from math import cos, pi, sin, sqrt

from si1geom import add, cross, det, dot, jacobi_eigen, norm, real_roots, scale, solve, sub

TOL = 1e-9


def quadric_value(Q, x):
    X = (x[0], x[1], x[2], 1.0)
    return sum(Q[i][j] * X[i] * X[j] for i in range(4) for j in range(4))


def _upper(Q):
    return [[Q[i][j] for j in range(3)] for i in range(3)]


def _lin(Q):
    return (Q[0][3], Q[1][3], Q[2][3])


def _combo(a, S, b, T):
    return [[a * S[i][j] + b * T[i][j] for j in range(4)] for i in range(4)]


def _mat_vec(A, x):
    return tuple(A[i][0] * x[0] + A[i][1] * x[1] + A[i][2] * x[2] for i in range(3))


def _unit(x):
    return scale(1.0 / norm(x), x)


def _normalized(Q):
    m = max(abs(float(Q[i][j])) for i in range(4) for j in range(4))
    return [[float(Q[i][j]) / m for j in range(4)] for i in range(4)]


class Sheet:
    """One sheet x = point(u) + v * direction(u) of the ruled member, with
    param(x) the value of u of a point x on the sheet."""

    def __init__(self, kind, point, direction, param):
        self.kind = kind
        self.point = point
        self.direction = direction
        self.param = param


def pencil_cubic(S, T):
    """Coefficients c0, c1, c2, c3 of f(1, lam) = det(S_u + lam T_u)."""
    nodes = [-1.0, 0.0, 1.0, 2.0]
    vals = [det([[S[i][j] + t * T[i][j] for j in range(3)] for i in range(3)]) for t in nodes]
    return solve([[t ** k for k in range(4)] for t in nodes], vals)


def middle_eigenvalue_zero(S, T):
    """A point (cos th, sin th) where the middle eigenvalue of the quadratic
    part of the member changes sign. It exists because the member at th + pi
    is minus the member at th."""
    def mid(th):
        return jacobi_eigen(_upper(_combo(cos(th), S, sin(th), T)))[0][1]
    lo, hi = 0.0, pi
    flo = mid(lo)
    if flo == 0:
        return (1.0, 0.0)
    for _ in range(64):
        m = 0.5 * (lo + hi)
        fm = mid(m)
        if (fm > 0) == (flo > 0):
            lo, flo = m, fm
        else:
            hi = m
    th = 0.5 * (lo + hi)
    return (cos(th), sin(th))


def pencil_candidates(S, T, c):
    """The real projective roots of f(alpha, beta) = det(alpha S_u + beta T_u),
    with c the coefficients of f(1, lam), as unit vectors, or the middle
    eigenvalue zero when f vanishes."""
    if max(abs(x) for x in c) <= TOL:
        return [middle_eigenvalue_zero(S, T)]
    raw = [(1.0, t) for t in real_roots(c, -1.0, 1.0)]
    raw += [(t, 1.0) for t in real_roots(list(reversed(c)), -1.0, 1.0)]
    out = []
    for a, b in raw:
        n = sqrt(a * a + b * b)
        a, b = a / n, b / n
        if all(abs(a * b2 - b * a2) > 1e-7 for a2, b2 in out):
            out.append((a, b))
    return out


def _plane_sheet(x0, nrm, G):
    """The plane through x0 with normal nrm, with the ruling direction chosen
    so that G restricted to a ruling is not constant whenever possible."""
    nrm = _unit(nrm)
    e = _unit(cross(nrm, (1.0, 0.0, 0.0)) if abs(nrm[0]) < 0.9 else cross(nrm, (0.0, 1.0, 0.0)))
    f = cross(nrm, e)
    Gu = _upper(G)

    def q(d):
        return dot(d, _mat_vec(Gu, d))
    d = max([e, f, _unit(add(e, f))], key=lambda w: abs(q(w)))
    if abs(q(d)) <= TOL:
        grad = add(_mat_vec(Gu, x0), _lin(G))
        gp = sub(grad, scale(dot(grad, nrm), nrm))
        d = _unit(gp) if norm(gp) > TOL else e
    eu = cross(nrm, d)
    return Sheet("plane", lambda u: add(x0, scale(u, eu)), lambda u: d, lambda x: dot(sub(x, x0), eu))


def ruled_sheets(R, G):
    """Return (kind, sheets) for the member R, or None when its quadratic part
    is regular or semidefinite of rank 2. kind is 'empty' when R = 0 has no
    real point."""
    vals, vecs = jacobi_eigen(_upper(R))
    vecs = [tuple(v) for v in vecs]
    big = max(1.0, max(abs(v) for v in vals))
    zero = [abs(v) <= TOL * big for v in vals]
    rank = 3 - sum(zero)
    r, c = _lin(R), R[3][3]
    if rank == 3:
        return None
    if rank == 2:
        i0 = zero.index(True)
        ia, ib = [i for i in range(3) if i != i0]
        if vals[ia] * vals[ib] > 0:
            return None
        if vals[ia] < 0:
            ia, ib = ib, ia
        ma, mb = vals[ia], vals[ib]
        ea, eb, e3 = vecs[ia], vecs[ib], vecs[i0]
        ra, rb, r3 = dot(r, ea), dot(r, eb), dot(r, e3)
        center = add(scale(-ra / ma, ea), scale(-rb / mb, eb))
        cp = c - ra * ra / ma - rb * rb / mb
        sa, sb = sqrt(ma), sqrt(-mb)

        def at(p, q, w):
            return add(center, add(scale(p / sa, ea), add(scale(q / sb, eb), scale(w, e3))))

        def pmq(x):
            y = sub(x, center)
            return sa * dot(y, ea) - sb * dot(y, eb)
        if abs(r3) > TOL * big:
            # p^2 - q^2 + 2 r3 w + cp = 0 with u = p - q and v = p + q
            sheet = Sheet("hyperbolic paraboloid",
                          lambda u: at(u / 2, -u / 2, -cp / (2 * r3)),
                          lambda u: add(add(scale(0.5 / sa, ea), scale(0.5 / sb, eb)), scale(-u / (2 * r3), e3)),
                          pmq)
            return "hyperbolic paraboloid", [sheet]
        if abs(cp) > TOL * big:
            k = -cp  # p^2 - q^2 = k, with p - q = t and p + q = k / t
            sheet = Sheet("hyperbolic cylinder",
                          lambda t: at((t + k / t) / 2, (k / t - t) / 2, 0.0),
                          lambda t: e3,
                          pmq)
            return "hyperbolic cylinder", [sheet]
        n1 = sub(scale(sa, ea), scale(sb, eb))
        n2 = add(scale(sa, ea), scale(sb, eb))
        return "intersecting planes", [_plane_sheet(center, n1, G), _plane_sheet(center, n2, G)]
    if rank == 1:
        i1 = zero.index(False)
        m1, e1 = vals[i1], vecs[i1]
        r1 = dot(r, e1)
        c0 = scale(-r1 / m1, e1)
        cp = c - r1 * r1 / m1
        rn = sub(r, scale(r1, e1))
        n = norm(rn)
        if n > TOL * big:
            g = scale(1.0 / n, rn)
            h = cross(e1, g)
            sheet = Sheet("parabolic cylinder",
                          lambda u: add(c0, add(scale(u, e1), scale(-(m1 * u * u + cp) / (2 * n), g))),
                          lambda u: h,
                          lambda x: dot(sub(x, c0), e1))
            return "parabolic cylinder", [sheet]
        if abs(cp) <= TOL * big:
            return "double plane", [_plane_sheet(c0, e1, G)]
        s2 = -cp / m1
        if s2 < 0:
            return "empty", []
        s = sqrt(s2)
        return "parallel planes", [_plane_sheet(add(c0, scale(s, e1)), e1, G),
                                   _plane_sheet(add(c0, scale(-s, e1)), e1, G)]
    n = norm(r)
    if n <= TOL * big:
        return "empty", []
    return "plane", [_plane_sheet(scale(-c / (2 * n * n), r), r, G)]


def ruling_quadratic(G, p, d):
    """G(p + v d) = a v^2 + b v + c."""
    Gu = _upper(G)
    a = dot(d, _mat_vec(Gu, d))
    b = 2 * dot(d, add(_mat_vec(Gu, p), _lin(G)))
    return a, b, quadric_value(G, p)


def ruling_roots(G, p, d):
    """Real roots v of G(p + v d) = 0, or None when the whole line lies in G."""
    a, b, c = ruling_quadratic(G, p, d)
    m = max(abs(a), abs(b), abs(c))
    if m <= TOL:
        return None
    if abs(a) > 1e-12 * m:
        disc = b * b - 4 * a * c
        if disc < 0:
            if disc < -1e-12 * (b * b + abs(4 * a * c)):
                return []
            disc = 0.0
        q = -0.5 * (b + (sqrt(disc) if b >= 0 else -sqrt(disc)))
        if q == 0:
            return [0.0]
        return sorted({q / a, c / q})
    if abs(b) > 1e-12 * m:
        return [-c / b]
    return []


def levin_intersection(S, T, us):
    S, T = _normalized(S), _normalized(T)
    c = pencil_cubic(S, T)  # @line L1
    cands = pencil_candidates(S, T, c)  # @line L2
    cands.append(middle_eigenvalue_zero(S, T))  # a safeguard against rounding; the proof needs no more
    for alpha, beta in cands:  # @line L3
        R = _combo(alpha, S, beta, T)
        G = S if abs(beta) >= abs(alpha) else T  # @line L4
        found = ruled_sheets(R, G)  # @line L5
        if found is not None:
            break
    kind, sheets = found
    points, lines = [], []
    for sheet in sheets:  # @line L6
        for u in us:
            if sheet.kind == "hyperbolic cylinder" and u == 0:
                continue
            p, d = sheet.point(u), sheet.direction(u)
            roots = ruling_roots(G, p, d)  # @line L7
            if roots is None:
                lines.append((p, d))
                continue
            for v in roots:  # @line L8
                points.append(add(p, scale(v, d)))
    return {"member": R, "kind": kind, "partner": G, "sheets": sheets, "points": points, "lines": lines}  # @line L9
si1geom.py 298 lines
# SPDX-License-Identifier: MIT
# Shared helper of the si1 cad pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small geometric and algebraic tools for the si1 pages.

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

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

Vec = tuple
Num = float


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

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


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


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


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


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


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


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


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

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


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


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


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


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


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

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


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


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


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


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


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


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


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

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


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

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

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


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


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

import random
import unittest
from math import sqrt

from levin_quadric_intersection import (
    _normalized, _upper, levin_intersection, pencil_candidates, pencil_cubic,
    quadric_value, ruled_sheets, ruling_roots, _combo,
)
from si1geom import add, dot, jacobi_eigen, norm, scale, solve, sub

SPHERE2 = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, -4]]
US = [i / 20 for i in range(-60, 61)]


def residual(Q, p):
    return abs(quadric_value(_normalized(Q), p)) / (1 + dot(p, p))


def gradient(Q, x):
    return tuple(2 * (sum(Q[i][j] * x[j] for j in range(3)) + Q[i][3]) for i in range(3))


def point_on_both(S, T, x, steps=60):
    """A point of S = T = 0 near x, by minimum norm Newton steps, or None."""
    for _ in range(steps):
        F = (quadric_value(S, x), quadric_value(T, x))
        if max(abs(F[0]), abs(F[1])) < 1e-14:
            return x
        gs, gt = gradient(S, x), gradient(T, x)
        try:
            y = solve([[dot(gs, gs), dot(gs, gt)], [dot(gt, gs), dot(gt, gt)]], list(F))
        except ZeroDivisionError:
            return None
        x = sub(x, add(scale(y[0], gs), scale(y[1], gt)))
        if norm(x) > 50:
            return None
    return None


def covered(res, x):
    """True when x lies on a sheet of the member and the quadratic of its
    ruling has a root at x, or the whole ruling is in both quadrics."""
    G = res["partner"]
    for sh in res["sheets"]:
        u = sh.param(x)
        if sh.kind == "hyperbolic cylinder" and abs(u) < 1e-12:
            continue
        p, d = sh.point(u), sh.direction(u)
        v = dot(sub(x, p), d) / dot(d, d)
        if norm(sub(add(p, scale(v, d)), x)) > 1e-7 * (1 + norm(x)):
            continue
        roots = ruling_roots(G, p, d)
        if roots is None or any(abs(r - v) <= 1e-6 * (1 + abs(v)) for r in roots):
            return True
    return False


def random_pair(rng):
    """Two random quadrics through a common random point."""
    A = [[0.0] * 4 for _ in range(4)]
    B = [[0.0] * 4 for _ in range(4)]
    for i in range(4):
        for j in range(i, 4):
            A[i][j] = A[j][i] = rng.uniform(-1, 1)
            B[i][j] = B[j][i] = rng.uniform(-1, 1)
    x0 = (rng.uniform(-1, 1), rng.uniform(-1, 1), rng.uniform(-1, 1))
    A[3][3] -= quadric_value(A, x0)
    B[3][3] -= quadric_value(B, x0)
    return A, B, x0


class TestLevin(unittest.TestCase):
    def test_example_viviani(self):
        T = [[1, 0, 0, -1], [0, 1, 0, 0], [0, 0, 0, 0], [-1, 0, 0, 0]]
        res = levin_intersection(SPHERE2, T, [-2, -1, 0, 1, 2])
        self.assertEqual(res["kind"], "parabolic cylinder")
        # the member is a multiple of S - T = z^2 + 2x - 4
        R = res["member"]
        k = R[0][3]
        self.assertGreater(abs(k), 0.1)
        self.assertAlmostEqual(R[2][2] / k, 1.0)
        self.assertAlmostEqual(R[3][3] / k, -4.0)
        self.assertAlmostEqual(R[0][0] / k, 0.0)
        for p in res["points"]:
            self.assertLess(residual(SPHERE2, p), 1e-12)
            self.assertLess(residual(T, p), 1e-12)
        h = sqrt(3) / 2
        for want in ((1.5, h, 1.0), (1.5, -h, 1.0), (1.5, h, -1.0), (1.5, -h, -1.0), (2.0, 0.0, 0.0), (0.0, 0.0, 2.0)):
            self.assertLess(min(norm(sub(p, want)) for p in res["points"]), 1e-5)

    def test_disjoint_spheres(self):
        # radius 1 about (3, 0, 0), against radius 2 about the origin
        T = [[1, 0, 0, -3], [0, 1, 0, 0], [0, 0, 1, 0], [-3, 0, 0, 8]]
        res = levin_intersection(SPHERE2, T, US)
        self.assertEqual(res["kind"], "plane")
        self.assertEqual(res["points"], [])

    def test_parallel_cylinders_vanishing_cubic(self):
        S = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 0], [0, 0, 0, -1]]
        T = [[1, 0, 0, -1], [0, 1, 0, 0], [0, 0, 0, 0], [-1, 0, 0, 0]]
        self.assertLess(max(abs(c) for c in pencil_cubic(_normalized(S), _normalized(T))), 1e-12)
        res = levin_intersection(S, T, [-1, 0, 1])
        self.assertEqual(res["kind"], "plane")
        self.assertEqual(len(res["points"]), 6)
        for p in res["points"]:
            self.assertAlmostEqual(p[0], 0.5)
            self.assertAlmostEqual(abs(p[1]), sqrt(3) / 2)

    def test_each_kind_of_member(self):
        cases = {
            "hyperbolic cylinder": [[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, 0, 0], [0, 0, 0, -1]],
            "intersecting planes": [[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]],
            "parallel planes": [[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, -1]],
            "double plane": [[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]],
            "hyperbolic paraboloid": [[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, 0, -0.5], [0, 0, -0.5, 0]],
        }
        rng = random.Random(3)
        for kind, S in cases.items():
            res = levin_intersection(S, SPHERE2, US)
            self.assertEqual(res["kind"], kind)
            self.assertTrue(res["points"])
            for p in res["points"]:
                self.assertLess(residual(S, p), 1e-11)
                self.assertLess(residual(SPHERE2, p), 1e-11)
            for _ in range(20):
                x = (rng.uniform(-2, 2), rng.uniform(-2, 2), rng.uniform(-2, 2))
                y = point_on_both(_normalized(S), _normalized(SPHERE2), x)
                if y is not None:
                    self.assertTrue(covered(res, y), (kind, y))

    def test_pencil_has_a_simple_ruled_root(self):
        # the theorem: some real root of the cubic gives a member that is not
        # semidefinite of rank 2, without the safeguard
        rng = random.Random(11)
        for _ in range(300):
            A, B, _x0 = random_pair(rng)
            S, T = _normalized(A), _normalized(B)
            cands = pencil_candidates(S, T, pencil_cubic(S, T))
            self.assertTrue(cands)
            good = 0
            for a, b in cands:
                R = _combo(a, S, b, T)
                vals = jacobi_eigen(_upper(R))[0]
                self.assertLess(min(abs(v) for v in vals), 1e-8)
                good += ruled_sheets(R, S) is not None
            self.assertGreater(good, 0)

    def test_random_points_satisfy_both_and_all_are_found(self):
        rng = random.Random(7)
        found = 0
        for _ in range(60):
            A, B, x0 = random_pair(rng)
            res = levin_intersection(A, B, US)
            for p in res["points"]:
                self.assertLess(residual(A, p), 1e-9)
                self.assertLess(residual(B, p), 1e-9)
            self.assertTrue(covered(res, x0))
            S, T = _normalized(A), _normalized(B)
            for _ in range(4):
                x = add(x0, (rng.uniform(-1, 1), rng.uniform(-1, 1), rng.uniform(-1, 1)))
                y = point_on_both(S, T, x)
                if y is not None:
                    found += 1
                    self.assertTrue(covered(res, y))
        self.assertGreater(found, 100)


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

History

Levin (1976) gave the pencil method as part of an algorithm to draw pictures of solids bounded by quadric patches, and extended it in 1979 into a method for the intersection of any two quadrics, with an analysis of the pencil. His method was for a long time the only general one. Later work studied its weak points: the classification by Wilf and Manor with the Segre characteristic, the enhancement of Wang, Goldman and Tu (2003) for singular and reducible curves, and the exact projective algorithm of Dupont, Lazard, Lazard and Petitjean, which gives near optimal parametrizations and removes the numerical trouble of the floating point method.

References

  1. Joshua Levin, A parametric algorithm for drawing pictures of solid objects composed of quadric surfaces, Communications of the ACM 19(10), 555 to 563, 1976, the whole paper (the pencil of two quadrics, a member with a parametrization linear in one parameter, and the quadratic equation along each line of it)
  2. L. Dupont, D. Lazard, S. Lazard and S. Petitjean, Near-optimal parameterization of the intersection of quadrics, I, The generic algorithm, INRIA Research Report 5667, 2005, Section 3, Levin's pencil method (Theorem 3.1, the existence of a simple ruled quadric or the empty set in the pencil, the steps of the method, and the sources of numerical trouble)

About this page

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

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