Algorithm Search⌘K

Algorithmadvanced

Implicitization of rational curves and surfaces

Also called implicitization by resultants, moving curves implicitization.

Converts a rational parametric curve or surface into an implicit polynomial equation by eliminating the parameter with a resultant, after Sederberg, Anderson and Goldman.

Time
O(d^5) worst
Space
O(d^2) extra
Where
d = the degree of the rational curve
Properties
deterministicexactiterative
Origin
Thomas W. Sederberg, David C. Anderson, Ronald N. Goldman, 1984

Implicitization turns a rational parametric curve x=X(t)/W(t)x = X(t) / W(t), y=Y(t)/W(t)y = Y(t) / W(t) into one polynomial equation F(x,y)=0F(x, y) = 0 that holds exactly on the curve. The method of Sederberg, Anderson and Goldman takes FF as the resultant in tt of X(t)−xW(t)X(t) - x W(t) and Y(t)−yW(t)Y(t) - y W(t), which vanishes exactly when the two have a common root, that is, when the point (x,y)(x, y) is on the curve. With the implicit form, the question "is this point on the curve, and on which side" becomes one evaluation, and the intersection of two curves becomes the roots of one polynomial in one unknown.

In plain words

A curve given by a formula with a moving parameter is easy to draw, because you can step the parameter and get points. But it is hard to test whether a given point is on the curve, because you must solve for the parameter. An implicit equation is the reverse: you put in a point and get a number that is zero exactly on the curve.

To get the equation, write the two coordinate formulas as two conditions on the parameter. A point is on the curve when one parameter value makes both conditions true. A classical tool, the resultant, is a determinant of the coefficients that is zero exactly when two polynomials share a root. So that determinant, read as a formula in the point, is the implicit equation. This page computes it exactly with fractions, at a grid of points, and rebuilds the formula from those values.

The problem

The input is three polynomials X,Y,WX, Y, W in tt with rational coefficients, W≠0W \ne 0, of largest degree d≥1d \ge 1. They define the rational curve CC of points (X(t)/W(t),Y(t)/W(t))(X(t) / W(t), Y(t) / W(t)) with W(t)≠0W(t) \ne 0. A rational Bézier curve of degree dd is of this form, after a change from the Bernstein basis to powers of tt. The output is a nonzero polynomial F(x,y)F(x, y) with integer coefficients and no common factor, of total degree at most dd, whose zero set in C2\mathbb{C}^2 is the closure of CC. Here the closure adds at most one point, the limit of the curve as t→∞t \to \infty.

Two cases are outside the problem, and the method shows them. If XX, YY and WW have a common root, a base point, the resultant is the zero polynomial; divide by their greatest common divisor first. If the parametrization is not proper, so that each point of the curve comes from k>1k > 1 values of tt, the method returns the kkth power of the irreducible equation.

The algorithm

For a point (x,y)(x, y) put A(t)=X(t)−xW(t)A(t) = X(t) - x W(t) and B(t)=Y(t)−yW(t)B(t) = Y(t) - y W(t). Both have degree at most dd, and the method reads both with the formal degree dd, even if their leading coefficients vanish. Their Sylvester matrix S(A,B)S(A, B) is the 2d×2d2d \times 2d matrix whose first dd rows hold the coefficients of td−1A,…,tA,At^{d - 1} A, \dots, t A, A and whose last dd rows hold those of td−1B,…,Bt^{d - 1} B, \dots, B. Its determinant R(x,y)=det⁡S(A,B)R(x, y) = \det S(A, B) is the implicit polynomial.

  1. IMPLICITIZE(X, Y, W)
  2. 1d ← max(deg X, deg Y, deg W)
  3. 2for each grid point (x_i, y_j) with x_i, y_j ∈ {0, 1, …, d}
  4. 3A ← X − x_i W and B ← Y − y_j W, both of formal degree d
  5. 4R[i][j] ← det S(A, B), in exact rational arithmetic
  6. 5interpolate R in y for each i, then in x for each power of y, to get F(x, y)
  7. 6return F scaled to coprime integer coefficients, leading coefficient positive

