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
- Model
- Real RAM
- Properties
- deterministicexactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Thomas W. Sederberg, David C. Anderson, Ronald N. Goldman, 1984
Implicitization turns a rational parametric curve , into one polynomial equation that holds exactly on the curve. The method of Sederberg, Anderson and Goldman takes as the resultant in of and , which vanishes exactly when the two have a common root, that is, when the point 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 in with rational coefficients, , of largest degree . They define the rational curve of points with . A rational Bézier curve of degree is of this form, after a change from the Bernstein basis to powers of . The output is a nonzero polynomial with integer coefficients and no common factor, of total degree at most , whose zero set in is the closure of . Here the closure adds at most one point, the limit of the curve as .
Two cases are outside the problem, and the method shows them. If , and 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 values of , the method returns the th power of the irreducible equation.
The algorithm
For a point put and . Both have degree at most , and the method reads both with the formal degree , even if their leading coefficients vanish. Their Sylvester matrix is the matrix whose first rows hold the coefficients of and whose last rows hold those of . Its determinant is the implicit polynomial.
IMPLICITIZE(X, Y, W)- 1
d ← max(deg X, deg Y, deg W) - 2
for each grid point (x_i, y_j) with x_i, y_j ∈ {0, 1, …, d} - 3
A ← X − x_i W and B ← Y − y_j W, both of formal degree d - 4
R[i][j] ← det S(A, B), in exact rational arithmetic - 5
interpolate R in y for each i, then in x for each power of y, to get F(x, y) - 6
return F scaled to coprime integer coefficients, leading coefficient positive
The entries of the first rows of are linear in , and those of the last rows linear in , so has degree at most in each variable, and its values on the 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 , and as coefficient lists from the constant term up, and returns as a map from exponent pairs to the coefficient of . A computer algebra system computes the same determinant with and as symbols. The grid form needs only exact numbers.
Example
Take the circle , , , so . Then and , and
Line L4 computes this determinant at the points of :
Line L5 recovers , and line L6 returns . The check by substitution is exact: at the curve point is , and .
Two points show the role of the formal degree. The point comes from , a common root of and . The point comes from no finite : there and have no common root, but both formal leading coefficients, and , are , so the first column of is zero. It is the limit of the curve as , and the resultant includes it, which closes the circle.
Other curves give the expected equations. The folium , , gives . The cuspidal cubic gives . The line gives .
Correctness
The full proof shows four facts. First, the Sylvester determinant of two polynomials of formal degree is zero exactly when they have a common root or both formal leading coefficients are zero, by the usual argument that exactly when for some of degree less than , not both zero. Second, without base points, exactly on the curve and at its point at infinity, because a common root with would be a base point. Third, has degree at most in and in , so lines L2 to L5 return it exactly, and its total degree is also at most : on any line , replacing the rows of by those of , which does not depend on , shows that has degree at most in . Fourth, is not the zero polynomial, because on a suitable vertical line it has at most zeros.
The finer fact that is a power of an irreducible polynomial, with 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 random curves of degree to they check by exact substitution with fractions that vanishes at random points of the curve, that its total degree is at most , and that it has at most 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 be polynomials in with coefficients in , not all of degree below , where , and with . The curve is . Write for the coefficients of . For a point put
both read as polynomials of formal degree , with leading coefficients and , and let be the determinant of their Sylvester matrix, the matrix of lines L3 and L4. Call a base point if , and call the point , defined when , the point of the curve at .
Lemma (the Sylvester criterion with formal degrees). For polynomials of formal degree , exactly when and have a common root in or both formal leading coefficients are .
Proof. The rows of are the coefficient vectors of and for , in the basis . So exactly when there are polynomials of degree less than , not both zero, with .
If both leading coefficients are , the first column of is zero and . If and have a common root , write and with ; then , give , and they are not both zero unless , in which case anyway.
Conversely, let with not both zero, and say the leading coefficient of is not , so . If then , so , which is excluded. So and divides . If and had no common root, would divide , which is impossible since . The case of a nonzero leading coefficient of is the same.
Claim 1 (the curve and only the curve). Assume there is no base point. Then exactly when or .
Proof. If , then , so by the lemma. If , both leading coefficients are , so . Conversely, let . By the lemma, either both leading coefficients are , so and , which forces (otherwise , against the choice of ) and then ; or and have a common root . In the second case, if , then and , a base point, which is excluded. So , and , .
The point is the limit of the curve as , so the zero set of is the image of the whole projective line, the closure of .
Claim 2 (degree in each variable). is a polynomial of degree at most in and at most in , and lines L2 to L5 return it exactly.
Proof. The first rows of have entries linear in and free of , and the last rows have entries linear in and free of . Expanding the determinant as a sum over permutations, each term is a product of entries of the first kind and of the second, so it has degree at most in and in .
Lines L3 and L4 compute exactly in rational arithmetic, at the points of the grid . Two polynomials of degree at most in each variable that agree on the grid are equal: their difference, for each fixed , is a polynomial in of degree at most with roots, so it is zero; hence each of its coefficients, a polynomial in of degree at most , vanishes at the values and is zero. Line L5 interpolates first in for each , then in for each power of , by solving Vandermonde systems with distinct nodes, which have unique solutions. So it returns . Line L6 only multiplies by a nonzero rational number.
Claim 3 (total degree). has total degree at most .
Proof. Fix a point and a direction with , and restrict to the line . There and . Put , which does not depend on . Replacing each row of the Sylvester matrix by adds a multiple of the row and multiplies the row by , so . Now is a sum of products of entries from the rows of , each of degree at most in , and entries from the rows of , free of , so it has degree at most in . Hence has degree at most .
If had total degree , let be its homogeneous part of degree . The coefficient of in is , so for all and all . A polynomial that vanishes on the dense set is zero, a contradiction.
Claim 4 (not identically zero). With no base point, is not the zero polynomial.
Proof. Since , there is at most one with . Choose any other , so . By Claim 1, the zeros of on the line are the points for the roots of with , at most of them, and possibly . So has at most zeros, and choosing outside them gives .
With a base point , every and has the root , so is the zero polynomial: dividing , and 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 whose complex zero set is exactly the closure of the curve. That is a power of an irreducible polynomial , where 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.
Complexity
Line L4 runs times, and each run is Bareiss elimination on a matrix, operations, so in all. Line L5 solves Vandermonde systems of size by Gaussian elimination, . The total is arithmetic operations, and extra space for the grid of values and one matrix. The operations are on rational numbers whose size grows with 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 determinants of matrices. For surfaces it is the size of the result that hurts. A tensor product patch of bidegree has an implicit equation of degree up to , which is for a bicubic patch, with up to 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 without base points has an implicit equation of degree at most , 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 . Points of the implicit curve outside the segment of a Bézier curve are still zeros of , 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 or more have no rational parametrization.
Variants and improvements
- Surfaces. A rational surface and so on gives three polynomials in two parameters, and the implicit equation is their resultant in and . Sederberg, Anderson and Goldman used the Dixon form of this resultant for tensor product patches. The degree is at most for a patch of bidegree , 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 , and 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 , and share a root, every and share it, and the method returns the zero polynomial. The curve , is an example; dividing by gives a curve of degree .
- Improper parametrization. The map covers the parabola twice, and the method returns . Take the square free part of the result, or reparametrize first.
- Formal degree. If and 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 for all points.
- Points not on the segment. A root of in an intersection may come from a parameter outside or from the point at infinity. Invert each point found and check its parameter.
- Floating point. The coefficients of can be large, and they cancel on the curve. Computing them in floats, or evaluating a high degree 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.
# 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
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag FF7D9Q Edit this page History Report an error Markdown