Algorithm Search⌘K

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
Properties
deterministicnot exactiterative
Origin
Felix Knöppel, Keenan Crane, Ulrich Pinkall, Peter Schröder, 2013

A smooth field of nn directions on a surface, such as a cross field with n=4n = 4, 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 nn-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 VV vertices, with faces oriented by the right-hand rule, and an integer n≥1n \ge 1. The output is an nn-direction field at the vertices that is as smooth as possible, with its singularities.

Frames and transport. At a vertex ii with corner angles α\alpha around it, scale the angles by si=2π/∑αs_i = 2\pi / \sum\alpha at an inner vertex and si=1s_i = 1 at a boundary vertex. Measure the direction of each edge ijij at ii by the angle φi(j)\varphi_i(j) from one chosen edge at ii, adding the scaled corner angles counterclockwise. The scaled angles at an inner vertex add up to 2π2\pi, so this is a full turn of directions in the tangent plane of ii. Moving from ii to jj along the edge, the direction of the edge turns from φi(j)\varphi_i(j) to φj(i)+π\varphi_j(i) + \pi, so a direction at angle θ\theta at ii is carried to θ+φj(i)+π−φi(j)\theta + \varphi_j(i) + \pi - \varphi_i(j) at jj. This is the discrete transport along the edge.

Representation. The nn directions at angles θ,θ+2π/n,…\theta, \theta + 2\pi/n, \dots at a vertex are stored as one complex number ui=einθu_i = e^{in\theta}, which does not depend on which of the nn directions is called θ\theta. Transport along ijij multiplies it by

rij=ein(φj(i)+π−φi(j)).r_{ij} = e^{in(\varphi_j(i) + \pi - \varphi_i(j))}.

Energy. With the cotangent weights wij=12(cot⁡αij+cot⁡βij)w_{ij} = \frac12(\cot\alpha_{ij} + \cot\beta_{ij}) of the cotangent Laplacian, the energy of a field u∈CVu \in \mathbb{C}^V is

E(u)=∑edges ijwij∣uj−rijui∣2=u∗Au,E(u) = \sum_{\text{edges } ij} w_{ij} \lvert u_j - r_{ij} u_i \rvert^2 = u^* A u,

where AA is Hermitian, with Aii=∑jwijA_{ii} = \sum_j w_{ij} and Aji=−wijrijA_{ji} = -w_{ij} r_{ij}, Aij=−wijrˉijA_{ij} = -w_{ij}\bar r_{ij}. It is zero exactly when every value is the transport of its neighbour, a parallel field.

Relaxation. The real problem asks for ∣ui∣=1\lvert u_i\rvert = 1 at every vertex, which is not convex. The relaxed problem asks only for u∗Mu=1u^* M u = 1, where MM is the diagonal matrix of vertex areas (one third of the areas of the triangles at the vertex):

min⁡u≠0u∗Auu∗Mu.\min_{u \ne 0} \frac{u^* A u}{u^* M u}.

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

  1. SmoothestField(M, n, ε, δ)
  2. 1for each vertex i: the frame angles φ_i(j) of its edges, with corner angles scaled by s_i
  3. 2for each edge ij: r_ij ← e^{in(φ_j(i) + π − φ_i(j))}, w_ij ← (cot α_ij + cot β_ij)/2
  4. 3A ← Σ over edges of w_ij |u_j − r_ij u_i|^2 written as a Hermitian matrix
  5. 4M ← diag(vertex areas)
  6. 5factor A + σM = L L^*, with σ = ε · max A_ii / max M_ii ▷ Cholesky, once
  7. 6u ← a random complex vector
  8. 7repeat: solve L L^* y = M u
  9. 8u ← y / sqrt(y^* M y)
  10. 9λ ← u^* A u
  11. 10until |A u − λ M u| in the M^{-1} norm ≤ δ · max(1, λ)
  12. 11return u, λ

