Applied differential geometry I: manifolds, geodesics and learning on meshes
Connect smooth manifold geometry to triangle meshes, cotangent Laplacians, heat geodesics and intrinsic networks under remeshing.
After this lesson you can
- Describe tangent spaces, geodesics and parallel transport on a sphere.
- Assemble cotangent stiffness and mass matrices on triangle meshes.
- Interpret curvature, spectra and heat-based geodesic approximations.
- Explain gauge-compatible surface networks and remeshing evaluation.
- Measure mesh segmentation results with explicit data and transfer limitations.
Before you start
- 25Combinatorial graph LaplacianGraph heat kernelGraph Fourier transformSteerable kernelsInduced action on signals and fieldsIrreducible representations
- 03Regular level sets as submanifoldsGradient
- 29Finite element assemblyGalerkin method
- 09Krylov subspaces, Arnoldi and LanczosSymmetric eigensolvers
- 24Sparsity and variable ordering in SLAMSO(3) exponential and logarithm maps
One shape, many meshes
One surface can be represented with large or small triangles. If a network learns to recognize parts of a human figure, changing the mesh should not by itself change its prediction. Yet averaging neighbors treats each edge as a unit: when refining the mesh, one layer travels a smaller physical distance. We need geometry that distinguishes the surface from its representation.
This lesson builds that bridge: first lengths and geodesics on a smooth manifold, then areas, curvature and operators on triangles. The combinatorial Laplacian does not account for lengths or angles, while the cotangent operator incorporates each face’s geometry. Its eigenvectors are discrete analogues of membrane vibration modes.
The sphere as a manifold laboratory
A smooth manifold and its tangent space can be understood through charts: around each point of a two-dimensional manifold there are local coordinates in an open subset of , related by smooth changes. On a surface defined as a regular level set , the regular level set theorem identifies the tangent plane as the kernel of .
For the unit sphere, , so . A curve on the sphere has tangent velocity because differentiating yields . Do not confuse the tangent space, a vector plane with origin zero, with the affine plane touching the sphere at .
The Riemannian metric and geodesics equip each tangent space with a smoothly varying inner product. On an embedded surface use the restricted Euclidean product. Curve length is . A geodesic has zero covariant acceleration; it locally minimizes length, though it may cease to minimize when extended.
On the unit sphere, for , and ,
For it is defined by continuity as . The corresponding path is a great circle at constant speed: acceleration is normal to the sphere and its tangent component vanishes. If and , the local inverse is , with value zero when . At the antipode infinitely many minimizing geodesics exist and the logarithm is not unique.
Parallel transport keeps a vector’s covariant derivative zero as it moves along a curve. On the sphere, a vector transported around a geodesic triangle returns rotated: the oriented angle modulo equals oriented area on the unit sphere. This is holonomy, not an arbitrary coordinate rotation.
From triangles to curvature
A triangle mesh consists of vertices and oriented faces . For nondegenerate face , its unnormalized oriented normal is and area is half its norm. A vertex normal can be estimated by summing those area normals and normalizing, provided the sum is nonzero.
At an interior vertex of a polyhedral surface, angular defect is . This is integrated curvature, not density: to approximate the latter divide by a positive dual area. A simple choice is barycentric area, one third of each incident face’s area. Mixed Voronoi areas require special treatment for obtuse triangles; uncorrected circumcentric Voronoi formulas can produce negative areas.
For a closed orientable mesh, discrete Gauss-Bonnet states . In a regular icosahedron five angles meet at each vertex, so each defect is and twelve sum to . With boundary, is used at boundary vertices; the preceding identity without that correction does not hold.
The cotangent operator and mass
The positive cotangent Laplacian is assembled as stiffness matrix : for each interior edge with opposite angles , , and . A boundary edge receives only the angle of its sole face. This is the FEM stiffness matrix for facewise linear functions; Rayleigh quotient approximates energy divided by norm .
The lumped diagonal mass matrix represents integration by barycentric areas. The problem is , not . Mass makes eigenvectors orthonormal in product and correctly expresses surface scale. On a sphere of radius , continuous eigenvalues are , with multiplicity . A finite mesh only approximates them and discretization can split a multiplicity.
Global matrix is symmetric positive semidefinite even if an individual cotangent is negative in an obtuse triangle. Negative weights can prevent a discrete maximum principle; an intrinsic Delaunay triangulation controls interior weight signs under its assumptions. Global symmetry and positivity do not imply every weight is positive.
Each eigenvector is normalized to show shape, not physical amplitude. Within a multiple eigenvalue a solver can choose any orthonormal basis of the subspace: comparing one vector’s orientation or sign across resolutions does not prove the mode changed. Compare eigenvalue sets and subspaces. A truncated spectrum can also cut through a multiplicity.
The ellipsoidal piece is obtained by scaling the sphere’s three axes by 0.55, 0.8 and 1. The transformation changes the metric and is not an isometric deformation; an identical spectrum to the sphere should not be expected. At each resolution uniform and cotangent operators are reassembled separately.
The sheet offers another control. Map rolls the flat domain into a cylinder: derivatives with respect to and are orthogonal with unit norm, so the continuous metric is preserved. Triangular faces join points by chords and the discretization is therefore not an exact isometry. For the first eight nonconstant eigenvalues, maximum relative difference between flat and rolled was 3.27 %, 0.785 % and 0.200 % across the figure’s three refinements. Sheets have boundaries and this problem uses the natural Neumann condition; the experiment does not prove convergence for every mesh.
A spectral shape signature can use the first eigenvalues, as in ShapeDNA, or the heat-kernel diagonal . Truncating the sum creates error depending on and mode count: at very small times high frequencies are missing. A functional map represents correspondence between surfaces as a map between function bases rather than immediately pairing points.
Distance via heat
The heat method for geodesics approximates distance from a source in three steps. With positive solve ; calculate facewise where norm is nonzero; and seek a potential whose gradient matches by solving a Poisson problem with one degree of freedom fixed. Then subtract the source value. Matrix factorizations can be reused for multiple sources, as explained by Crane, Weischedel and Wardetzky.
has units of length squared. A common choice scales with the square of a representative edge length. Too small can make the gradient numerically unstable; too large oversmooths. Edge Dijkstra computes shortest distance restricted to the edge network, not the continuous geodesic that may cross faces. On a sphere the reference is also known.
Networks aware of the surface
Intrinsic mesh networks make communication depend on internal geometry. Geodesic CNNs define neighborhoods using surface distances; MoNet learns kernels on local coordinates. DiffusionNet combines diffusion with learnable times, pointwise MLPs and gradient features; its operators can be discretized across representations. Remeshing robustness is evaluated, not a guarantee of exact identity under every finite discretization.
A general surface has no canonical global tangent north. Rotating the local basis changes vector coordinates even though the geometric vector is the same. A scalar layer must return the same result, while a vector output must transform coordinates with the appropriate representation. Gauge-equivariant CNNs impose that law and transport features between frames. A network using directions without controlling the frame can change its prediction merely by choosing another basis.
To see this algebraically, let be the orthogonal matrix whose columns are frame vectors, and a fixed physical operator. In local coordinates the operator is ; transforming output back gives . If instead the same diagonal matrix is used in every frame, the physical operator changes when rotates. This illustrates a local transformation; a mesh network must also compare and transport features between different tangent planes.
Lab: geometry on a closed mesh
Construct a sphere from an icosahedron and refine each triangle by projecting edge midpoints onto the sphere. The continuous reference is known, so error can be measured without confusing it with a second approximate method. The OBJ reader accepts vertices and positive triangular faces; it explicitly fails on polygons or relative indices instead of misinterpreting them.
import numpy as np
from scipy.spatial import ConvexHull
from scipy.sparse import coo_matrix, diags
from scipy.sparse.linalg import eigsh, spsolve
from scipy.sparse.csgraph import dijkstra
def read_obj(text):
V, F = [], []
for line in text.splitlines():
p = line.split('#', 1)[0].split()
if not p:
continue
if p[0] == 'v':
V.append([float(x) for x in p[1:4]])
elif p[0] == 'f':
if len(p) != 4:
raise ValueError('Se necesitan caras triangulares')
face = [int(x.split('/')[0]) for x in p[1:]]
if min(face) <= 0:
raise ValueError('Solo índices OBJ positivos')
F.append([x - 1 for x in face])
return np.asarray(V, float), np.asarray(F, int)
def sphere_mesh(level=0):
g = (1 + np.sqrt(5)) / 2
V = np.array([(0, a, b*g) for a in (-1, 1) for b in (-1, 1)]
+ [(a, b*g, 0) for a in (-1, 1) for b in (-1, 1)]
+ [(b*g, 0, a) for a in (-1, 1) for b in (-1, 1)], float)
V /= np.linalg.norm(V, axis=1)[:, None]
F = ConvexHull(V).simplices
for _ in range(level):
verts, cache, faces = list(V), {}, []
def mid(i, j):
key = tuple(sorted((int(i), int(j))))
if key not in cache:
p = (V[i] + V[j]) / 2
p /= np.linalg.norm(p)
cache[key] = len(verts)
verts.append(p)
return cache[key]
for i, j, k in F:
a, b, c = mid(i, j), mid(j, k), mid(k, i)
faces.extend([(i, a, c), (j, b, a), (k, c, b), (a, b, c)])
V, F = np.asarray(verts), np.asarray(faces)
# Orientación coherente hacia fuera.
for face in F:
i, j, k = face
if np.dot(np.cross(V[j]-V[i], V[k]-V[i]), V[i]) < 0:
face[1], face[2] = face[2], face[1]
return V, F
V0, F0 = sphere_mesh()
obj = '\n'.join(['v ' + ' '.join(map(str, v)) for v in V0]
+ ['f ' + ' '.join(str(i+1) for i in f) for f in F0])
Vr, Fr = read_obj(obj)
print('OBJ:', np.allclose(Vr, V0), np.array_equal(Fr, F0))To avoid poorly conditioned inverse angles, compute cotangents as dot product divided by cross-product norm. Local energy is summed edge by edge; negative weights are not clamped to zero.
def geometry(V, F):
n = len(V)
mass = np.zeros(n)
normals = np.zeros_like(V)
angle_sum = np.zeros(n)
rows, cols, vals = [], [], []
areas, grads = [], []
for face in F:
a, b, c = V[face]
cross = np.cross(b-a, c-a)
twice = np.linalg.norm(cross)
if twice < 1e-14:
raise ValueError('Triángulo degenerado')
normal = cross / twice
area = twice / 2
areas.append(area)
grads.append(np.array([np.cross(normal, c-b), np.cross(normal, a-c),
np.cross(normal, b-a)]) / twice)
for local in range(3):
i, j, k = face[local], face[(local+1)%3], face[(local+2)%3]
u, v = V[j]-V[i], V[k]-V[i]
angle_sum[i] += np.arctan2(np.linalg.norm(np.cross(u, v)), np.dot(u, v))
mass[i] += area / 3
normals[i] += cross
w = np.dot(u, v) / (2 * twice)
rows.extend([j, k, j, k]); cols.extend([j, k, k, j])
vals.extend([w, w, -w, -w])
L = coo_matrix((vals, (rows, cols)), shape=(n, n)).tocsr()
lengths = np.linalg.norm(normals, axis=1)
if np.any(lengths < 1e-14):
raise ValueError('Normal de vértice indefinida')
return L, diags(mass).tocsr(), 2*np.pi-angle_sum, normals/lengths[:, None], np.array(areas), np.array(grads)
L0, M0, K0, N0, _, _ = geometry(V0, F0)
print('defecto/pi:', np.round(K0 / np.pi, 8))
print('Gauss-Bonnet / 4pi:', K0.sum() / (4*np.pi))
print('L simétrica y L1=0:', np.allclose(L0.toarray(), L0.toarray().T),
np.allclose(L0 @ np.ones(len(V0)), 0))The geometry implementation assumes all vertices are interior when computing defect. For a surface with boundary replace by at boundary vertices; stiffness and mass do not need that change. We compare spectra of two refinements and calculate HKS using mass-normalized modes.
For curvature density you can also use mixed Voronoi area of Meyer and colleagues. In an obtuse triangle assign half to the obtuse vertex and a quarter to each other; in a nonobtuse triangle use the circumcentric region. Areas must sum to total area on both an acute mesh and an obtuse triangle.
def mixed_voronoi_area(V, F):
out = np.zeros(len(V))
for face in F:
p = V[face]
twice = np.linalg.norm(np.cross(p[1]-p[0], p[2]-p[0]))
if twice < 1e-14:
raise ValueError('Triángulo degenerado')
dots = np.array([np.dot(p[(i+1)%3]-p[i], p[(i+2)%3]-p[i]) for i in range(3)])
area = twice/2
if dots.min() < 0:
obtuse = int(np.argmin(dots))
weights = np.full(3, area/4)
weights[obtuse] = area/2
else:
cot = dots/twice
weights = np.array([(np.sum((p[(i+1)%3]-p[i])**2)*cot[(i+2)%3]
+ np.sum((p[(i+2)%3]-p[i])**2)*cot[(i+1)%3])/8
for i in range(3)])
np.add.at(out, face, weights)
return out
V, F = sphere_mesh(1)
mixed = mixed_voronoi_area(V, F)
_, _, _, _, face_area, _ = geometry(V, F)
print('área mixta y área total:', mixed.sum(), face_area.sum())
obtuse = np.array([[0.,0.,0.],[2.,0.,0.],[0.3,0.2,0.]])
print('reparto obtuso:', mixed_voronoi_area(obtuse, np.array([[0,1,2]])))for level in (0, 1, 2):
V, F = sphere_mesh(level)
L, M, K, N, areas, grads = geometry(V, F)
lam, phi = eigsh(L, k=9, M=M, sigma=-1e-6, which='LM', v0=np.ones(len(V)))
order = np.argsort(lam)
lam, phi = lam[order], phi[:, order]
hks = (phi**2) @ np.exp(-0.5 * lam)
print('nivel', level, 'vértices', len(V), 'autovalores', np.round(lam[:5], 4),
'HKS intervalo', np.round([hks.min(), hks.max()], 4))The Poisson solve uses weak product , avoiding an invented per-vertex divergence. The source is fixed at zero to remove the constant null mode. Source value is also subtracted afterward for clarity. dijkstra operates on an edge-length matrix without duplicates.
def heat_distance(V, F, source, factor=1.0):
L, M, _, _, areas, grads = geometry(V, F)
edges = sorted({tuple(sorted((int(face[i]), int(face[(i+1)%3]))))
for face in F for i in range(3)})
lens = np.array([np.linalg.norm(V[i]-V[j]) for i, j in edges])
t = factor * np.mean(lens)**2
u0 = np.zeros(len(V)); u0[source] = 1
u = spsolve(M + t*L, M @ u0)
grad_u = np.einsum('fi,fij->fj', u[F], grads)
norm = np.linalg.norm(grad_u, axis=1)
X = -grad_u / np.maximum(norm[:, None], 1e-15)
rhs = np.zeros(len(V))
np.add.at(rhs, F.ravel(), (areas[:, None] * np.einsum('fij,fj->fi', grads, X)).ravel())
keep = np.arange(len(V)) != source
dist = np.zeros(len(V))
dist[keep] = spsolve(L[keep][:, keep], rhs[keep])
ii, jj = np.array(edges).T
graph = coo_matrix((np.r_[lens, lens], (np.r_[ii, jj], np.r_[jj, ii])),
shape=L.shape).tocsr()
return dist, dijkstra(graph, indices=source), t
V, F = sphere_mesh(2)
exact = np.arccos(np.clip(V @ V[0], -1, 1))
for factor in (0.25, 1.0, 4.0):
heat, edge, t = heat_distance(V, F, 0, factor)
print('factor', factor, 't', round(t, 5),
'MAE calor', round(np.mean(np.abs(heat-exact)), 5),
'MAE aristas', round(np.mean(np.abs(edge-exact)), 5))The polyhedral sphere is not exactly the smooth sphere. Comparison therefore mixes representation and method error, and edge distance need not improve at the same rate as distance through faces. To compare implementations locally install potpourri3d, run preceding cell definitions there and compare the same mesh:
import potpourri3d as pp3d
V, F = sphere_mesh(2)
propia, _, _ = heat_distance(V, F, 0, 1.0)
referencia = pp3d.MeshHeatMethodDistanceSolver(V, F).compute_distance(0)
exacta = np.arccos(np.clip(V @ V[0], -1, 1))
print('Error medio propio:', np.mean(np.abs(propia - exacta)))
print('Error medio potpourri3d:', np.mean(np.abs(referencia - exacta)))
print('Discrepancia media:', np.mean(np.abs(propia - referencia)))
In a local run with potpourri3d 1.4.0 and the same 162-vertex mesh, mean errors were approximately 0.045048 and 0.045052 respectively, and mean discrepancy 0.00000404. These are not independent references for the smooth geodesic: both algorithms work on the same polyhedral mesh and the analytic reference is the sphere. Library internals may change with version.
Human-body segmentation and remeshing
This lab’s dataset comes from the remeshed HumanBody version of SubdivNet. The selection contains 32 training FAUST and 8 test SHREC meshes with facewise part labels. These are distinct meshes, not necessarily 32 distinct people; original data conditions still apply. Selection and hashes are in human_manifest.json.
Also download fetch_human.py and human_seg.py. The first program extracts OBJ and JSON pairs by ranges from the published archive and verifies CRC and SHA-256. The second simplifies each mesh and transfers labels from the original face with the nearest center. This transfer is approximate near part boundaries; do not confuse its error with the network’s. It then converts face labels to vertices by area-weighted voting.
Training uses meshes simplified to about 256 faces and evaluates the same test shapes at about 256 and 1024 faces. The simplified intrinsic network combines heat signatures, spectral diffusion with learnable times and gradient magnitudes; the baseline uses uniform neighbor means with the same inputs. Area-weighted accuracy and mIoU are measured. This is not the full DiffusionNet implementation, and both resolutions simplify an already remeshed mesh, not two independent acquisitions.
Install PyTorch, NumPy, SciPy, trimesh, fast-simplification and potpourri3d locally. Put the three downloadable files together and run:
python fetch_human.py --out datos_humanos
python human_seg.py --data datos_humanos
In a run with 35 epochs, 32 training shapes and 8 test shapes, the intrinsic network obtained area-weighted accuracy/mIoU 0.8307/0.6935 at 256 faces and 0.8477/0.7288 at 1024. The uniform network obtained 0.7224/0.5320 and 0.6880/0.5354. These figures are for this subset and one seed: higher resolution also changes approximate label transfer, whose contribution was not separated. The observed difference does not show superiority on every mesh or the full dataset.
Exercises
Step 1 of 3. Which curve satisfies the initial conditions?
Step 1 of 3. What are hat-function gradients on a face?
cotan_laplacian(V, F) for a nondegenerate triangular mesh. Return positive stiffness L and lumped barycentric mass M, both SciPy sparse matrices. Each angle contributes half its cotangent to the opposite edge weight.import numpy as np
from scipy.sparse import coo_matrix, diags
def cotan_laplacian(V, F):
pass