The entries of the first dd rows of S(A,B)S(A, B) are linear in xx, and those of the last dd rows linear in yy, so RR has degree at most dd in each variable, and its values on the (d+1)×(d+1)(d + 1) \times (d + 1) grid fix it. Line L4 uses fraction free Bareiss elimination, and line L5 solves Vandermonde systems in rational arithmetic, a form of polynomial interpolation. The code takes XX, YY and WW as coefficient lists from the constant term up, and returns FF as a map from exponent pairs (a,b)(a, b) to the coefficient of xaybx^a y^b. A computer algebra system computes the same determinant with xx and yy as symbols. The grid form needs only exact numbers.

Example

Take the circle X=1−t2X = 1 - t^2, Y=2tY = 2t, W=1+t2W = 1 + t^2, so d=2d = 2. Then A=−(1+x)t2+(1−x)A = -(1 + x) t^2 + (1 - x) and B=−yt2+2t−yB = -y t^2 + 2t - y, and

S(A,B)=(−1−x01−x00−1−x01−x−y2−y00−y2−y),det⁡S(A,B)=4(x2+y2−1).S(A, B) = \begin{pmatrix} -1 - x & 0 & 1 - x & 0 \\ 0 & -1 - x & 0 & 1 - x \\ -y & 2 & -y & 0 \\ 0 & -y & 2 & -y \end{pmatrix}, \qquad \det S(A, B) = 4 (x^2 + y^2 - 1).

Line L4 computes this determinant at the 99 points of {0,1,2}2\{0, 1, 2\}^2:

R(xi,yj)R(x_i, y_j) y=0y = 0 y=1y = 1 y=2y = 2
x=0x = 0 −4-4 00 1212
x=1x = 1 00 44 1616
x=2x = 2 1212 1616 2828

Line L5 recovers 4x2+4y2−44x^2 + 4y^2 - 4, and line L6 returns x2+y2−1x^2 + y^2 - 1. The check by substitution is exact: at t=12t = \tfrac12 the curve point is (3/45/4,15/4)=(35,45)(\tfrac{3/4}{5/4}, \tfrac{1}{5/4}) = (\tfrac35, \tfrac45), and 925+1625−1=0\tfrac{9}{25} + \tfrac{16}{25} - 1 = 0.

Two points show the role of the formal degree. The point (1,0)(1, 0) comes from t=0t = 0, a common root of A=−2t2A = -2t^2 and B=2tB = 2t. The point (−1,0)(-1, 0) comes from no finite tt: there A=2A = 2 and B=2tB = 2t have no common root, but both formal leading coefficients, −1−x-1 - x and −y-y, are 00, so the first column of SS is zero. It is the limit of the curve as t→∞t \to \infty, and the resultant includes it, which closes the circle.

Other curves give the expected equations. The folium X=3tX = 3t, Y=3t2Y = 3t^2, W=1+t3W = 1 + t^3 gives x3+y3−3xyx^3 + y^3 - 3xy. The cuspidal cubic (t2,t3)(t^2, t^3) gives x3−y2x^3 - y^2. The line (t,2t+3)(t, 2t + 3) gives 2x−y+32x - y + 3.

Correctness

The full proof shows four facts. First, the Sylvester determinant of two polynomials of formal degree dd is zero exactly when they have a common root or both formal leading coefficients are zero, by the usual argument that det⁡S=0\det S = 0 exactly when PA+QB=0P A + Q B = 0 for some P,QP, Q of degree less than dd, not both zero. Second, without base points, R(x,y)=0R(x, y) = 0 exactly on the curve and at its point at infinity, because a common root t0t_0 with W(t0)=0W(t_0) = 0 would be a base point. Third, RR has degree at most dd in xx and in yy, so lines L2 to L5 return it exactly, and its total degree is also at most dd: on any line (x0+sp,y0+sq)(x_0 + s p, y_0 + s q), replacing the rows of BB by those of qA−pBq A - p B, which does not depend on ss, shows that RR has degree at most dd in ss. Fourth, RR is not the zero polynomial, because on a suitable vertical line it has at most d+1d + 1 zeros.