Lines L1 to L4 build the problem in O(V)O(V) time. Line L5 adds a tiny multiple of MM so that the matrix is positive definite even when λ1=0\lambda_1 = 0, which happens when a parallel field exists. Lines L7 and L8 are one step of inverse iteration on the pencil A−λMA - \lambda M: a solve with the fixed factor and a normalization. Line L10 stops when the pair (u,λ)(u, \lambda) is an eigenpair up to δ\delta. The directions at a vertex are the nn-th roots of ui/∣ui∣u_i / \lvert u_i\rvert.

Singularities. The code of this page reads the index of the field in each face ff with vertices p0,p1,p2p_0, p_1, p_2 counterclockwise:

I(f)=nKf+∑cτc2πn,Kf=∑cspcαc−π,τc=arg⁡upc+1rpcpc+1upc∈(−π,π].I(f) = \frac{n K_f + \sum_{c} \tau_c}{2\pi n}, \qquad K_f = \sum_c s_{p_c} \alpha_c - \pi, \qquad \tau_c = \arg\frac{u_{p_{c+1}}}{r_{p_c p_{c+1}} u_{p_c}} \in (-\pi, \pi].

KfK_f is the curvature of the scaled frames in ff, and τc\tau_c is the turn from the transported value to the next value. I(f)I(f) is a multiple of 1/n1/n, and on a closed mesh the indices add up to χ=V−E+F=2−2g\chi = V - E + F = 2 - 2g. The faces with I(f)≠0I(f) \ne 0 are the singularities.

Example

The regular octahedron with n=4n = 4. Each vertex has four angles of 60°60°, so s=2π/(4π/3)=3/2s = 2\pi / (4\pi/3) = 3/2, and each face has Kf=3⋅32⋅π3−π=π/2K_f = 3 \cdot \tfrac32 \cdot \tfrac{\pi}{3} - \pi = \pi/2. Transport once around a face multiplies uu by e−4iKf=e−2πi=1e^{-4iK_f} = e^{-2\pi i} = 1, so a parallel cross field exists, λ1=0\lambda_1 = 0, and the code finds it in 2 steps. Every face has the index (4⋅π/2+0)/(8π)=1/4(4 \cdot \pi/2 + 0)/(8\pi) = 1/4, and the 8 faces give 2=χ2 = \chi. With n=1n = 1 or n=2n = 2 the transport around a face is not trivial, there is no parallel field, and the code returns λ1=1.0\lambda_1 = 1.0 in both cases.

The regular icosahedron. Five angles of 60°60° meet at each vertex, so s=6/5s = 6/5 and Kf=π/5K_f = \pi/5, and the transport around a face is trivial only for nn a multiple of 10. The code returned:

nn λ1\lambda_1 steps singular faces indices
1 0.27639320.2763932 17 2 1,11, 1
2 0.47639320.4763932 24 4 12\tfrac12 four times
4 0.55278640.5527864 43 8 14\tfrac14 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 1/41/4, like the corners of a cube. The eigenvalues agree to 10−910^{-9} 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 1,1,0.51, 1, 0.5, with seed 0, ε=10−8\varepsilon = 10^{-8}, δ=10−10\delta = 10^{-10}, dense factorization in pure Python:

mesh nn λ1\lambda_1 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 n=4n = 4 the residual did not reach δ\delta 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 uiu_i is set to unit length. It is always at least λ1\lambda_1, and here it is 1.3 to 2.7 times λ1\lambda_1. These numbers are measurements on these meshes, not bounds.

Correctness

The proof in proofs/correctness.md shows the following.

  1. E(u)=u∗AuE(u) = u^* A u with AA Hermitian, and AA is positive semidefinite when all weights wijw_{ij} are positive.
  2. Key invariant. The minimum of u∗Au/u∗Muu^* A u / u^* M u over u≠0u \ne 0 is the smallest eigenvalue λ1\lambda_1 of Au=λMuAu = \lambda M u, and it is reached exactly by the eigenvectors of λ1\lambda_1. The proof writes v=M1/2uv = M^{1/2} u and uses the spectral theorem for the Hermitian matrix M−1/2AM−1/2M^{-1/2} A M^{-1/2}. This is a generalized eigenvalue problem.
  3. If the random start has a nonzero part in the eigenspace of λ1\lambda_1, which happens with probability 1, inverse iteration converges to that eigenspace. If λ2\lambda_2 is the next distinct eigenvalue, the rest shrinks by the factor (λ1+σ)/(λ2+σ)(\lambda_1 + \sigma) / (\lambda_2 + \sigma) per step.
  4. A returned pair has u∗Mu=1u^* M u = 1, λ=u∗Au≥λ1\lambda = u^* A u \ge \lambda_1, and an eigenvalue within δmax⁡(1,λ)\delta \max(1, \lambda) of λ\lambda.
  5. The face indices are multiples of 1/n1/n, and on a closed mesh they add up to χ\chi.

