Algorithm Search⌘K

Algorithmadvanced

Harmonic coordinates

Also called harmonic cage coordinates.

Cage coordinates that solve Laplace's equation inside the cage on a grid; they are nonnegative and decay with distance inside the cage, even for concave cages.

Time
O(G^4 + n G^3 + N n) allO(n) per_pointO(G^4 + n G^3) precompute
Space
O(G^3 + n G^2) extra
Where
G = the number of grid cells across the cage; N = the number of points to deform; n = the number of cage vertices
Properties
deterministicnot exactofflineiterative

Harmonic coordinates are the weights of a cage-based deformation that come from the Laplace equation. The coordinate hih_i of cage vertex ii is the harmonic function inside the cage that equals 1 at vertex ii, 0 at the other vertices, and is linear along each cage edge. A point pp then moves to ∑ihi(p)ci′\sum_i h_i(p)c'_i, where ci′c'_i are the moved cage vertices. Pushkar Joshi, Mark Meyer, Tony DeRose, Brian Green and Tom Sanocki (2007) introduced them at Pixar for posing characters with cages. Unlike mean value coordinates, harmonic coordinates are never negative, so a vertex on the far side of a concave part of the cage cannot pull a point the wrong way. They have no closed form; this page computes them in 2D with a finite difference solve on a grid.

In plain words

Think of the cage as a wire frame that holds a flat sheet of soap film. Lift one corner of the frame to height 1 and keep the other corners at 0, with the wire straight between corners. The film takes the smoothest shape that the frame allows, and its height at a point is the coordinate of that corner at the point. The film never dips below the lowest wire, so the height is never negative. It also cannot see through walls: around a sharp inner corner of the frame, the film has to go around it. Do this once for each corner, and each point of the shape has one weight per corner, which add up to 1.

The problem

The input is a cage, a simple polygon with the vertices c1,…,cnc_1, \dots, c_n in counterclockwise order, and the grid spacing δ\delta. On the boundary of the cage, the hat function ϕi\phi_i of vertex ii is 1 at cic_i, 0 at every other vertex, and linear on each edge. The harmonic coordinate hih_i is the solution of

Δhi=0 inside the cage,hi=ϕi on the boundary.\Delta h_i = 0 \text{ inside the cage}, \qquad h_i = \phi_i \text{ on the boundary}.

The output is a discrete hih_i at the nodes of a grid with the spacing δ\delta, and then hi(p)h_i(p) at any point pp inside the cage, for the deformation p↦∑ihi(p)ci′p \mapsto \sum_i h_i(p)c'_i.

The algorithm