The finer fact that RR is a power GkG^k of an irreducible polynomial, with kk the number of parameter values per point, is cited from Sederberg, Anderson and Goldman and not proved here. The tests check the circle, the folium, the cusp, a line, the improper parametrization and a base point, and for 4040 random curves of degree 11 to 44 they check by exact substitution with fractions that FF vanishes at random points of the curve, that its total degree is at most dd, and that it has at most d+1d + 1 zeros on a vertical line.

Proof: The Sylvester resultant of X - xW and Y - yW vanishes exactly on the closure of a rational curve, has total degree at most d, and is recovered exactly by interpolationfull

Let X,Y,WX, Y, W be polynomials in tt with coefficients in Q\mathbb{Q}, not all of degree below dd, where d=max⁡(deg⁡X,deg⁡Y,deg⁡W)≥1d = \max(\deg X, \deg Y, \deg W) \ge 1, and with W≠0W \ne 0. The curve is C={(X(t)/W(t),Y(t)/W(t)):t∈C,W(t)≠0}C = \{(X(t) / W(t), Y(t) / W(t)) : t \in \mathbb{C}, W(t) \ne 0\}. Write Xd,Yd,WdX_d, Y_d, W_d for the coefficients of tdt^d. For a point (x,y)∈C2(x, y) \in \mathbb{C}^2 put

Ax(t)=X(t)−xW(t),By(t)=Y(t)−yW(t),A_x(t) = X(t) - x W(t), \qquad B_y(t) = Y(t) - y W(t),

both read as polynomials of formal degree dd, with leading coefficients Xd−xWdX_d - x W_d and Yd−yWdY_d - y W_d, and let R(x,y)=det⁡S(Ax,By)R(x, y) = \det S(A_x, B_y) be the determinant of their 2d×2d2d \times 2d Sylvester matrix, the matrix of lines L3 and L4. Call t0∈Ct_0 \in \mathbb{C} a base point if X(t0)=Y(t0)=W(t0)=0X(t_0) = Y(t_0) = W(t_0) = 0, and call the point p∞=(Xd/Wd,Yd/Wd)p_\infty = (X_d / W_d, Y_d / W_d), defined when Wd≠0W_d \ne 0, the point of the curve at t=∞t = \infty.

Lemma (the Sylvester criterion with formal degrees). For polynomials A,BA, B of formal degree dd, det⁡S(A,B)=0\det S(A, B) = 0 exactly when AA and BB have a common root in C\mathbb{C} or both formal leading coefficients are 00.

Proof. The rows of S(A,B)S(A, B) are the coefficient vectors of tiAt^i A and tiBt^i B for 0≤i<d0 \le i < d, in the basis t2d−1,…,1t^{2d - 1}, \dots, 1. So det⁡S=0\det S = 0 exactly when there are polynomials P,QP, Q of degree less than dd, not both zero, with PA+QB=0P A + Q B = 0.

If both leading coefficients are 00, the first column of SS is zero and det⁡S=0\det S = 0. If AA and BB have a common root t0t_0, write A=(t−t0)A1A = (t - t_0) A_1 and B=(t−t0)B1B = (t - t_0) B_1 with deg⁡A1,deg⁡B1<d\deg A_1, \deg B_1 < d; then P=B1P = B_1, Q=−A1Q = -A_1 give PA+QB=0P A + Q B = 0, and they are not both zero unless A=B=0A = B = 0, in which case S=0S = 0 anyway.