So the code solves the relaxed problem exactly, up to the stopping test. It does not solve the problem with ∣ui∣=1\lvert u_i\rvert = 1: 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 λ1\lambda_1.

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. MM is a connected, oriented triangle mesh with vertices 1,…,V1, \dots, V, faces oriented by the right-hand rule, and an integer n≥1n \ge 1. The frame angles φi(j)\varphi_i(j), the transports rijr_{ij}, the weights wijw_{ij}, the matrix AA and the diagonal matrix MM 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 mim_i of MM is positive. R(u)=u∗Au/u∗MuR(u) = u^* A u / u^* M u for u≠0u \ne 0. Eigenvalues of Au=λMuAu = \lambda Mu are listed with repetition as λ1≤λ2≤⋯≤λV\lambda_1 \le \lambda_2 \le \dots \le \lambda_V.

Claim.

  1. E(u)=u∗AuE(u) = u^* A u with AA Hermitian. If all wij>0w_{ij} > 0, then AA is positive semidefinite.
  2. min⁡u≠0R(u)=λ1\min_{u \ne 0} R(u) = \lambda_1, and R(u)=λ1R(u) = \lambda_1 exactly when uu is an eigenvector for λ1\lambda_1. Every local minimizer of RR is such an eigenvector.
  3. If AA is positive semidefinite and σ>0\sigma > 0, line L5 succeeds. If the start of line L6 has a nonzero component in the eigenspace of λ1\lambda_1, the iterates of lines L7 and L8 converge to that eigenspace, and the residual of line L10 tends to 0.
  4. The algorithm terminates. A returned pair has u∗Mu=1u^* M u = 1, λ=u∗Au≥λ1\lambda = u^* A u \ge \lambda_1, and some eigenvalue λk\lambda_k with ∣λk−λ∣≤δmax⁡(1,λ)\lvert \lambda_k - \lambda \rvert \le \delta \max(1, \lambda).
  5. Each face index I(f)I(f) is a multiple of 1/n1/n. On a closed mesh, ∑fI(f)=χ\sum_f I(f) = \chi, when no uiu_i is zero and no turn τ\tau is exactly π\pi.

Proof of 1. For one edge, with a=uia = u_i and b=ujb = u_j,

∣b−ra∣2=(b−ra)∗(b−ra)=∣a∣2+∣b∣2−bˉ r a−aˉ rˉ b,\lvert b - r a \rvert^2 = (b - ra)^*(b - ra) = \lvert a\rvert^2 + \lvert b\rvert^2 - \bar b\, r\, a - \bar a\, \bar r\, b,

because ∣r∣=1\lvert r\rvert = 1. Multiplied by wijw_{ij}, these are the four entries Aii+=wijA_{ii} \mathrel{+}= w_{ij}, Ajj+=wijA_{jj} \mathrel{+}= w_{ij}, Aji−=wijrijA_{ji} \mathrel{-}= w_{ij} r_{ij} and Aij−=wijrˉijA_{ij} \mathrel{-}= w_{ij} \bar r_{ij} of line L3. Summing over the edges gives E(u)=u∗AuE(u) = u^* A u. The diagonal is real, and Aij=Aji‾A_{ij} = \overline{A_{ji}}, so AA is Hermitian. If all wij>0w_{ij} > 0, EE is a sum of nonnegative terms, so u∗Au≥0u^* A u \ge 0 for all uu. □\square