Each interior node has four arms to its neighbours. An arm that leaves the cage is cut at its first crossing with the boundary, so its length ℓ\ell is at most δ\delta; this is the Shortley-Weller stencil.

  1. HARMONIC(cage, δ)
  2. 1U ← the grid nodes strictly inside the cage
  3. 2for each node p in U, cut each arm of p at its first crossing with the cage, giving the length ℓ ≤ δ
  4. 3give the arm of length ℓ, opposite an arm of length ℓ', the weight a = 2 / (ℓ(ℓ + ℓ'))
  5. 4if the arm ends on the cage at q then add a φ_i(q) to b_i[p] for each i, else put -a in the row of p of A
  6. 5factor A = LU, with the diagonal of A equal to the sum of the weights of the arms of each node
  7. 6for each vertex i, solve A x_i = b_i
  8. 7h_i(p) ← x_i[p] for every p in U
  9. DEFORM(p, c')
  10. 8return Σ_i h_i(p) c'_i, with h_i(p) by bilinear interpolation of the nodes

Lines L2 to L4 discretize ∂2h/∂x2+∂2h/∂y2\partial^2 h/\partial x^2 + \partial^2 h/\partial y^2 at each node with the uneven three-point formula in each direction. Line L5 factors the matrix once; it is banded, with a band of width about GG when the nodes are numbered row by row, and it needs no pivoting because it is an M-matrix. For line L8, a grid node outside the cage takes the boundary data at its nearest boundary point. The paper of Joshi and others also uses a grid; the details of its solver are not repeated here.

Example

The cage is the L shape with the vertices (0,0)(0, 0), (2,0)(2, 0), (2,1)(2, 1), (1,1)(1, 1), (1,2)(1, 2), (0,2)(0, 2); the vertex (1,1)(1, 1) is the inner, reflex corner. The grid has G=16G = 16 cells across the cage, so δ=0.125\delta = 0.125, with 161 interior nodes. At the node p=(0.875,1.375)p = (0.875, 1.375) in the upper arm of the L, the six harmonic coordinates are about

h(p)=(0.0479, 0.0072, 0.0031, 0.5117, 0.3426, 0.0875).h(p) = (0.0479,\ 0.0072,\ 0.0031,\ 0.5117,\ 0.3426,\ 0.0875).

The vertex (2,1)(2, 1) is hidden from pp behind the reflex corner: the segment from pp to it leaves the cage. Its harmonic coordinate is small and positive, 0.00310.0031. The mean value coordinates at the same point are about (0.0598,0.0312,−0.0097,0.4527,0.3793,0.0867)(0.0598, 0.0312, -0.0097, 0.4527, 0.3793, 0.0867), with a negative weight for that vertex. So if the user drags (2,1)(2, 1) to the right, the mean value deformation moves pp to the left, against the drag, while the harmonic deformation moves it a little to the right. The tests check these values, the nonnegativity at all nodes, the sum 1, the exact reproduction of linear functions at the nodes, and that the coordinate of (1,1)(1, 1) peaks close to (1,1)(1, 1).

Correctness

The claims here are about the discrete coordinates, and the proof proves them.

  • The constant 1 solves the discrete problem with the data ∑iϕi=1\sum_i \phi_i = 1, and the solution is unique, so ∑ihi=1\sum_i h_i = 1 at every node.
  • The Shortley-Weller formula is exact on quadratic polynomials, so a linear function gg satisfies the discrete equation with its own boundary values. The data ∑iϕici\sum_i \phi_i c_i is the identity on the boundary, because each ϕi\phi_i is linear on edges. So ∑ihi(p)ci=p\sum_i h_i(p)c_i = p at every node: linear precision.
  • The matrix AA has a positive diagonal, nonpositive entries off it, row sums at least 0, and a strictly dominant row in every connected set of nodes. So it is a nonsingular M-matrix with A−1≥0A^{-1} \ge 0. The right sides bib_i are nonnegative, so hi≥0h_i \ge 0: a discrete maximum principle.
  • Bilinear interpolation in L8 keeps the sum 1 and the nonnegativity, and keeps linear precision in cells whose four nodes are interior.

For the continuous problem, the strong maximum principle gives 0<hi<10 < h_i < 1 strictly inside the cage when the cage has at least three vertices, and hih_i is smooth inside. The coordinates are not local in the strict sense: each hih_i is positive everywhere inside. They do decay with the distance from vertex ii measured inside the cage, which the test of the peak measures for one cage; this decay is an observed property, not a bound proved here.

Proof: The discrete harmonic coordinates exist, are unique and nonnegative, sum to 1, and reproduce linear functions at the grid nodesfull

We use the notation of the page. For a node p∈Up \in U and one axis, let the two arms along that axis have the lengths ℓ−\ell_- and ℓ+\ell_+, at most δ\delta, and end at the points q−q_- and q+q_+. An end is either a node of UU, with the unknown value there, or a point on the cage, with the value of the boundary data there. The arm weights are a±=2/(ℓ±(ℓ−+ℓ+))a_\pm = 2/(\ell_\pm(\ell_- + \ell_+)), and the discrete Laplacian at pp is

(Lu)(p)=∑both axesa−(u(q−)−u(p))+a+(u(q+)−u(p)).(L u)(p) = \sum_{\text{both axes}} a_-(u(q_-) - u(p)) + a_+(u(q_+) - u(p)).

The system Ax=biAx = b_i of lines L4 to L6 is (Lu)(p)=0(Lu)(p) = 0 for every p∈Up \in U, with the boundary data ϕi\phi_i, after the known boundary values are moved to the right side. We assume that every arm whose neighbour node is not in UU ends at a crossing with the cage. The implementation has a fallback for rounding cases where the crossing is not found, and there the exactness claims hold only up to the rounding.

Exactness on quadratics

Lemma 1. For every polynomial g(t)=α+βt+γt2g(t) = \alpha + \beta t + \gamma t^2 and all ℓ−,ℓ+>0\ell_-, \ell_+ > 0: a−(g(−ℓ−)−g(0))+a+(g(ℓ+)−g(0))=2γ=g′′a_-(g(-\ell_-) - g(0)) + a_+(g(\ell_+) - g(0)) = 2\gamma = g''.

Proof. The left side is a−(−βℓ−+γℓ−2)+a+(βℓ++γℓ+2)=2ℓ−+ℓ+(−β+γℓ−+β+γℓ+)=2γa_-(-\beta\ell_- + \gamma\ell_-^2) + a_+(\beta\ell_+ + \gamma\ell_+^2) = \frac{2}{\ell_- + \ell_+}(-\beta + \gamma\ell_- + \beta + \gamma\ell_+) = 2\gamma. □\square

So if g(x,y)g(x, y) is a polynomial whose restriction to each horizontal and each vertical line has degree at most 2, Lg=∂2g/∂x2+∂2g/∂y2Lg = \partial^2g/\partial x^2 + \partial^2g/\partial y^2 exactly at every node. This holds for 11, xx, yy, xyxy, x2x^2 and y2y^2.

A discrete maximum principle

Lemma 2. Every connected set of nodes of UU, where two nodes are joined when an arm of one ends at the other, contains a node with an arm that ends on the cage.

Proof. Take the node pp of the set with the largest xx, and among those the largest yy. Its right arm cannot end at a node of UU, because that node is joined to pp and has a larger xx. So it ends on the cage. □\square

Lemma 3. If Lu=0Lu = 0 on UU with boundary data ≥0\ge 0, then u≥0u \ge 0 on UU. If the boundary data are 0, then u=0u = 0.

Proof. Let m=min⁡Uum = \min_U u and assume m<0m < 0, with m=u(p)m = u(p). (Lu)(p)=0(Lu)(p) = 0 says that u(p)u(p) is the weighted mean, with the positive weights aa, of the values at the ends of its four arms. Each end value is ≥m\ge m: a node value by the choice of mm, a boundary value because it is ≥0>m\ge 0 > m. So all end values equal mm; in particular no arm of pp ends on the cage, and every neighbour node in UU also has the value mm. Repeating the argument, every node of the connected set of pp has the value mm and no arm on the cage, which Lemma 2 forbids. So u≥0u \ge 0. With the data 0, the same argument applied to uu and to −u-u gives u≥0u \ge 0 and u≤0u \le 0. □\square

Theorem 1. The matrix AA is nonsingular, so each hih_i exists and is unique, and hi≥0h_i \ge 0 at every node.

Proof. If Ax=0Ax = 0, then xx solves Lu=0Lu = 0 with the data 0, so x=0x = 0 by Lemma 3. The data ϕi\phi_i are ≥0\ge 0, so hi≥0h_i \ge 0 by Lemma 3. □\square

This is the M-matrix property: AA has a positive diagonal, nonpositive entries off it and A−1≥0A^{-1} \ge 0. It is also why the LU factorization without pivoting of line L5 is stable: the Schur complements of a nonsingular M-matrix are M-matrices, so every pivot is positive.

Partition of unity and linear precision

Lemma 4. On the cage boundary, ∑iϕi=1\sum_i \phi_i = 1 and ∑iϕi(q)ci=q\sum_i \phi_i(q)c_i = q.

Proof. A point qq on the edge from ckc_k to ck+1c_{k+1} at the fraction ss has ϕk(q)=1−s\phi_k(q) = 1 - s, ϕk+1(q)=s\phi_{k+1}(q) = s and ϕi(q)=0\phi_i(q) = 0 otherwise. So the sum is 1, and ∑iϕi(q)ci=(1−s)ck+sck+1=q\sum_i \phi_i(q)c_i = (1 - s)c_k + sc_{k+1} = q. □\square

Theorem 2. At every node p∈Up \in U: ∑ihi(p)=1\sum_i h_i(p) = 1 and ∑ihi(p)ci=p\sum_i h_i(p)c_i = p.

Proof. The system is linear in the data, so u=∑ihiu = \sum_i h_i solves Lu=0Lu = 0 with the data ∑iϕi=1\sum_i \phi_i = 1, and v=∑ihici,xv = \sum_i h_i c_{i,x} solves it with the data ∑iϕici,x\sum_i \phi_i c_{i,x}, which is the xx coordinate of the boundary point by Lemma 4. LL applied to the constant 1 or to the coordinate function xx gives 0 exactly, by Lemma 1, and these functions have the same boundary values. By Theorem 1 the solution is unique, so u=1u = 1 and v=xv = x; the same holds for yy. □\square

Theorem 3. If the cage is an axis-aligned rectangle with the corners as its four vertices, the discrete hih_i at every node equal the bilinear coordinates of the rectangle.

Proof. Each bilinear coordinate, such as (1−x/w)(1−y/v)(1 - x/w)(1 - y/v) for the rectangle [0,w]×[0,v][0, w] \times [0, v], is linear on each edge and equals 1 at its corner and 0 at the others, so it agrees with ϕi\phi_i on the boundary. On each horizontal or vertical line it is linear, so LL of it is 0 by Lemma 1. By uniqueness it is the discrete solution. □\square

Evaluation between nodes

Line L8 interpolates the four corner nodes of the grid cell that holds pp with the bilinear weights, which are ≥0\ge 0 and sum to 1. A corner outside UU takes ϕ(q∗)\phi(q^*) at its nearest boundary point q∗q^*, which is ≥0\ge 0 and sums to 1 by Lemma 4. So ∑ihi(p)=1\sum_i h_i(p) = 1 and hi(p)≥0h_i(p) \ge 0 at every point. If all four corners are in UU, bilinear interpolation of the nodal values of a linear function gives that function, so ∑ihi(p)ci=p\sum_i h_i(p)c_i = p. If a corner zz is not in UU, its value reproduces q∗q^* instead of zz; the segment from zz to pp crosses the cage and has the length at most 2 δ\sqrt2\,\delta, so ∣q∗−z∣≤2 δ|q^* - z| \le \sqrt2\,\delta, and ∣∑ihi(p)ci−p∣≤2 δ|\sum_i h_i(p)c_i - p| \le \sqrt2\,\delta.

The continuous coordinates

For the exact hih_i of the Laplace equation, the weak maximum principle gives 0≤hi≤10 \le h_i \le 1, and the strong maximum principle gives 0<hi<10 < h_i < 1 inside when ϕi\phi_i is not constant, which holds for a cage with at least three vertices. These are standard facts about harmonic functions and are not proved here.

Complexity

Let GG be the number of cells across the cage, so there are O(G2)O(G^2) unknowns. Lines L1 to L4 test each node against the cage and cut each arm in O(n)O(n) time, so they cost O(nG2)O(nG^2). The band LU of line L5 has a band of width O(G)O(G), so it costs O(G4)O(G^4) time and O(G3)O(G^3) memory; each solve of line L6 costs O(G3)O(G^3), and there are nn of them. The values take O(nG2)O(nG^2) memory. One evaluation of line L8 reads four nodes with nn values each, plus a nearest boundary point in O(n)O(n) for outside nodes, so it costs O(n)O(n). A multigrid or conjugate gradient solver makes the precomputation close to linear in the number of unknowns; the band LU is used here because it is short and exact up to rounding.

Properties

  • Partition of unity (proved). ∑ihi=1\sum_i h_i = 1, so a translation of the cage translates the shape.
  • Linear precision (proved, at the nodes). ∑ihi(p)ci=p\sum_i h_i(p)c_i = p at every node, so the rest cage gives the identity there. Between nodes near the boundary, the bilinear interpolation leaves an error of order δ\delta.
  • Nonnegative (proved). hi≥0h_i \ge 0 at every node, for every simple cage, convex or not.
  • Interpolation on the boundary (by definition). On the cage boundary hi=ϕih_i = \phi_i, so the cage edges map linearly onto the moved cage edges.
  • Bilinear on rectangles (proved). On an axis-aligned rectangle the discrete coordinates are exactly the bilinear coordinates, because bilinear functions are harmonic and the stencil is exact on them.
  • Decay inside the cage (measurement). The coordinate of a vertex is largest near the vertex and small at points that are far from it along paths inside the cage.
  • Discretization error (known, not proved here). The Shortley-Weller scheme converges with order δ2\delta^2 for smooth solutions; at reflex corners the exact hih_i is not smooth, and the convergence there is slower.

Variants and improvements

When to use it

Use harmonic coordinates when the cage is concave, for example a cage around the legs or fingers of a character, and mean value coordinates would let one part pull on another across a gap. The precomputation is heavy but runs once per cage, and after it each point has fixed weights, so posing is as cheap as for any cage. If the cage is convex or nearly so, or if the weights must have a closed form, mean value coordinates are simpler.

Pitfalls

  • Grid too coarse. Thin parts of the cage that are narrower than the grid spacing have no interior nodes and get only boundary data; choose δ\delta well below the smallest feature.
  • Nodes on the boundary. A node that lies on the cage within rounding must be treated as a boundary node, or the cut arm has length near 0 and the weight aa blows up.
  • Outside points. The coordinates are defined only inside the cage. Points of the shape that stick out need a cage that encloses them.
  • Linear precision between nodes. Near the boundary, the interpolated coordinates reproduce linear functions only up to order δ\delta, so the rest cage moves such points a little.
  • Storage. One value per node per vertex is a lot in 3D; store only the coordinates at the points of the shape after the solve.

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.

harmonic_coordinates.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/harmonic-coordinates/. The authors are listed in prov/XS2ZCM.jsonl.
"""Harmonic coordinates of a 2D cage (Joshi, Meyer, DeRose, Green and Sanocki 2007).

The coordinate h_i of cage vertex i is the solution of the Laplace equation
inside the cage, with the boundary value equal to the piecewise linear hat
function of vertex i on the cage boundary. This module solves the equation
on a uniform grid with the Shortley-Weller five-point stencil: an arm of
the stencil that leaves the cage is cut at the first boundary crossing, and
the stencil weights use the shorter arm length. The stencil is exact on
quadratic functions, so the discrete coordinates reproduce linear
functions exactly at the grid nodes. The matrix is an M-matrix, so the
coordinates are nonnegative and the LU factorization needs no pivoting.

The cage is a simple polygon with the vertices in counterclockwise order.
"""

import math


def _cross(ax, ay, bx, by):
    return ax * by - ay * bx


def point_in_polygon(p, poly):
    """Even-odd rule. The result on the boundary is not defined; callers test that first."""
    x, y = p
    inside = False
    n = len(poly)
    for i in range(n):
        (x1, y1), (x2, y2) = poly[i], poly[(i + 1) % n]
        if (y1 > y) != (y2 > y):
            xc = x1 + (y - y1) * (x2 - x1) / (y2 - y1)
            if xc > x:
                inside = not inside
    return inside


def nearest_on_boundary(p, poly):
    """Return (distance, edge index, s) of the boundary point closest to p."""
    best = (math.inf, 0, 0.0)
    n = len(poly)
    for k in range(n):
        (ax, ay), (bx, by) = poly[k], poly[(k + 1) % n]
        dx, dy = bx - ax, by - ay
        dd = dx * dx + dy * dy
        s = min(1.0, max(0.0, ((p[0] - ax) * dx + (p[1] - ay) * dy) / dd))
        d = math.hypot(p[0] - ax - s * dx, p[1] - ay - s * dy)
        if d < best[0]:
            best = (d, k, s)
    return best


def hat_values(poly, k, s):
    """Return the boundary data of all n coordinates at the point with parameter s on edge k."""
    n = len(poly)
    out = [0.0] * n
    out[k] += 1.0 - s
    out[(k + 1) % n] += s
    return out


def first_crossing(p, q, poly, eps=1e-12):
    """Return (t, edge index, s) of the first crossing of the segment p + t (q - p), t in (0, 1].

    Edges parallel to the segment are skipped; their end points are found
    through the neighbouring edges. Return None if there is no crossing.
    """
    best = None
    n = len(poly)
    rx, ry = q[0] - p[0], q[1] - p[1]
    for k in range(n):
        (ax, ay), (bx, by) = poly[k], poly[(k + 1) % n]
        ex, ey = bx - ax, by - ay
        den = _cross(rx, ry, ex, ey)
        if abs(den) < eps * (abs(rx) + abs(ry)) * (abs(ex) + abs(ey)):
            continue
        wx, wy = ax - p[0], ay - p[1]
        t = _cross(wx, wy, ex, ey) / den
        s = _cross(wx, wy, rx, ry) / den
        if -eps <= s <= 1 + eps and eps < t <= 1 + eps:
            if best is None or t < best[0]:
                best = (min(t, 1.0), k, min(1.0, max(0.0, s)))
    return best


class BandLU:
    """LU factorization without pivoting of a band matrix, for M-matrices.

    The matrix is given as rows of {column: value}. Fill-in stays inside
    the band, so the cost is O(N p q) for the factorization and O(N (p + q))
    for each solve.
    """

    def __init__(self, rows):
        self.n = n = len(rows)
        p = q = 0
        for i, row in enumerate(rows):
            for j in row:
                p = max(p, i - j)
                q = max(q, j - i)
        self.p, self.q = p, q
        width = p + q + 1
        band = [[0.0] * width for _ in range(n)]
        for i, row in enumerate(rows):
            for j, v in row.items():
                band[i][j - i + p] += v
        for k in range(n):
            piv = band[k][p]
            if piv <= 0:
                raise ValueError("a pivot is not positive; the matrix is not an M-matrix")
            for i in range(k + 1, min(n, k + p + 1)):
                lik = band[i][k - i + p]
                if lik == 0:
                    continue
                lik /= piv
                band[i][k - i + p] = lik
                ri, rk = band[i], band[k]
                for j in range(k + 1, min(n, k + q + 1)):
                    ukj = rk[j - k + p]
                    if ukj != 0:
                        ri[j - i + p] -= lik * ukj
        self.band = band

    def solve(self, b):
        n, p, q, band = self.n, self.p, self.q, self.band
        y = list(b)
        for i in range(n):
            s = y[i]
            for k in range(max(0, i - p), i):
                s -= band[i][k - i + p] * y[k]
            y[i] = s
        for i in range(n - 1, -1, -1):
            s = y[i]
            for j in range(i + 1, min(n, i + q + 1)):
                s -= band[i][j - i + p] * y[j]
            y[i] = s / band[i][p]
        return y


class HarmonicCoordinates:
    """Discrete harmonic coordinates of a 2D cage on a grid with n_cells cells across."""

    def __init__(self, cage, n_cells=32, on_boundary=1e-9):
        self.cage = [tuple(map(float, c)) for c in cage]
        n = len(self.cage)
        xs = [c[0] for c in self.cage]
        ys = [c[1] for c in self.cage]
        size = max(max(xs) - min(xs), max(ys) - min(ys))
        self.h = h = size / n_cells
        self.x0, self.y0 = min(xs) - h, min(ys) - h
        self.nx = int(math.ceil((max(xs) - self.x0) / h)) + 2
        self.ny = int(math.ceil((max(ys) - self.y0) / h)) + 2
        tol = on_boundary * size

        # L1: the nodes strictly inside the cage are the unknowns.
        self.index = {}
        for j in range(self.ny):  # @line L1
            for i in range(self.nx):
                p = self.node(i, j)
                if nearest_on_boundary(p, self.cage)[0] > tol and point_in_polygon(p, self.cage):
                    self.index[(i, j)] = len(self.index)

        rows, rhs = [], []
        for (i, j), r in sorted(self.index.items(), key=lambda kv: kv[1]):
            p = self.node(i, j)
            row, b = {}, [0.0] * n
            diag = 0.0
            arms = {}
            for di, dj in ((-1, 0), (1, 0), (0, -1), (0, 1)):
                q = self.node(i + di, j + dj)
                hit = first_crossing(p, q, self.cage)  # @line L2
                if hit is not None and (hit[0] < 1.0 or (i + di, j + dj) not in self.index):
                    t, k, s = hit
                    arms[(di, dj)] = (t * h, hat_values(self.cage, k, s))
                elif (i + di, j + dj) in self.index:
                    arms[(di, dj)] = (h, self.index[(i + di, j + dj)])
                else:
                    d, k, s = nearest_on_boundary(q, self.cage)
                    arms[(di, dj)] = (h, hat_values(self.cage, k, s))
            for lo, hi in (((-1, 0), (1, 0)), ((0, -1), (0, 1))):
                hl, hr = arms[lo][0], arms[hi][0]
                for arm, length in ((arms[lo], hl), (arms[hi], hr)):
                    a = 2.0 / (length * (hl + hr))  # @line L3
                    diag += a
                    target = arm[1]
                    if isinstance(target, int):
                        row[target] = row.get(target, 0.0) - a
                    else:
                        for v in range(n):
                            b[v] += a * target[v]  # @line L4
            row[r] = diag
            rows.append(row)
            rhs.append(b)
        self.rows, self.rhs = rows, rhs

        lu = BandLU(rows)  # @line L5
        cols = []
        for v in range(n):
            cols.append(lu.solve([b[v] for b in rhs]))  # @line L6
        self.values = [[cols[v][r] for v in range(n)] for r in range(len(rows))]  # @line L7

    def node(self, i, j):
        return (self.x0 + i * self.h, self.y0 + j * self.h)

    def node_coordinates(self, i, j):
        """Return the n coordinates at grid node (i, j).

        Nodes outside the cage or on its boundary take the boundary data at
        the closest boundary point.
        """
        r = self.index.get((i, j))
        if r is not None:
            return list(self.values[r])
        _, k, s = nearest_on_boundary(self.node(i, j), self.cage)
        return hat_values(self.cage, k, s)

    def coordinates(self, p):
        """Return the n coordinates at the point p by bilinear interpolation of the nodes."""
        fx = (p[0] - self.x0) / self.h
        fy = (p[1] - self.y0) / self.h
        i = min(max(int(math.floor(fx)), 0), self.nx - 2)
        j = min(max(int(math.floor(fy)), 0), self.ny - 2)
        a, b = fx - i, fy - j
        out = [0.0] * len(self.cage)
        for di, dj, w in ((0, 0, (1 - a) * (1 - b)), (1, 0, a * (1 - b)), (0, 1, (1 - a) * b), (1, 1, a * b)):
            if w != 0:
                for v, c in enumerate(self.node_coordinates(i + di, j + dj)):
                    out[v] += w * c
        return out

    def deform(self, p, new_cage):
        """Return sum_i h_i(p) c'_i."""
        w = self.coordinates(p)
        return (sum(wi * c[0] for wi, c in zip(w, new_cage)), sum(wi * c[1] for wi, c in zip(w, new_cage)))  # @line L8


def gauss_seidel(rows, b, iters=5000, tol=1e-13):
    """Solve the same system by Gauss-Seidel iteration. Used by the tests as a second method."""
    n = len(rows)
    x = [0.0] * n
    for _ in range(iters):
        change = 0.0
        for i, row in enumerate(rows):
            s = b[i]
            for j, v in row.items():
                if j != i:
                    s -= v * x[j]
            new = s / row[i]
            change = max(change, abs(new - x[i]))
            x[i] = new
        if change < tol:
            break
    return x
test_harmonic_coordinates.py 135 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/harmonic-coordinates/. The authors are listed in prov/XS2ZCM.jsonl.
import math
import random

from harmonic_coordinates import BandLU, HarmonicCoordinates, gauss_seidel, point_in_polygon

L_SHAPE = [(0, 0), (2, 0), (2, 1), (1, 1), (1, 2), (0, 2)]
RECT = [(0, 0), (3, 0), (3, 2), (0, 2)]
STAR = [(math.cos(2 * math.pi * k / 10) * (1.0 if k % 2 == 0 else 0.45), math.sin(2 * math.pi * k / 10) * (1.0 if k % 2 == 0 else 0.45)) for k in range(10)]

_CACHE = {}


def hc(cage, n_cells):
    key = (tuple(cage), n_cells)
    if key not in _CACHE:
        _CACHE[key] = HarmonicCoordinates(cage, n_cells)
    return _CACHE[key]


def mvc(p, poly):
    """2D mean value coordinates, for comparison."""
    n = len(poly)
    d = [(c[0] - p[0], c[1] - p[1]) for c in poly]
    r = [math.hypot(*v) for v in d]
    tan_half = []
    for i in range(n):
        a, b = d[i], d[(i + 1) % n]
        cr = a[0] * b[1] - a[1] * b[0]
        tan_half.append(cr / (r[i] * r[(i + 1) % n] + (a[0] * b[0] + a[1] * b[1])))
    w = [(tan_half[i - 1] + tan_half[i]) / r[i] for i in range(n)]
    s = sum(w)
    return [x / s for x in w]


def test_partition_of_unity_and_nonnegative():
    for cage, cells in ((L_SHAPE, 16), (STAR, 20)):
        h = hc(cage, cells)
        for vals in h.values:
            assert abs(sum(vals) - 1) < 1e-12
            assert min(vals) >= -1e-14


def test_linear_precision_at_nodes():
    for cage, cells in ((L_SHAPE, 16), (STAR, 20)):
        h = hc(cage, cells)
        for (i, j), r in h.index.items():
            x, y = h.node(i, j)
            vals = h.values[r]
            px = sum(v * c[0] for v, c in zip(vals, cage))
            py = sum(v * c[1] for v, c in zip(vals, cage))
            assert abs(px - x) < 1e-11 and abs(py - y) < 1e-11


def test_rectangle_gives_bilinear_coordinates():
    h = hc(RECT, 12)
    for (i, j), r in h.index.items():
        x, y = h.node(i, j)
        a, b = x / 3, y / 2
        want = [(1 - a) * (1 - b), a * (1 - b), a * b, (1 - a) * b]
        assert all(abs(u - v) < 1e-12 for u, v in zip(h.values[r], want))


def test_band_lu_matches_gauss_seidel():
    h = hc(L_SHAPE, 10)
    lu = BandLU(h.rows)
    for v in range(len(L_SHAPE)):
        b = [row[v] for row in h.rhs]
        x1 = lu.solve(b)
        x2 = gauss_seidel(h.rows, b)
        assert max(abs(a - c) for a, c in zip(x1, x2)) < 1e-10


def test_band_lu_on_random_m_matrix():
    rng = random.Random(41)
    n = 30
    rows = []
    for i in range(n):
        row = {}
        off = 0.0
        for j in range(max(0, i - 3), min(n, i + 4)):
            if j != i and rng.random() < 0.7:
                row[j] = -rng.uniform(0.1, 1.0)
                off += -row[j]
        row[i] = off + rng.uniform(0.1, 1.0)
        rows.append(row)
    x = [rng.uniform(-1, 1) for _ in range(n)]
    b = [sum(v * x[j] for j, v in row.items()) for row in rows]
    y = BandLU(rows).solve(b)
    assert max(abs(a - c) for a, c in zip(x, y)) < 1e-12


def test_harmonic_stays_nonnegative_where_mean_value_goes_negative():
    h = hc(L_SHAPE, 16)
    worst_mvc = 0.0
    for (i, j), r in h.index.items():
        p = h.node(i, j)
        worst_mvc = min(worst_mvc, min(mvc(p, L_SHAPE)))
        assert min(h.values[r]) >= -1e-14
    assert worst_mvc < -0.009
    # The worked example: at (0.875, 1.375) the mean value weight of the
    # vertex (2, 1) is about -0.0097, and its harmonic coordinate is positive.
    p = (0.875, 1.375)
    assert abs(mvc(p, L_SHAPE)[2] + 0.0097336) < 1e-6
    r = h.index[(round((p[0] - h.x0) / h.h), round((p[1] - h.y0) / h.h))]
    assert 0.003 < h.values[r][2] < 0.0032


def test_interpolation_and_deformation():
    h = hc(L_SHAPE, 16)
    rng = random.Random(42)
    for _ in range(20):
        p = (rng.uniform(0, 2), rng.uniform(0, 2))
        if not point_in_polygon(p, L_SHAPE):
            continue
        w = h.coordinates(p)
        assert abs(sum(w) - 1) < 1e-12
        assert min(w) >= -1e-14
    # The identity cage gives back the node, and a translated cage translates it.
    (i, j) = next(iter(h.index))
    p = h.node(i, j)
    q = h.deform(p, L_SHAPE)
    assert math.dist(p, q) < 1e-11
    moved = [(x + 0.5, y - 0.25) for x, y in L_SHAPE]
    q = h.deform(p, moved)
    assert math.dist((p[0] + 0.5, p[1] - 0.25), q) < 1e-11


def test_vertex_coordinate_peaks_near_its_vertex():
    h = hc(L_SHAPE, 16)
    # The coordinate of the reflex vertex (1, 1) is largest close to it.
    best = max(h.index.items(), key=lambda kv: h.values[kv[1]][3])
    x, y = h.node(*best[0])
    assert math.hypot(x - 1, y - 1) < 0.3

History

Joshi, Meyer, DeRose, Green and Sanocki presented harmonic coordinates at SIGGRAPH 2007, from work on character articulation at Pixar. They showed that the mean value coordinates of Ju, Schaefer and Warren (2005) can be negative inside concave cages and proposed the solutions of the Laplace equation instead, computed numerically. Floater (2015) surveys harmonic coordinates together with the other generalized barycentric coordinates.

References

  1. Pushkar Joshi, Mark Meyer, Tony DeRose, Brian Green and Tom Sanocki, Harmonic coordinates for character articulation, SIGGRAPH 2007, ACM Transactions on Graphics 26(3), article 71, 2007, the whole paper (the definition by the Laplace equation with piecewise linear boundary data, the nonnegativity and the comparison with mean value coordinates on concave cages, and the numerical solution on a grid)
  2. Michael S. Floater, Generalized barycentric coordinates and applications, Acta Numerica 24, 161-214, 2015, the whole survey (harmonic coordinates among the generalized barycentric coordinates)

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.all
  • a full proof of time.per_point
  • a full proof of time.precompute
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • History with a source
  • at least three sources
  • a scene preset for the example