Conversely, let PA+QB=0P A + Q B = 0 with P,QP, Q not both zero, and say the leading coefficient of AA is not 00, so deg⁡A=d\deg A = d. If Q=0Q = 0 then PA=0P A = 0, so P=0P = 0, which is excluded. So Q≠0Q \ne 0 and AA divides QBQ B. If AA and BB had no common root, AA would divide QQ, which is impossible since 0≤deg⁡Q<d=deg⁡A0 \le \deg Q < d = \deg A. The case of a nonzero leading coefficient of BB is the same. □\square

Claim 1 (the curve and only the curve). Assume there is no base point. Then R(x,y)=0R(x, y) = 0 exactly when (x,y)∈C(x, y) \in C or (x,y)=p∞(x, y) = p_\infty.

Proof. If (x,y)=(X(t0)/W(t0),Y(t0)/W(t0))(x, y) = (X(t_0) / W(t_0), Y(t_0) / W(t_0)), then Ax(t0)=By(t0)=0A_x(t_0) = B_y(t_0) = 0, so R=0R = 0 by the lemma. If (x,y)=p∞(x, y) = p_\infty, both leading coefficients are 00, so R=0R = 0. Conversely, let R(x,y)=0R(x, y) = 0. By the lemma, either both leading coefficients are 00, so Xd=xWdX_d = x W_d and Yd=yWdY_d = y W_d, which forces Wd≠0W_d \ne 0 (otherwise Xd=Yd=Wd=0X_d = Y_d = W_d = 0, against the choice of dd) and then (x,y)=p∞(x, y) = p_\infty; or AxA_x and ByB_y have a common root t0t_0. In the second case, if W(t0)=0W(t_0) = 0, then X(t0)=Ax(t0)=0X(t_0) = A_x(t_0) = 0 and Y(t0)=0Y(t_0) = 0, a base point, which is excluded. So W(t0)≠0W(t_0) \ne 0, and x=X(t0)/W(t0)x = X(t_0) / W(t_0), y=Y(t0)/W(t0)y = Y(t_0) / W(t_0). □\square

The point p∞p_\infty is the limit of the curve as t→∞t \to \infty, so the zero set of RR is the image of the whole projective line, the closure of CC.

Claim 2 (degree in each variable). RR is a polynomial of degree at most dd in xx and at most dd in yy, and lines L2 to L5 return it exactly.

Proof. The first dd rows of S(Ax,By)S(A_x, B_y) have entries linear in xx and free of yy, and the last dd rows have entries linear in yy and free of xx. Expanding the determinant as a sum over permutations, each term is a product of dd entries of the first kind and dd of the second, so it has degree at most dd in xx and in yy.

Lines L3 and L4 compute R(xi,yj)R(x_i, y_j) exactly in rational arithmetic, at the (d+1)2(d + 1)^2 points of the grid {0,…,d}2\{0, \dots, d\}^2. Two polynomials of degree at most dd in each variable that agree on the grid are equal: their difference, for each fixed xix_i, is a polynomial in yy of degree at most dd with d+1d + 1 roots, so it is zero; hence each of its coefficients, a polynomial in xx of degree at most dd, vanishes at the d+1d + 1 values xix_i and is zero. Line L5 interpolates first in yy for each xix_i, then in xx for each power of yy, by solving Vandermonde systems with distinct nodes, which have unique solutions. So it returns RR. Line L6 only multiplies by a nonzero rational number. □\square

Claim 3 (total degree). RR has total degree at most dd.

