Algorithmresearch
Globally optimal direction fields
Also called Knoppel direction fields, n-direction field design.
Knöppel, Crane, Pinkall and Schröder's smoothest n-direction fields on a surface, found as the eigenvector of the smallest eigenvalue of one sparse Hermitian matrix.
- Time
- O(n^3 + k n^2) denseO(n^(3/2) + k n log n) nested_dissection
- Space
- O(n^2) denseO(n log n) nested_dissection
- Where
- k = the number of inverse iteration steps; n = the number of vertices
- Model
- Real RAM
- Properties
- deterministicnot exactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Felix Knöppel, Keenan Crane, Ulrich Pinkall, Peter Schröder, 2013
A smooth field of directions on a surface, such as a cross field with , usually cannot exist without singular points, and searching over where to put them is a hard combinatorial problem. Knöppel, Crane, Pinkall and Schröder removed the combinatorial part. They store the field at each vertex as one complex number, the -th power of a direction, so that the smoothness energy becomes a Hermitian quadratic form, and they replace the unit length condition at each vertex by one condition on the whole field. The smoothest field is then the eigenvector of the smallest eigenvalue, the minimizer of a Rayleigh quotient, and inverse iteration finds it with one matrix factorization. The singularities appear where the field passes through zero, with no search.
In plain words
Picture a field of small crosses drawn on a curved surface, for example to guide where the lines of a grid go. Neighbouring crosses should line up as well as the curvature allows.
Each cross is stored as one turning number that does not care which of its four arms comes first. Then the mismatch between neighbours is a simple sum of squares.
Asking every cross to have full size at once makes the problem hard. So the method only asks that the crosses be large on average, and it may shrink some of them. The best answer to this easier question is the first natural mode of one big table of numbers, and a few rounds of repeated solving find it. The places where the crosses shrink to nothing are the unavoidable defects, and the method puts them there by itself.
The problem
The input is a connected, oriented manifold mesh of triangles with vertices, with faces oriented by the right-hand rule, and an integer . The output is an -direction field at the vertices that is as smooth as possible, with its singularities.
Frames and transport. At a vertex with corner angles around it, scale the angles by at an inner vertex and at a boundary vertex. Measure the direction of each edge at by the angle from one chosen edge at , adding the scaled corner angles counterclockwise. The scaled angles at an inner vertex add up to , so this is a full turn of directions in the tangent plane of . Moving from to along the edge, the direction of the edge turns from to , so a direction at angle at is carried to at . This is the discrete transport along the edge.
Representation. The directions at angles at a vertex are stored as one complex number , which does not depend on which of the directions is called . Transport along multiplies it by
Energy. With the cotangent weights of the cotangent Laplacian, the energy of a field is
where is Hermitian, with and , . It is zero exactly when every value is the transport of its neighbour, a parallel field.
Relaxation. The real problem asks for at every vertex, which is not convex. The relaxed problem asks only for , where is the diagonal matrix of vertex areas (one third of the areas of the triangles at the vertex):
The answer of the relaxed problem is normalized afterwards to unit length at the vertices where it is not zero, and its zeros are the singularities.
The algorithm
SmoothestField(M, n, ε, δ)- 1
for each vertex i: the frame angles φ_i(j) of its edges, with corner angles scaled by s_i - 2
for each edge ij: r_ij ← e^{in(φ_j(i) + π − φ_i(j))}, w_ij ← (cot α_ij + cot β_ij)/2 - 3
A ← Σ over edges of w_ij |u_j − r_ij u_i|^2 written as a Hermitian matrix - 4
M ← diag(vertex areas) - 5
factor A + σM = L L^*, with σ = ε · max A_ii / max M_ii ▷ Cholesky, once - 6
u ← a random complex vector - 7
repeat: solve L L^* y = M u - 8
u ← y / sqrt(y^* M y) - 9
λ ← u^* A u - 10
until |A u − λ M u| in the M^{-1} norm ≤ δ · max(1, λ) - 11
return u, λ
Lines L1 to L4 build the problem in time. Line L5 adds a tiny multiple of so that the matrix is positive definite even when , which happens when a parallel field exists. Lines L7 and L8 are one step of inverse iteration on the pencil : a solve with the fixed factor and a normalization. Line L10 stops when the pair is an eigenpair up to . The directions at a vertex are the -th roots of .
Singularities. The code of this page reads the index of the field in each face with vertices counterclockwise:
is the curvature of the scaled frames in , and is the turn from the transported value to the next value. is a multiple of , and on a closed mesh the indices add up to . The faces with are the singularities.
Example
The regular octahedron with . Each vertex has four angles of , so , and each face has . Transport once around a face multiplies by , so a parallel cross field exists, , and the code finds it in 2 steps. Every face has the index , and the 8 faces give . With or the transport around a face is not trivial, there is no parallel field, and the code returns in both cases.
The regular icosahedron. Five angles of meet at each vertex, so and , and the transport around a face is trivial only for a multiple of 10. The code returned:
| steps | singular faces | indices | ||
|---|---|---|---|---|
| 1 | 17 | 2 | ||
| 2 | 24 | 4 | four times | |
| 4 | 43 | 8 | eight times |
The indices add up to 2 in every row. A vector field gets two singularities of index 1, like the poles of a sphere, and a cross field gets eight of index , like the corners of a cube. The eigenvalues agree to with the smallest eigenvalue from a dense Jacobi eigenvalue computation, in the tests.
Measured on finer meshes. Icosahedra subdivided once (42 vertices, 80 faces) and twice (162 vertices, 320 faces), projected to the unit sphere, or to an ellipsoid with half axes , with seed 0, , , dense factorization in pure Python:
| mesh | steps | singular faces | quotient of the unit field | ||
|---|---|---|---|---|---|
| sphere, 42 | 1 | 0.99968 | 16 | 2 of index 1 | 1.98 |
| sphere, 42 | 4 | 3.41685 | 417 | 8 of index 1/4 | 4.39 |
| sphere, 162 | 1 | 1.00003 | 16 | 2 of index 1 | 2.41 |
| sphere, 162 | 2 | 1.97753 | 18 | 4 of index 1/2 | 4.03 |
| sphere, 162 | 4 | 3.84255 | 1679 | 8 of index 1/4 | 6.68 |
| ellipsoid, 42 | 1 | 1.40211 | 3925 | 2 of index 1 | 3.07 |
| ellipsoid, 162 | 2 | 2.28189 | 6847 | 4 of index 1/2 | 6.18 |
On the 162 vertex ellipsoid with the residual did not reach in 10000 steps. The large step counts come from the second smallest eigenvalue being very close to the first on these symmetric shapes. The last column is the Rayleigh quotient after each is set to unit length. It is always at least , and here it is 1.3 to 2.7 times . These numbers are measurements on these meshes, not bounds.
Correctness
The proof in proofs/correctness.md shows the following.
- with Hermitian, and is positive semidefinite when all weights are positive.
- Key invariant. The minimum of over is the smallest eigenvalue of , and it is reached exactly by the eigenvectors of . The proof writes and uses the spectral theorem for the Hermitian matrix . This is a generalized eigenvalue problem.
- If the random start has a nonzero part in the eigenspace of , which happens with probability 1, inverse iteration converges to that eigenspace. If is the next distinct eigenvalue, the rest shrinks by the factor per step.
- A returned pair has , , and an eigenvalue within of .
- The face indices are multiples of , and on a closed mesh they add up to .
So the code solves the relaxed problem exactly, up to the stopping test. It does not solve the problem with : the unit field made from the eigenvector is not proved to be the smoothest unit field, and in the measurements its Rayleigh quotient is 1.3 to 2.7 times .
Proof: The smoothest field of the relaxed problem is the eigenvector of the smallest eigenvalue, inverse iteration finds it, and the face indices add up to the Euler characteristicfull
Setting. is a connected, oriented triangle mesh with vertices , faces oriented by the right-hand rule, and an integer . The frame angles , the transports , the weights , the matrix and the diagonal matrix of vertex areas are as on the page, and the algorithm is lines L1 to L11 of the page. Every vertex is in a triangle of positive area, so every diagonal entry of is positive. for . Eigenvalues of are listed with repetition as .
Claim.
- with Hermitian. If all , then is positive semidefinite.
- , and exactly when is an eigenvector for . Every local minimizer of is such an eigenvector.
- If is positive semidefinite and , line L5 succeeds. If the start of line L6 has a nonzero component in the eigenspace of , the iterates of lines L7 and L8 converge to that eigenspace, and the residual of line L10 tends to 0.
- The algorithm terminates. A returned pair has , , and some eigenvalue with .
- Each face index is a multiple of . On a closed mesh, , when no is zero and no turn is exactly .
Proof of 1. For one edge, with and ,
because . Multiplied by , these are the four entries , , and of line L3. Summing over the edges gives . The diagonal is real, and , so is Hermitian. If all , is a sum of nonnegative terms, so for all .
Proof of 2. is diagonal with positive entries, so and exist. Put and . is Hermitian, and , so . Also exactly when , so has the eigenvalues . By the spectral theorem, has an orthonormal basis of eigenvectors with . Write . Then
with equality exactly when for every with , that is, when is in the eigenspace of . The value is reached at .
For the local minimizers: let be a local minimizer and . The quotient is smooth at , and its derivative in the direction is . At a local minimizer it vanishes for all , so : is an eigenvector, for some eigenvalue . If , take a unit eigenvector of ; it is orthogonal to because they belong to different eigenvalues of a Hermitian matrix. For , the quotient is for every , so is not a local minimizer. Hence .
Proof of 3. because some weight is positive in a mesh with a triangle, so . For , , so is Hermitian positive definite and has a Cholesky factor . In the coordinates of claim 2, line L7 computes , which is . So in these coordinates one step of lines L7 and L8 is followed by scaling to length 1. After steps,
Let be the indices with , and let be the smallest eigenvalue larger than (if there is none, is already an eigenvector of after the first step). The ratio of the part outside to the part in is at most
because for and the factors are positive. The denominator is nonzero by assumption, and the first factor is below 1 and tends to 0. So the distance from to the eigenspace of tends to 0. The Rayleigh quotient and the residual are continuous in , and they are and 0 on the unit vectors of that eigenspace, so they tend to and to 0.
Proof of 4. The loop of lines L7 to L10 runs at most a fixed number of times (the code allows max_steps, and fails after that), so the algorithm terminates. When it returns at line L11, line L8 has set , and line L9 has set by claim 2. The residual of line L10 is , with . In the basis of claim 2,
So some eigenvalue lies within of . Claim 4 does not say that this eigenvalue is ; that follows from claim 3 when the iteration has converged, and the tests compare with from a dense eigenvalue computation.
Proof of 5. Let have the corners in counterclockwise order, and let be the angle at . At the corner the face lies between the edges to and to (indices mod 3), in this counterclockwise order around , so line L1 gives . Then, summing the exponents of the three transports and grouping the terms by vertex,
Multiplying by , . Each turn satisfies , and the product of the three quotients telescopes:
So is a multiple of , and is a multiple of .
Now let the mesh be closed, with vertices, edges and faces. Every vertex is inner, so the scaled angles at each vertex add up to , and
because each face has three edges and each edge two faces, so and . For the turns, each edge is crossed once as in one face and once as in the other. From the definition, . So
and the two turns are and , since the argument in of is minus that of when . So all turns add up to 0, and .
Claims 1 to 5 together give the statement of the page: the eigenvector is the exact optimum of the relaxed problem, inverse iteration reaches it from almost every start, the returned pair is certified by its residual, and the singularities it shows obey the index sum .
Complexity
Lines L1 to L4 take time. With a dense factorization, as in the code, line L5 takes time and space once, and each step of lines L7 to L10 takes . For steps the total is . has one nonzero entry per vertex and two per edge, so a sparse Cholesky factorization with nested dissection on the planar mesh graph takes time and space, and each solve then takes . The factor is computed once, which is why one eigenvector is about as cheap as one linear solve when is small. The number depends on the gap between the two smallest eigenvalues and is not bounded in advance.
Properties
- Proved. The eigenvector of the smallest eigenvalue minimizes the energy among all fields with , the relaxed problem. This optimum is global: every local minimum of the quotient is an eigenvector of .
- Proved. The returned is at least , and the residual test certifies an eigenvalue within .
- Proved. The face indices are multiples of and add up to on a closed mesh.
- Not proved. The unit field made from the eigenvector is not proved to be the smoothest unit field. It is optimal for the relaxed problem only.
- Measured. On flat disks of 19 vertices (seeds 0 to 2) the code returns and on all edges, a parallel field.
- No integer unknowns. The singularities, their number and their positions all follow from the eigenvector, with no rounding step.
- No starting field. The output does not depend on a starting field or a choice of singularities. Only the random start of inverse iteration enters, and it changes only by a phase when is simple.
Variants and improvements
- Alignment to given directions. Knöppel et al. also fit the field to a given field , such as the principal curvature directions from curvature tensor estimation, by solving one linear system of the form with a parameter below .
- Smoothness measures. The paper describes a family of energies that weigh the holomorphic and antiholomorphic parts of the Dirichlet energy, from one alone to the other, which trades fewer singularities against straighter field lines.
- Face based fields. The same idea works with one value per face and transport across edges, with dual weights. The cross field page gives the index in that form.
- Other eigensolvers. The Lanczos algorithm or a shift closer to converges faster than plain inverse iteration when the two smallest eigenvalues are close. Power iteration on itself would find the largest eigenvalue instead, the roughest field.
- Quad meshing. The cross field with is the input of mixed-integer quadrangulation, which cuts the surface along a cut graph through the singularities.
When to use it
Use it to design cross fields for quad meshing, line fields for hatching, or vector fields on meshes, when the singularities should be placed automatically and the result should not depend on a starting guess. It needs one sparse factorization, so it scales to large meshes. If the user must control the singularities exactly, or a unit field is required everywhere with no shrinking, a mixed-integer method or a method with fixed singularities is more suitable.
Pitfalls
- Negative cotangent weights. On meshes with obtuse angles, can be negative. Then can take negative values and is not positive semidefinite, so the Cholesky factorization of line L5 can fail and the minimum loses its meaning. The code raises an error in that case. Use a mesh with the Delaunay property or intrinsic weights.
- Eigenvalues that are almost equal. On symmetric shapes the two smallest eigenvalues are almost equal, and inverse iteration then needs thousands of steps, as the ellipsoid rows show. The eigenvalue converges much faster than the eigenvector. A stopping test on the change of is the slowest. A test on the residual, as in line L10, stops earlier, but any field in the nearly repeated eigenspace is then a valid answer, and the singularities can move between runs with different seeds.
- No shift. If , as on the octahedron with or on a flat disk, is singular and its Cholesky factorization fails. Add with a small , as in line L5.
- Unscaled angles. Without the scaling , the frame at an inner vertex with angle sum other than does not close up, and the transport around the vertex is wrong. The scaled angles put the curvature of each vertex into the transport.
- Reading off the singularities. The singularities are where winds around zero, not where is small. Compute the index from the turns and the curvature; the size of only hints at where they are.
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/globally-optimal-direction-fields/. The authors are listed in prov/8TE408.jsonl.
"""Smoothest n-direction fields on a triangle mesh (after Knoppel, Crane, Pinkall and Schroder 2013).
An n-direction field is stored at each vertex i as one complex number u_i in a
tangent frame at i: the n directions are the n-th roots of u_i / |u_i|. The
frame at i measures angles from one edge at i, with the corner angles at i
scaled so that they add up to 2 pi at an inner vertex. Moving across the edge
ij multiplies by r_ij = exp(i n (phi_j(i) + pi - phi_i(j))), where phi_i(j)
is the angle of the edge ij in the frame of i. The energy
E(u) = sum over edges ij of w_ij |u_j - r_ij u_i|^2, w_ij = (cot a + cot b) / 2,
is a Hermitian form u* A u. The smoothest field with u* M u = 1, M the
diagonal matrix of vertex areas, is an eigenvector of A u = lambda M u for the
smallest lambda, computed here by inverse iteration with a complex Cholesky
factor of A + eps M.
"""
import cmath
import math
import random
from mx2geom import length
def corner_angles(vertices, faces):
"""For each face, its three corner angles, from the 3D vertex positions."""
out = []
for tri in faces:
p = [vertices[v] for v in tri]
ang = []
for k in range(3):
a, b, c = p[k], p[(k + 1) % 3], p[(k + 2) % 3]
u = [b[m] - a[m] for m in range(3)]
v = [c[m] - a[m] for m in range(3)]
dot = sum(x * y for x, y in zip(u, v))
cr = [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]]
ang.append(math.atan2(math.sqrt(sum(x * x for x in cr)), dot))
out.append(ang)
return out
def tangent_frames(vertices, faces):
"""phi[i][j]: the angle of edge ij in the frame of i; scale[i]: the factor on the corner angles at i."""
n = len(vertices)
ang = corner_angles(vertices, faces)
nxt = [dict() for _ in range(n)] # around i, counterclockwise: neighbour a -> (neighbour b, corner angle)
total = [0.0] * n
for f, tri in enumerate(faces):
for k in range(3):
i, a, b = tri[k], tri[(k + 1) % 3], tri[(k + 2) % 3]
nxt[i][a] = (b, ang[f][k])
total[i] += ang[f][k]
phi, scale = [], []
for i in range(n):
ends = set(b for b, _ in nxt[i].values())
starts = [a for a in nxt[i] if a not in ends]
inner = not starts
s = 2 * math.pi / total[i] if inner else 1.0 # @line L1
a = min(nxt[i]) if inner else starts[0]
p = {a: 0.0}
while a in nxt[i]:
b, al = nxt[i][a]
if b in p:
break
p[b] = p[a] + s * al
a = b
phi.append(p)
scale.append(s)
return phi, scale, ang
def transport(phi, i, j, n):
"""r_ij: the factor that carries an n-th power field value from the frame of i to the frame of j."""
return cmath.exp(1j * n * (phi[j][i] + math.pi - phi[i][j]))
def energy_matrices(vertices, faces, n):
"""The Hermitian matrix A of the energy, the vertex areas M, and the edges with weights and transports."""
nv = len(vertices)
phi, scale, ang = tangent_frames(vertices, faces)
weight = {}
for f, tri in enumerate(faces):
for k in range(3):
i, j = tri[(k + 1) % 3], tri[(k + 2) % 3]
e = (min(i, j), max(i, j))
weight[e] = weight.get(e, 0.0) + 0.5 / math.tan(ang[f][k])
a = [[0j] * nv for _ in range(nv)]
edges = []
for (i, j), w in sorted(weight.items()):
r = transport(phi, i, j, n) # @line L2
edges.append((i, j, w, r))
# w |u_j - r u_i|^2 = w |u_i|^2 + w |u_j|^2 - w conj(u_j) r u_i - w conj(u_i) conj(r) u_j
a[i][i] += w # @line L3
a[j][j] += w
a[j][i] -= w * r
a[i][j] -= w * r.conjugate()
m = [0.0] * nv
for tri in faces:
p0, p1, p2 = (vertices[v] for v in tri)
l0, l1, l2 = length(p1, p2), length(p2, p0), length(p0, p1)
s = (l0 + l1 + l2) / 2
area = math.sqrt(max(0.0, s * (s - l0) * (s - l1) * (s - l2)))
for v in tri:
m[v] += area / 3 # @line L4
return a, m, edges
def energy(edges, u):
"""E(u) = sum of w_ij |u_j - r_ij u_i|^2 over the edges."""
return sum(w * abs(u[j] - r * u[i]) ** 2 for i, j, w, r in edges)
def hermitian_form(a, u):
return sum((u[p].conjugate() * a[p][q] * u[q] for p in range(len(u)) for q in range(len(u)) if a[p][q])).real
def complex_cholesky(a):
"""The lower triangular l with a = l l^H, for a Hermitian positive definite a."""
n = len(a)
l = [[0j] * n for _ in range(n)]
for i in range(n):
for j in range(i + 1):
s = a[i][j] - sum(l[i][k] * l[j][k].conjugate() for k in range(j))
if i == j:
if s.real <= 0:
raise ValueError("matrix is not positive definite")
l[i][i] = complex(math.sqrt(s.real), 0.0)
else:
l[i][j] = s / l[j][j].real
return l
def cholesky_solve(l, b):
"""Solve l l^H x = b."""
n = len(l)
y = [0j] * n
for i in range(n):
y[i] = (b[i] - sum(l[i][k] * y[k] for k in range(i))) / l[i][i].real
x = [0j] * n
for i in range(n - 1, -1, -1):
x[i] = (y[i] - sum(l[k][i].conjugate() * x[k] for k in range(i + 1, n))) / l[i][i].real
return x
def apply_a(edges, u):
"""A u, from the edge list (each edge adds its 2 by 2 block)."""
out = [0j] * len(u)
for i, j, w, r in edges:
out[i] += w * (u[i] - r.conjugate() * u[j])
out[j] += w * (u[j] - r * u[i])
return out
def residual(edges, m, u, lam):
"""The size of A u - lambda M u in the M^(-1) norm."""
au = apply_a(edges, u)
return math.sqrt(sum(abs(au[p] - lam * m[p] * u[p]) ** 2 / m[p] for p in range(len(u))))
def smoothest_field(vertices, faces, n=4, seed=0, eps=1e-8, tol=1e-10, max_steps=10000):
"""The smoothest n-direction field: (u, lambda, steps), with u* M u = 1 and lambda = u* A u.
The loop stops when the residual |A u - lambda M u| in the M^(-1) norm is at most
tol * max(1, lambda); then some eigenvalue lies within that distance of lambda.
"""
a, m, edges = energy_matrices(vertices, faces, n)
nv = len(vertices)
shift = eps * max(abs(a[i][i]) for i in range(nv)) / max(m)
b = [[a[p][q] + (shift * m[p] if p == q else 0) for q in range(nv)] for p in range(nv)]
l = complex_cholesky(b) # @line L5
rng = random.Random(seed)
u = [complex(rng.gauss(0, 1), rng.gauss(0, 1)) for _ in range(nv)] # @line L6
for step in range(1, max_steps + 1):
y = cholesky_solve(l, [m[p] * u[p] for p in range(nv)]) # @line L7
norm = math.sqrt(sum(m[p] * abs(y[p]) ** 2 for p in range(nv)))
u = [x / norm for x in y] # @line L8
lam = energy(edges, u) # @line L9
if residual(edges, m, u, lam) <= tol * max(1.0, lam): # @line L10
return u, lam, step # @line L11
raise ArithmeticError("inverse iteration did not converge in max_steps steps")
def directions(u, n):
"""One of the n directions at each vertex, as an angle in the frame of the vertex (None where u = 0)."""
return [cmath.phase(x) / n if abs(x) > 0 else None for x in u]
def face_indices(vertices, faces, u, n):
"""The index of the field in each face, a multiple of 1/n (the singularities are the faces with index != 0).
index = (n K_f + sum of the turns) / (2 pi n), where K_f is the scaled angle sum of f minus pi (the
curvature of the frames in f) and each turn, in (-pi, pi], is the angle from the transported value
to the value at the next corner.
"""
phi, scale, ang = tangent_frames(vertices, faces)
out = []
for f, tri in enumerate(faces):
k_f = sum(scale[tri[c]] * ang[f][c] for c in range(3)) - math.pi
turn = 0.0
for c in range(3):
p, q = tri[c], tri[(c + 1) % 3]
turn += cmath.phase(u[q] / (transport(phi, p, q, n) * u[p]))
out.append((turn + n * k_f) / (2 * math.pi * n))
return out
mx2geom.py 150 lines
# SPDX-License-Identifier: MIT
# Shared helper of the mx2 cad pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small tools for triangle meshes, used by the mx2 pages.
Points are tuples of int, fractions.Fraction or float. ORIENT2D is exact
when the coordinates are int or Fraction. A mesh is a list of faces, each a
tuple of three vertex indices, oriented so that the outward normal follows
the right-hand rule (counterclockwise seen from outside).
"""
import math
from fractions import Fraction
def orient2d(a, b, c):
"""Twice the signed area of triangle abc: > 0 if counterclockwise."""
return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])
def exact_orient2d(a, b, c):
"""ORIENT2D with the float coordinates converted to rationals first, so the sign is exact."""
return orient2d(*[tuple(Fraction(x) for x in p) for p in (a, b, c)])
def solve(a, b, tol=0.0):
"""Solve a x = b by Gaussian elimination with partial pivoting.
a is a list of n rows of length n, b is a list of n rows of length m
(m right-hand sides). Entries are Fraction (exact), float or complex.
Raises ValueError if a pivot has absolute value <= tol.
"""
n = len(a)
m = len(b[0]) if n else 0
rows = [list(a[i]) + list(b[i]) for i in range(n)]
for col in range(n):
piv = max(range(col, n), key=lambda r: abs(rows[r][col]))
if abs(rows[piv][col]) <= tol:
raise ValueError("singular matrix")
rows[col], rows[piv] = rows[piv], rows[col]
pr = rows[col]
for r in range(col + 1, n):
f = rows[r][col]
if f:
f = Fraction(f) / pr[col] if isinstance(f, int) and isinstance(pr[col], int) else f / pr[col]
row = rows[r]
for k in range(col, n + m):
if pr[k]:
row[k] -= f * pr[k]
x = [[0] * m for _ in range(n)]
for i in range(n - 1, -1, -1):
row = rows[i]
for k in range(m):
s = row[n + k]
for j in range(i + 1, n):
if row[j]:
s -= row[j] * x[j][k]
x[i][k] = Fraction(s) / row[i] if isinstance(s, int) and isinstance(row[i], int) else s / row[i]
return x
def cholesky(a):
"""The lower triangular factor l with a = l l^T of a symmetric positive definite float matrix."""
n = len(a)
l = [[0.0] * n for _ in range(n)]
for i in range(n):
for j in range(i + 1):
s = a[i][j] - sum(l[i][k] * l[j][k] for k in range(j))
if i == j:
if s <= 0:
raise ValueError("matrix is not positive definite")
l[i][i] = math.sqrt(s)
else:
l[i][j] = s / l[j][j]
return l
def cholesky_solve(l, b):
"""Solve l l^T x = b for one right-hand side b, a list of floats."""
n = len(l)
y = [0.0] * n
for i in range(n):
y[i] = (b[i] - sum(l[i][k] * y[k] for k in range(i))) / l[i][i]
x = [0.0] * n
for i in range(n - 1, -1, -1):
x[i] = (y[i] - sum(l[k][i] * x[k] for k in range(i + 1, n))) / l[i][i]
return x
def directed_edges(faces):
"""Map each directed edge (i, j) to (face index, corner of i). Raises on a repeated directed edge."""
out = {}
for f, tri in enumerate(faces):
for k in range(3):
e = (tri[k], tri[(k + 1) % 3])
if e in out:
raise ValueError("directed edge %r used twice: not an oriented manifold" % (e,))
out[e] = (f, k)
return out
def undirected_edges(faces):
"""The sorted list of edges, each a sorted pair of vertex indices."""
return sorted({tuple(sorted((tri[k], tri[(k + 1) % 3]))) for tri in faces for k in range(3)})
def boundary_loop(faces):
"""The boundary of an oriented disk as one vertex loop, in the order of the face orientation."""
de = directed_edges(faces)
nxt = {}
for i, j in de:
if (j, i) not in de:
if i in nxt:
raise ValueError("boundary vertex %r is not manifold" % (i,))
nxt[i] = j
if not nxt:
raise ValueError("the mesh has no boundary")
start = min(nxt)
loop = [start]
while True:
v = nxt[loop[-1]]
if v == start:
break
loop.append(v)
if len(loop) != len(nxt):
raise ValueError("the boundary has more than one loop")
return loop
def euler_characteristic(faces):
"""V - E + F of the mesh, counting only the vertices used by faces."""
verts = {v for tri in faces for v in tri}
return len(verts) - len(undirected_edges(faces)) + len(faces)
def length(p, q):
return math.sqrt(sum((float(a) - float(b)) ** 2 for a, b in zip(p, q)))
def corner_angle(a, b, c):
"""The angle opposite the side of length a in a triangle with sides a, b, c (law of cosines)."""
x = (b * b + c * c - a * a) / (2 * b * c)
return math.acos(max(-1.0, min(1.0, x)))
def triangle_frame(p0, p1, p2):
"""Corners of a congruent counterclockwise 2D triangle: p0 at 0, p1 on the positive x-axis."""
l01, l12, l20 = length(p0, p1), length(p1, p2), length(p2, p0)
a0 = corner_angle(l12, l01, l20)
return (0.0, 0.0), (l01, 0.0), (l20 * math.cos(a0), l20 * math.sin(a0))
test_globally_optimal_direction_fields.py 154 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/globally-optimal-direction-fields/. The authors are listed in prov/8TE408.jsonl.
import math
import random
from globally_optimal_direction_fields import energy, energy_matrices, face_indices, hermitian_form, smoothest_field
from mx2geom import euler_characteristic
TET_V = [(1, 1, 1), (1, -1, -1), (-1, 1, -1), (-1, -1, 1)]
TET_F = [(0, 1, 2), (0, 3, 1), (0, 2, 3), (1, 3, 2)]
OCTA_V = [(1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, -1, 0), (0, 0, 1), (0, 0, -1)]
OCTA_F = [(0, 2, 4), (2, 1, 4), (1, 3, 4), (3, 0, 4), (2, 0, 5), (1, 2, 5), (3, 1, 5), (0, 3, 5)]
PYR_V = [(-1, -1, 0), (1, -1, 0), (1, 1, 0), (-1, 1, 0), (0, 0, 1)]
PYR_F = [(0, 1, 4), (1, 2, 4), (2, 3, 4), (3, 0, 4)]
_T = (1 + 5 ** 0.5) / 2
ICO_V = [(-1, _T, 0), (1, _T, 0), (-1, -_T, 0), (1, -_T, 0), (0, -1, _T), (0, 1, _T),
(0, -1, -_T), (0, 1, -_T), (_T, 0, -1), (_T, 0, 1), (-_T, 0, -1), (-_T, 0, 1)]
ICO_F = [(0, 11, 5), (0, 5, 1), (0, 1, 7), (0, 7, 10), (0, 10, 11), (1, 5, 9), (5, 11, 4), (11, 10, 2), (10, 7, 6), (7, 1, 8),
(3, 9, 4), (3, 4, 2), (3, 2, 6), (3, 6, 8), (3, 8, 9), (4, 9, 5), (2, 4, 11), (6, 2, 10), (8, 6, 7), (9, 8, 1)]
CLOSED = [(TET_V, TET_F), (OCTA_V, OCTA_F), (ICO_V, ICO_F)]
def jittered(vertices, seed, amount=0.15):
rng = random.Random(seed)
return [tuple(c + rng.uniform(-amount, amount) for c in p) for p in vertices]
def flat_disk(seed):
"""A jittered hexagonal patch of the plane, 19 vertices."""
rng = random.Random(seed)
pts, index = [], {}
for i in range(-2, 3):
for j in range(-2, 3):
if abs(i + j) <= 2:
index[(i, j)] = len(pts)
pts.append((i + 0.5 * j + rng.uniform(-0.1, 0.1), j * math.sqrt(3) / 2 + rng.uniform(-0.1, 0.1), 0.0))
faces = []
for (i, j), v in index.items():
if (i + 1, j) in index and (i, j + 1) in index:
faces.append((v, index[(i + 1, j)], index[(i, j + 1)]))
if (i + 1, j) in index and (i + 1, j - 1) in index:
faces.append((v, index[(i + 1, j - 1)], index[(i + 1, j)]))
return pts, faces
def jacobi_eigenvalues(s, sweeps=100):
"""All eigenvalues of a real symmetric matrix by cyclic Jacobi rotations (a slow, independent reference)."""
a = [row[:] for row in s]
n = len(a)
for _ in range(sweeps):
off = sum(a[p][q] ** 2 for p in range(n) for q in range(n) if p != q)
if off < 1e-30:
break
for p in range(n - 1):
for q in range(p + 1, n):
if abs(a[p][q]) < 1e-300:
continue
theta = (a[q][q] - a[p][p]) / (2 * a[p][q])
t = (1.0 if theta >= 0 else -1.0) / (abs(theta) + math.sqrt(theta * theta + 1))
c = 1 / math.sqrt(t * t + 1)
sn = t * c
for k in range(n):
akp, akq = a[k][p], a[k][q]
a[k][p], a[k][q] = c * akp - sn * akq, sn * akp + c * akq
for k in range(n):
apk, aqk = a[p][k], a[q][k]
a[p][k], a[q][k] = c * apk - sn * aqk, sn * apk + c * aqk
return sorted(a[i][i] for i in range(n))
def smallest_by_brute_force(a, m):
"""The smallest eigenvalue of A u = lambda M u: the Hermitian M^(-1/2) A M^(-1/2) as a real symmetric 2n matrix."""
n = len(a)
b = [[a[p][q] / math.sqrt(m[p] * m[q]) for q in range(n)] for p in range(n)]
s = [[0.0] * (2 * n) for _ in range(2 * n)]
for p in range(n):
for q in range(n):
s[p][q] = s[n + p][n + q] = b[p][q].real
s[p][n + q] = -b[p][q].imag
s[n + p][q] = b[p][q].imag
return jacobi_eigenvalues(s)[0]
def test_matrix_is_the_energy():
for v, f in CLOSED + [(PYR_V, PYR_F)]:
for n in (1, 2, 4):
a, m, edges = energy_matrices(v, f, n)
assert all(abs(a[p][q] - a[q][p].conjugate()) < 1e-14 for p in range(len(v)) for q in range(len(v)))
rng = random.Random(n)
u = [complex(rng.gauss(0, 1), rng.gauss(0, 1)) for _ in v]
assert abs(hermitian_form(a, u) - energy(edges, u)) < 1e-12 * max(1.0, energy(edges, u))
def test_eigenvalue_matches_brute_force_on_tiny_meshes():
for k, (v, f) in enumerate(CLOSED + [(PYR_V, PYR_F)]):
for seed in (0, 1):
vv = jittered(v, 10 * k + seed) if seed else v
for n in (1, 2, 4):
u, lam, _ = smoothest_field(vv, f, n)
a, m, edges = energy_matrices(vv, f, n)
assert abs(lam - smallest_by_brute_force(a, m)) < 1e-9
def test_no_random_field_is_smoother():
v = jittered(OCTA_V, 3)
for n in (1, 4):
u, lam, _ = smoothest_field(v, OCTA_F, n)
a, m, edges = energy_matrices(v, OCTA_F, n)
rng = random.Random(5)
for _ in range(2000):
w = [complex(rng.gauss(0, 1), rng.gauss(0, 1)) for _ in v]
assert energy(edges, w) / sum(mi * abs(x) ** 2 for mi, x in zip(m, w)) >= lam - 1e-12
# Small changes of the minimizer do not lower the quotient either.
for _ in range(500):
w = [x + complex(rng.gauss(0, 1e-3), rng.gauss(0, 1e-3)) for x in u]
assert energy(edges, w) / sum(mi * abs(x) ** 2 for mi, x in zip(m, w)) >= lam - 1e-12
def test_eigenvector_residual_is_small():
for v, f in CLOSED:
for n in (1, 2, 4):
u, lam, _ = smoothest_field(jittered(v, 7), f, n)
a, m, _ = energy_matrices(jittered(v, 7), f, n)
assert abs(sum(mi * abs(x) ** 2 for mi, x in zip(m, u)) - 1) < 1e-12
res = max(abs(sum(a[p][q] * u[q] for q in range(len(u))) - lam * m[p] * u[p]) for p in range(len(u)))
assert res < 1e-6
def test_flat_disk_has_a_parallel_field():
for seed in range(3):
v, f = flat_disk(seed)
for n in (1, 4):
u, lam, _ = smoothest_field(v, f, n)
assert lam < 1e-10
a, m, edges = energy_matrices(v, f, n)
assert max(abs(u[j] - r * u[i]) for i, j, w, r in edges) < 1e-5
def test_indices_add_up_to_the_euler_characteristic():
for k, (v, f) in enumerate(CLOSED):
for seed in range(3):
vv = jittered(v, 100 * k + seed)
for n in (1, 2, 4):
u, _, _ = smoothest_field(vv, f, n)
idx = face_indices(vv, f, u, n)
assert all(abs(x * n - round(x * n)) < 1e-9 for x in idx)
assert abs(sum(idx) - euler_characteristic(f)) < 1e-9
def test_octahedron_cross_field():
u, lam, _ = smoothest_field(OCTA_V, OCTA_F, 4)
assert lam < 1e-10
assert all(abs(x - 0.25) < 1e-9 for x in face_indices(OCTA_V, OCTA_F, u, 4))
History
Fields of crosses and other symmetric directions were designed on meshes before 2013 by smoothing angles with integer period jumps, as in the work of Ray, Vallet, Li and Lévy in 2008, and by mixed-integer methods that round the jumps one at a time. These methods need a starting field or a choice of singularities. Felix Knöppel, Keenan Crane, Ulrich Pinkall and Peter Schröder showed in ACM Transactions on Graphics in 2013 that with the -th power representation and one global norm the problem becomes a smallest eigenvalue problem, whose answer is globally optimal and places the singularities by itself. The survey of Vaxman and others in 2016 places the method among the other representations of directional fields.
References
- Felix Knöppel, Keenan Crane, Ulrich Pinkall and Peter Schröder, Globally optimal direction fields, ACM Transactions on Graphics 32(4), Article 59, 2013, the n-th power representation, the quadratic smoothness energy with the discrete connection, the relaxation of the unit length condition to one global norm, and the smallest eigenvector computed by inverse iteration
- Nicolas Ray, Bruno Vallet, Wan Chiu Li and Bruno Lévy, N-symmetry direction field design, ACM Transactions on Graphics 27(2), Article 10, 2008, the representation of N-symmetry fields by angles and period jumps, and the index of a singularity
- Amir Vaxman, Marcel Campen, Olga Diamanti, Daniele Panozzo, David Bommes, Klaus Hildebrandt and Mirela Ben-Chen, Directional field synthesis, design, and processing, Computer Graphics Forum 35(2), 545-572, 2016, the survey of power vector representations, connection Laplacians and the eigenvector method among the field design methods
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 8TE408 Edit this page History Report an error Markdown