Proof of 2. MM is diagonal with positive entries, so M1/2M^{1/2} and M−1/2M^{-1/2} exist. Put v=M1/2uv = M^{1/2} u and B=M−1/2AM−1/2B = M^{-1/2} A M^{-1/2}. BB is Hermitian, u∗Mu=v∗vu^* M u = v^* v and u∗Au=v∗Bvu^* A u = v^* B v, so R(u)=v∗Bv/v∗vR(u) = v^* B v / v^* v. Also Au=λMuAu = \lambda M u exactly when Bv=λvB v = \lambda v, so BB has the eigenvalues λk\lambda_k. By the spectral theorem, BB has an orthonormal basis of eigenvectors q1,…,qVq_1, \dots, q_V with Bqk=λkqkB q_k = \lambda_k q_k. Write v=∑kckqkv = \sum_k c_k q_k. Then

R(u)=∑kλk∣ck∣2∑k∣ck∣2≥λ1,R(u) = \frac{\sum_k \lambda_k \lvert c_k\rvert^2}{\sum_k \lvert c_k\rvert^2} \ge \lambda_1,

with equality exactly when ck=0c_k = 0 for every kk with λk>λ1\lambda_k > \lambda_1, that is, when vv is in the eigenspace of λ1\lambda_1. The value λ1\lambda_1 is reached at v=q1v = q_1.

For the local minimizers: let uu be a local minimizer and v=M1/2uv = M^{1/2} u. The quotient is smooth at v≠0v \ne 0, and its derivative in the direction hh is 2 Re(h∗(Bv−Rv))/v∗v2\,\mathrm{Re}(h^*(Bv - R v)) / v^* v. At a local minimizer it vanishes for all hh, so Bv=R(u)vB v = R(u) v: vv is an eigenvector, for some eigenvalue μ\mu. If μ>λ1\mu > \lambda_1, take a unit eigenvector qq of λ1\lambda_1; it is orthogonal to vv because they belong to different eigenvalues of a Hermitian matrix. For vt=v+t∥v∥qv_t = v + t\lVert v\rVert q, the quotient is (μ+t2λ1)/(1+t2)<μ(\mu + t^2 \lambda_1)/(1 + t^2) < \mu for every t≠0t \ne 0, so vv is not a local minimizer. Hence μ=λ1\mu = \lambda_1. □\square

Proof of 3. max⁡iAii>0\max_i A_{ii} > 0 because some weight is positive in a mesh with a triangle, so σ>0\sigma > 0. For u≠0u \ne 0, u∗(A+σM)u=u∗Au+σu∗Mu>0u^*(A + \sigma M)u = u^* A u + \sigma u^* M u > 0, so A+σMA + \sigma M is Hermitian positive definite and has a Cholesky factor LL∗L L^*. In the coordinates vv of claim 2, line L7 computes y=(A+σM)−1Muy = (A + \sigma M)^{-1} M u, which is M1/2y=(B+σI)−1vM^{1/2} y = (B + \sigma I)^{-1} v. So in these coordinates one step of lines L7 and L8 is v↦(B+σI)−1vv \mapsto (B + \sigma I)^{-1} v followed by scaling to length 1. After kk steps,

vk∝∑jcj(λj+σ)k qj.v_k \propto \sum_j \frac{c_j}{(\lambda_j + \sigma)^k}\, q_j.

Let PP be the indices with λj=λ1\lambda_j = \lambda_1, and let λ′\lambda' be the smallest eigenvalue larger than λ1\lambda_1 (if there is none, v0v_0 is already an eigenvector of BB after the first step). The ratio of the part outside PP to the part in PP is at most