Proof. Fix a point (x0,y0)(x_0, y_0) and a direction (p,q)(p, q) with p≠0p \ne 0, and restrict RR to the line (x0+sp,y0+sq)(x_0 + s p, y_0 + s q). There A=Ax0−spWA = A_{x_0} - s p W and B=By0−sqWB = B_{y_0} - s q W. Put E=qA−pB=qAx0−pBy0E = q A - p B = q A_{x_0} - p B_{y_0}, which does not depend on ss. Replacing each row tiBt^i B of the Sylvester matrix by tiE=q tiA−p tiBt^i E = q \, t^i A - p \, t^i B adds a multiple of the row tiAt^i A and multiplies the row by −p-p, so det⁡S(A,E)=(−p)ddet⁡S(A,B)\det S(A, E) = (-p)^d \det S(A, B). Now det⁡S(A,E)\det S(A, E) is a sum of products of dd entries from the rows of AA, each of degree at most 11 in ss, and dd entries from the rows of EE, free of ss, so it has degree at most dd in ss. Hence s↦R(x0+sp,y0+sq)s \mapsto R(x_0 + s p, y_0 + s q) has degree at most dd.

If RR had total degree D>dD > d, let RDR_D be its homogeneous part of degree DD. The coefficient of sDs^D in R(x0+sp,y0+sq)R(x_0 + s p, y_0 + s q) is RD(p,q)R_D(p, q), so RD(p,q)=0R_D(p, q) = 0 for all p≠0p \ne 0 and all qq. A polynomial that vanishes on the dense set {p≠0}\{p \ne 0\} is zero, a contradiction. □\square

Claim 4 (not identically zero). With no base point, RR is not the zero polynomial.

Proof. Since W≠0W \ne 0, there is at most one x0x_0 with X=x0WX = x_0 W. Choose any other x0x_0, so Ax0≠0A_{x_0} \ne 0. By Claim 1, the zeros of RR on the line x=x0x = x_0 are the points (x0,Y(t0)/W(t0))(x_0, Y(t_0) / W(t_0)) for the roots t0t_0 of Ax0A_{x_0} with W(t0)≠0W(t_0) \ne 0, at most dd of them, and possibly p∞p_\infty. So R(x0,⋅)R(x_0, \cdot) has at most d+1d + 1 zeros, and choosing y0y_0 outside them gives R(x0,y0)≠0R(x_0, y_0) \ne 0. □\square

With a base point t0t_0, every AxA_x and ByB_y has the root t0t_0, so RR is the zero polynomial: dividing XX, YY and WW by their greatest common divisor first is necessary.

So for a curve without base points, line L6 returns a nonzero polynomial of total degree at most dd whose complex zero set is exactly the closure of the curve. That RR is a power GkG^k of an irreducible polynomial GG, where kk is the number of parameter values that map to a general point of the curve, is the classical refinement of Claim 1; it is cited from Sederberg, Anderson and Goldman (1984), not proved here. ■\blacksquare

Complexity

Line L4 runs (d+1)2(d + 1)^2 times, and each run is Bareiss elimination on a 2d×2d2d \times 2d matrix, O(d3)O(d^3) operations, so O(d5)O(d^5) in all. Line L5 solves 2(d+1)2 (d + 1) Vandermonde systems of size d+1d + 1 by Gaussian elimination, O(d4)O(d^4). The total is O(d5)O(d^5) arithmetic operations, and O(d2)O(d^2) extra space for the grid of values and one matrix. The operations are on rational numbers whose size grows with dd and with the size of the input coefficients. Bareiss elimination keeps every intermediate value a minor of the matrix, so the sizes stay polynomial. Interpolation by a faster method, or a direct symbolic determinant, changes the constants but not the nature of the result.

For curves the cost is small: a cubic needs 1616 determinants of 6×66 \times 6 matrices. For surfaces it is the size of the result that hurts. A tensor product patch of bidegree (m,n)(m, n) has an implicit equation of degree up to 2mn2mn, which is 1818 for a bicubic patch, with up to (213)=1330\binom{21}{3} = 1330 coefficients.

Properties

  • Exact. With rational input, the result is exact. Rounding in floats would turn the zero set of a high degree polynomial into a different curve, so implicitization is done in exact arithmetic.
  • Degree preserving. A rational curve of degree dd without base points has an implicit equation of degree at most dd, the number of points in which a general line meets the curve.
  • Whole curve. The zero set is the closure of the whole image of the parameter line, not the image of [0,1][0, 1]. Points of the implicit curve outside the segment of a Bézier curve are still zeros of FF, and an inversion step decides whether a zero belongs to the segment.
  • Always possible. Every rational curve and surface has an implicit equation. The converse is false: most implicit curves of degree 33 or more have no rational parametrization.

Variants and improvements

  • Surfaces. A rational surface x=X(s,t)/W(s,t)x = X(s, t) / W(s, t) and so on gives three polynomials in two parameters, and the implicit equation is their resultant in ss and tt. Sederberg, Anderson and Goldman used the Dixon form of this resultant for tensor product patches. The degree is at most 2mn2mn for a patch of bidegree (m,n)(m, n), and base points of the surface lower it, but they also make the plain resultant vanish identically, which is the main practical difficulty.
  • Moving lines and moving surfaces. Sederberg and Chen (1995) build the implicit equation from polynomial families of lines, conics or planes that follow the curve or surface, and get it as the determinant of a matrix smaller than the Sylvester or Dixon matrix. The method handles some base points better.
  • Gröbner bases. Elimination of the parameters from the ideal of Wx−XW x - X, Wy−YW y - Y and 1−zW1 - z W with a lex Gröbner basis, by the elimination theorem, gives the implicit equation of curves and surfaces of any form, without the base point problem, but usually at much higher cost.
  • Approximate implicitization. For use in intersection, a low degree polynomial that is small on the curve or surface is often enough, and it is found by least squares on sample points.

When to use it

Use it when one of two curves or surfaces in an intersection problem is rational and of low degree: implicitize one, substitute the other, and solve one polynomial, as in curve and surface intersection and algebraic surface intersection. Use it also for exact inside and outside tests and for a symbolic description of the curve. Do not implicitize bicubic or higher patches in a time critical loop, because the degree and the number of coefficients of the result are large. Subdivision or marching methods on the parametric form are then cheaper.

Pitfalls

  • Base points. If XX, YY and WW share a root, every AA and BB share it, and the method returns the zero polynomial. The curve (t2+t)/(t2+3t)(t^2 + t) / (t^2 + 3t), (t2+2t)/(t2+3t)(t^2 + 2t) / (t^2 + 3t) is an example; dividing by tt gives a curve of degree 11.
  • Improper parametrization. The map t↦(t2,t4)t \mapsto (t^2, t^4) covers the parabola y=x2y = x^2 twice, and the method returns (y−x2)2=x4−2x2y+y2(y - x^2)^2 = x^4 - 2x^2 y + y^2. Take the square free part of the result, or reparametrize first.
  • Formal degree. If AA and BB are taken with their actual degree at each point, the size of the matrix changes from point to point and the values on the grid are not values of one polynomial. Keep the formal degree dd for all points.
  • Points not on the segment. A root of FF in an intersection may come from a parameter outside [0,1][0, 1] or from the point at infinity. Invert each point found and check its parameter.
  • Floating point. The coefficients of FF can be large, and they cancel on the curve. Computing them in floats, or evaluating a high degree FF near the curve in floats, gives a result whose sign is not reliable.

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.

implicitization.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/implicitization/. The authors are listed in prov/FF7D9Q.jsonl.

"""Implicitization of a rational plane curve by the Sylvester resultant.

The curve is x = X(t) / W(t), y = Y(t) / W(t), with X, Y, W polynomials given
as coefficient lists from the constant term up, with integer or Fraction
entries. The implicit polynomial is

    F(x, y) = Res_t(X(t) - x W(t), Y(t) - y W(t)),

the determinant of the 2d x 2d Sylvester matrix of the two polynomials, both
taken with the formal degree d = max(deg X, deg Y, deg W). Its entries are
linear in x or in y, so F has degree at most d in x and at most d in y. The
code evaluates the determinant exactly at the (d + 1)^2 points of a grid and
interpolates. F is returned as a dictionary (a, b) -> coefficient of x^a y^b,
scaled to integer coefficients with no common factor and a positive leading
coefficient.
"""