(λ1+σλ′+σ)k(∑j∉P∣cj∣2)1/2(∑j∈P∣cj∣2)1/2,\Big(\frac{\lambda_1 + \sigma}{\lambda' + \sigma}\Big)^k \frac{\big(\sum_{j \notin P} \lvert c_j\rvert^2\big)^{1/2}}{\big(\sum_{j \in P} \lvert c_j\rvert^2\big)^{1/2}},

because λj+σ≥λ′+σ\lambda_j + \sigma \ge \lambda' + \sigma for j∉Pj \notin P 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 vkv_k to the eigenspace of λ1\lambda_1 tends to 0. The Rayleigh quotient and the residual ∥(B−R)vk∥\lVert (B - R) v_k \rVert are continuous in vkv_k, and they are λ1\lambda_1 and 0 on the unit vectors of that eigenspace, so they tend to λ1\lambda_1 and to 0. □\square

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 u∗Mu=1u^* M u = 1, and line L9 has set λ=u∗Au=R(u)≥λ1\lambda = u^* A u = R(u) \ge \lambda_1 by claim 2. The residual of line L10 is ρ=(∑i∣(Au−λMu)i∣2/mi)1/2=∥M−1/2(Au−λMu)∥=∥(B−λI)v∥\rho = \big(\sum_i \lvert (Au - \lambda M u)_i\rvert^2 / m_i\big)^{1/2} = \lVert M^{-1/2}(Au - \lambda Mu)\rVert = \lVert (B - \lambda I) v\rVert, with ∥v∥=1\lVert v\rVert = 1. In the basis of claim 2,

ρ2=∑k(λk−λ)2∣ck∣2≥min⁡k(λk−λ)2∑k∣ck∣2=min⁡k(λk−λ)2.\rho^2 = \sum_k (\lambda_k - \lambda)^2 \lvert c_k\rvert^2 \ge \min_k (\lambda_k - \lambda)^2 \sum_k \lvert c_k\rvert^2 = \min_k (\lambda_k - \lambda)^2.

So some eigenvalue lies within ρ≤δmax⁡(1,λ)\rho \le \delta\max(1, \lambda) of λ\lambda. Claim 4 does not say that this eigenvalue is λ1\lambda_1; that follows from claim 3 when the iteration has converged, and the tests compare λ\lambda with λ1\lambda_1 from a dense eigenvalue computation. □\square

Proof of 5. Let ff have the corners p0,p1,p2p_0, p_1, p_2 in counterclockwise order, and let αc\alpha_c be the angle at pcp_c. At the corner pcp_c the face lies between the edges to pc+1p_{c+1} and to pc+2=pc−1p_{c+2} = p_{c-1} (indices mod 3), in this counterclockwise order around pcp_c, so line L1 gives φpc(pc−1)≡φpc(pc+1)+spcαc(mod2π)\varphi_{p_c}(p_{c-1}) \equiv \varphi_{p_c}(p_{c+1}) + s_{p_c}\alpha_c \pmod{2\pi}. Then, summing the exponents of the three transports rpcpc+1r_{p_c p_{c+1}} and grouping the terms by vertex,

∑c(φpc+1(pc)+π−φpc(pc+1))=3π+∑c(φpc(pc−1)−φpc(pc+1))≡3π+∑cspcαc=4π+Kf≡Kf(mod2π).\sum_c \big(\varphi_{p_{c+1}}(p_c) + \pi - \varphi_{p_c}(p_{c+1})\big) = 3\pi + \sum_c \big(\varphi_{p_c}(p_{c-1}) - \varphi_{p_c}(p_{c+1})\big) \equiv 3\pi + \sum_c s_{p_c}\alpha_c = 4\pi + K_f \equiv K_f \pmod{2\pi}.

Multiplying by nn, ∏crpcpc+1=einKf\prod_c r_{p_c p_{c+1}} = e^{inK_f}. Each turn satisfies eiτc=upc+1/(rpcpc+1upc)e^{i\tau_c} = u_{p_{c+1}} / (r_{p_c p_{c+1}} u_{p_c}), and the product of the three quotients telescopes:

ei∑cτc=1∏crpcpc+1=e−inKf.e^{i\sum_c \tau_c} = \frac{1}{\prod_c r_{p_c p_{c+1}}} = e^{-inK_f}.

So nKf+∑cτcnK_f + \sum_c \tau_c is a multiple of 2π2\pi, and I(f)=(nKf+∑cτc)/(2πn)I(f) = (nK_f + \sum_c\tau_c)/(2\pi n) is a multiple of 1/n1/n.

Now let the mesh be closed, with VV vertices, EE edges and FF faces. Every vertex is inner, so the scaled angles at each vertex add up to 2π2\pi, and

∑fKf=∑v2π−πF=2πV−πF=2π(V−E+F)=2πχ,\sum_f K_f = \sum_v 2\pi - \pi F = 2\pi V - \pi F = 2\pi (V - E + F) = 2\pi\chi,

because each face has three edges and each edge two faces, so 3F=2E3F = 2E and πF=2π(E−F)\pi F = 2\pi(E - F). For the turns, each edge pqpq is crossed once as p→qp \to q in one face and once as q→pq \to p in the other. From the definition, rpqrqp=ein⋅2π=1r_{pq} r_{qp} = e^{in \cdot 2\pi} = 1. So

uprqpuq=rpqupuq=(uqrpqup)−1,\frac{u_p}{r_{qp} u_q} = \frac{r_{pq} u_p}{u_q} = \Big(\frac{u_q}{r_{pq} u_p}\Big)^{-1},

and the two turns are τ\tau and −τ-\tau, since the argument in (−π,π](-\pi, \pi] of 1/z1/z is minus that of zz when arg⁡z≠π\arg z \ne \pi. So all turns add up to 0, and ∑fI(f)=n⋅2πχ/(2πn)=χ\sum_f I(f) = n \cdot 2\pi\chi / (2\pi n) = \chi. □\square

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 χ\chi. ■\blacksquare

Complexity

Lines L1 to L4 take O(V)O(V) time. With a dense factorization, as in the code, line L5 takes O(V3)O(V^3) time and O(V2)O(V^2) space once, and each step of lines L7 to L10 takes O(V2)O(V^2). For kk steps the total is O(V3+kV2)O(V^3 + k V^2). AA has one nonzero entry per vertex and two per edge, so a sparse Cholesky factorization with nested dissection on the planar mesh graph takes O(V3/2)O(V^{3/2}) time and O(Vlog⁡V)O(V \log V) space, and each solve then takes O(Vlog⁡V)O(V \log V). The factor is computed once, which is why one eigenvector is about as cheap as one linear solve when kk is small. The number kk 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 u∗Mu=1u^* M u = 1, the relaxed problem. This optimum is global: every local minimum of the quotient is an eigenvector of λ1\lambda_1.
  • Proved. The returned λ\lambda is at least λ1\lambda_1, and the residual test certifies an eigenvalue within δmax⁡(1,λ)\delta \max(1, \lambda).
  • Proved. The face indices are multiples of 1/n1/n and add up to χ\chi 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 λ1<10−10\lambda_1 < 10^{-10} and ∣uj−rijui∣<10−5\lvert u_j - r_{ij} u_i\rvert < 10^{-5} 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 uu only by a phase when λ1\lambda_1 is simple.

Variants and improvements

  • Alignment to given directions. Knöppel et al. also fit the field to a given field qq, such as the principal curvature directions from curvature tensor estimation, by solving one linear system of the form (A−λM)u=Mq(A - \lambda M) u = M q with a parameter λ\lambda below λ1\lambda_1.
  • 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 λ1\lambda_1 converges faster than plain inverse iteration when the two smallest eigenvalues are close. Power iteration on AA itself would find the largest eigenvalue instead, the roughest field.
  • Quad meshing. The cross field with n=4n = 4 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, cot⁡α+cot⁡β\cot\alpha + \cot\beta can be negative. Then EE can take negative values and AA 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 uu 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 λ1=0\lambda_1 = 0, as on the octahedron with n=4n = 4 or on a flat disk, AA is singular and its Cholesky factorization fails. Add σM\sigma M with a small σ>0\sigma > 0, as in line L5.
  • Unscaled angles. Without the scaling sis_i, the frame at an inner vertex with angle sum other than 2π2\pi 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 uu winds around zero, not where ∣u∣\lvert u\rvert is small. Compute the index from the turns and the curvature; the size of uu 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.

globally_optimal_direction_fields.pyI0RawGitHub
# 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 nn-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

  1. 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
  2. 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
  3. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.dense
  • a full proof of time.nested_dissection
  • a full proof of space.dense
  • a full proof of space.nested_dissection
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example