from fractions import Fraction
from math import gcd
from typing import Sequence

from si1geom import det, solve


def sylvester(A: Sequence, B: Sequence, d: int) -> list:
    """The 2d x 2d Sylvester matrix of A and B, both of formal degree d.

    Row i < d holds the coefficients of t^(d-1-i) A, row d + i those of
    t^(d-1-i) B, highest power first."""
    a = [A[k] if k < len(A) else 0 for k in range(d, -1, -1)]
    b = [B[k] if k < len(B) else 0 for k in range(d, -1, -1)]
    rows = []
    for c in (a, b):
        for i in range(d):
            rows.append([0] * i + c + [0] * (d - 1 - i))
    return rows


def _interpolate(nodes: list, values: list) -> list:
    """Coefficients (constant first) of the polynomial through (nodes[k], values[k])."""
    V = [[Fraction(x) ** j for j in range(len(nodes))] for x in nodes]
    return solve(V, [Fraction(v) for v in values])


def implicitize(X: Sequence, Y: Sequence, W: Sequence) -> dict:
    d = max(len(X), len(Y), len(W)) - 1  # @line L1
    nodes = list(range(d + 1))
    R = [[None] * (d + 1) for _ in range(d + 1)]
    for i, x0 in enumerate(nodes):  # @line L2
        for j, y0 in enumerate(nodes):
            A = [Fraction(X[k] if k < len(X) else 0) - x0 * Fraction(W[k] if k < len(W) else 0) for k in range(d + 1)]  # @line L3
            B = [Fraction(Y[k] if k < len(Y) else 0) - y0 * Fraction(W[k] if k < len(W) else 0) for k in range(d + 1)]
            R[i][j] = det(sylvester(A, B, d))  # @line L4
    rows = [_interpolate(nodes, R[i]) for i in range(d + 1)]  # @line L5
    F = {}
    for b in range(d + 1):
        col = _interpolate(nodes, [rows[i][b] for i in range(d + 1)])
        for a in range(d + 1):
            if col[a] != 0:
                F[(a, b)] = col[a]
    return normalize(F)  # @line L6


def normalize(F: dict) -> dict:
    """Scale F to coprime integer coefficients, with the coefficient of the
    largest monomial (by total degree, then by the power of x) positive."""
    if not F:
        return {}
    den = 1
    for c in F.values():
        den = den * Fraction(c).denominator // gcd(den, Fraction(c).denominator)
    ints = {k: int(Fraction(c) * den) for k, c in F.items()}
    g = 0
    for c in ints.values():
        g = gcd(g, c)
    lead = max(ints, key=lambda e: (e[0] + e[1], e[0]))
    s = 1 if ints[lead] > 0 else -1
    return {k: s * c // g for k, c in ints.items()}


def eval_implicit(F: dict, x, y):
    return sum(c * x ** a * y ** b for (a, b), c in F.items())
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_implicitization.py 66 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/implicitization/. The authors are listed in prov/FF7D9Q.jsonl.

import random
import unittest
from fractions import Fraction

from implicitization import eval_implicit, implicitize, sylvester
from si1geom import det, peval


def point(X, Y, W, t):
    w = peval(W, t)
    return Fraction(peval(X, t)) / w, Fraction(peval(Y, t)) / w


class TestImplicitization(unittest.TestCase):
    def test_example_circle(self):
        X, Y, W = [1, 0, -1], [0, 2], [1, 0, 1]
        self.assertEqual(implicitize(X, Y, W), {(2, 0): 1, (0, 2): 1, (0, 0): -1})
        # the raw determinant is 4 (x^2 + y^2 - 1)
        for x, y in ((0, 0), (2, 3), (Fraction(1, 3), Fraction(-5, 7))):
            A = [1 - x, 0, -1 - x]
            B = [-y, 2, -y]
            self.assertEqual(det(sylvester(A, B, 2)), 4 * (x * x + y * y - 1))
        self.assertEqual(point(X, Y, W, Fraction(1, 2)), (Fraction(3, 5), Fraction(4, 5)))

    def test_known_curves(self):
        self.assertEqual(implicitize([0, 3], [0, 0, 3], [1, 0, 0, 1]), {(3, 0): 1, (0, 3): 1, (1, 1): -3})
        self.assertEqual(implicitize([0, 0, 1], [0, 0, 0, 1], [1]), {(3, 0): 1, (0, 2): -1})
        self.assertEqual(implicitize([0, 1], [3, 2], [1]), {(1, 0): 2, (0, 1): -1, (0, 0): 3})

    def test_improper_parametrization_gives_a_power(self):
        # t -> (t^2, t^4) covers the parabola y = x^2 twice
        self.assertEqual(implicitize([0, 0, 1], [0, 0, 0, 0, 1], [1]), {(4, 0): 1, (2, 1): -2, (0, 2): 1})

    def test_base_point_gives_zero(self):
        # X, Y and W share the root t = 0
        self.assertEqual(implicitize([0, 1, 1], [0, 2, 1], [0, 3, 1]), {})

    def test_substitution_with_fractions(self):
        rng = random.Random(4)
        for _ in range(40):
            d = rng.randint(1, 4)
            X = [rng.randint(-5, 5) for _ in range(d + 1)]
            Y = [rng.randint(-5, 5) for _ in range(d + 1)]
            W = [rng.randint(-5, 5) for _ in range(d)] + [rng.choice([-3, -2, -1, 1, 2, 3])]
            F = implicitize(X, Y, W)
            self.assertTrue(F)
            self.assertLessEqual(max(a + b for a, b in F), d)
            for _ in range(8):
                t = Fraction(rng.randint(-40, 40), rng.randint(1, 13))
                if peval(W, t) == 0:
                    continue
                x, y = point(X, Y, W, t)
                self.assertEqual(eval_implicit(F, x, y), 0)
            # a point off the curve: on the line x = x0 the curve has at most d + 1 points
            x0 = Fraction(rng.randint(-50, 50), 7)
            hits = 0
            for k in range(d + 3):
                hits += eval_implicit(F, x0, Fraction(1000 + k, 3)) == 0
            self.assertLessEqual(hits, d + 1)


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

History

Elimination of variables by resultants is classical algebra, from Sylvester's matrix of 1840 and the work of the nineteenth and early twentieth centuries on the resultants of several polynomials. Sederberg, Anderson and Goldman (1984) brought these tools into geometric modeling: they showed that every rational curve and surface has an implicit equation found by a resultant, with the degrees above, and used it to reduce intersections to polynomials in one variable. Sederberg and Chen (1995) introduced moving lines and moving surfaces, which give the same equations from smaller determinants, and they applied the surface version to the bicubic patches of the Utah teapot. Gröbner basis methods and approximate implicitization are later alternatives.

References

  1. Thomas W. Sederberg, David C. Anderson and Ronald N. Goldman, Implicit representation of parametric curves and surfaces, Computer Vision, Graphics, and Image Processing 28(1), 72 to 84, 1984, the whole paper (the implicit equation of a rational curve as a resultant in the parameter, and of a rational surface as a resultant in two parameters)
  2. Thomas W. Sederberg and Falai Chen, Implicitization using moving curves and surfaces, Proceedings of SIGGRAPH 95, 301 to 308, 1995, the whole paper (implicit equations as determinants of smaller matrices built from moving lines, moving conics and moving planes)

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