Skip to content

Clamped patches

vertax.clamped

Mechanics on a clamped patch: a tissue fragment whose boundary is a field-of-view cut.

A crop of a microscopy field is not a closed tissue and it is not periodic. Some cells are cut by the edge of the image, and at the junctions on that edge one of the incident cells was never imaged, so their force balance cannot be written from the data at all. This module provides the mechanics for that situation: which degrees of freedom carry an equation, how to relax only those, and how to report a residual that means something.

It is the companion to vertax.trace, which produces the patch geometry from a segmentation mask.

What this module does NOT contain: the energy

No energy is defined here, deliberately. Every function below takes the energy as a callable E(x, K). Defining E1 and E2 here would put a second implementation of the same physics inside src/ alongside vertax.energy, which is the drift hazard this package has already paid for once.

The reason vertax.energy cannot simply be called instead is worth stating precisely, because it is a data-structure mismatch rather than a disagreement about physics:

  • vertax.energy and vertax.geo operate on the half-edge tables of a PbcMesh (vertTable, heTable, faceTable, plus width/height), and every length and area they compute goes through the periodic minimum-image convention.
  • A clamped patch has no periodicity and no half-edge table. It is a set of polygons over a shared vertex array, and its boundary is a real boundary rather than a wrap.

Putting a patch into the periodic representation would mean inventing half-edge twins across an edge that has no other side, and setting a box large enough that the minimum-image rule never fires — a representation that is numerically inert but structurally false. So the caller supplies the energy, built from patch_geometry below, and this module supplies everything else.

Signed areas, and why geo.get_area is not used

vertax.geo.get_area returns 0.5 * |shoelace|. That absolute value is correct for the periodic meshes it serves and is not changed here. It is wrong for a clamped patch, and the failure is silent:

  • an area term written (|A| - 1)² has a spurious minimum at A = 0, so a cell collapsing to a point looks like an improvement rather than a failure;
  • |A| cannot distinguish a cell from its own inversion, so a mesh that has folded through itself scores the same as one that has not.

Collapse and inversion are exactly the failure modes a fixed-topology relaxation on real, imperfect geometry runs into, so this module computes a signed area throughout, via signed_face_areas. The sign convention is counter-clockwise-positive, matching vertax.trace, whose faces are emitted in that winding.

The free/clamped partition, which is the substantive content

A vertex is clamped when one of the materials meeting there was not imaged. Such a vertex carries an unknown reaction force from the missing environment, so:

  • it is held fixed during relaxation — relax optimises the free coordinates only;
  • its gradient component is excluded from the residual — r_eq normalises over free components alone. Including it would report the strength of the clamp rather than the quality of the mechanics, and it would improve as the clamp got stiffer.

Typical use

from vertax.clamped import load_mesh, patch_geometry, relax, r_eq, split_gradient

patch = load_mesh("crop.npz")                  # geometry + the free/clamped partition

def E(x, K):                                   # the caller's energy; see the note above
    A, P, L = patch_geometry(x, patch)
    return 0.5 * K * jnp.sum((A - 1.0) ** 2) + jnp.sum(gamma * L)

out = relax(E, patch, K=5.0)                   # free coordinates only
print(out["r_eq"], out["min_area"])            # residual over free DOF; signed, so <0 means folded
u, v = split_gradient(E, patch, out["x"])      # grad E = K u + v, exactly

float64 is required: the residuals reported here reach 1e-13, which float32 cannot represent. Enable it before importing JAX arrays, e.g. jax.config.update("jax_enable_x64", True) at process scope or jax.experimental.enable_x64() as a context manager. The arrays of a loaded patch are float64 on disk and become JAX arrays in JAX's default float dtype, so under x64 they stay float64 with no cast; without x64 they are rounded to float32.

ClampedPatch dataclass

ClampedPatch(stem: str, x0: NDArray, PA: NDArray, PB: NDArray, PF: NDArray, nf: int, EA: NDArray, EB: NDArray, free_idx: NDArray, a_ref_px: float, face_is_interior: NDArray, face_labels: NDArray, n_free: int)

Geometry and boundary partition of one clamped patch, in units of sqrt(A_ref).

Faces are stored as a flat list of polygon corners rather than as cycles, so that areas and perimeters are one segment_sum each: PA[i] -> PB[i] is a polygon edge belonging to face PF[i].

Attributes:

Name Type Description
stem str

identifier of the crop this came from.

x0 NDArray

(Nv, 2) observed vertex positions, normalised by sqrt(A_ref).

PA, (PB, PF)

polygon-corner arrays — start vertex, end vertex, owning face.

nf int

number of faces.

EA, EB

endpoints of the cell-cell edges only. Edges bordering unimaged space carry no tension and exert no force on any free vertex; see clamped_edges_are_inert.

free_idx NDArray

indices of vertices whose force balance can be written from the data.

n_free int

len(free_idx), cached because the residual normalises by it.

a_ref_px float

the reference area in px², i.e. the square of the length unit.

face_is_interior NDArray

faces none of whose edges borders unimaged space.

face_labels NDArray

original segmentation label of each face.

load_mesh

load_mesh(path: str | Path) -> ClampedPatch

Load a traced patch from an .npz file with the keys listed below.

No function of VertAX writes this file: it is the output format of the tracing stage of the analysis pipeline, outside the library. tests/fixtures/clamped_patch_demo_003_pos2.npz is one.

Coordinates are divided by sqrt(a_ref_px) on load, so that a typical interior cell has unit area and every length in this module is dimensionless. That is what makes tensions comparable between crops imaged at different magnifications.

Parameters:

Name Type Description Default
path str | Path

.npz carrying verts_px, faces_padded, face_len, edges, edge_is_cellcell, free, a_ref_px, face_is_interior, face_labels, stem.

required

Returns:

Type Description
ClampedPatch

A ClampedPatch in normalised coordinates.

smoothed_norm

smoothed_norm(d, eps: float)

Edge length, optionally smoothed as sqrt(l² + eps²).

l = ||dx|| has a kink at l = 0, and an energy with tension drives some edges there — that is a T1 demand, not a numerical accident. The kink does not merely stall the local force balance: it breaks the quasi-Newton model globally, so L-BFGS terminates with a residual on every free vertex and a genuine obstruction becomes indistinguishable from a failed minimisation.

With eps > 0 the kink is gone — d(sqrt(l²+eps²))/dl = l/sqrt(l²+eps²) -> 0 as l -> 0, so a zero-length edge is a true smooth stationary point — and the solve converges to machine precision. The unsmoothed residual is then re-evaluated at that configuration, and what remains is the irreducible T1 force and nothing else.

At eps = 1e-6 the smoothing shifts a real edge (l > 1e-2) by under 5e-11 in relative terms, orders below any residual worth reporting.

Parameters:

Name Type Description Default
d

(N, 2) edge vectors.

required
eps float

smoothing scale; 0 gives the exact norm.

required

signed_face_areas

signed_face_areas(x, patch: ClampedPatch)

Shoelace area per face, signed, counter-clockwise positive.

Explicitly signed, and not vertax.geo.get_area, which returns 0.5 * |shoelace|. The absolute value is right for the periodic meshes that function serves and is left alone; here it would hide the two failure modes that matter on real geometry. An area term built on |A| has a spurious minimum at A = 0, so a collapsing cell reads as an improvement, and it scores an inverted cell identically to a healthy one.

Callers should treat A <= 0 as an inverted face and a small positive A as a collapsing one.

patch_geometry

patch_geometry(x, patch: ClampedPatch, eps: float = 0.0)

Signed face areas, face perimeters and cell-cell edge lengths at configuration x.

The three quantities every energy on a patch is built from, computed together because they share the same gather. Areas are signed — see signed_face_areas.

Parameters:

Name Type Description Default
x

(Nv, 2) vertex positions in normalised units.

required
patch ClampedPatch

the patch whose connectivity to use.

required
eps float

edge-length smoothing, passed to smoothed_norm. Applies to perimeters and edge lengths; areas are polynomial and need no smoothing.

0.0

Returns:

Type Description

(areas, perimeters, edge_lengths), with edge_lengths over cell-cell edges only.

split_gradient

split_gradient(E, patch: ClampedPatch, x)

Decompose grad E = K u + v exactly, and return (u, v) at x.

Exact, not a fit: an energy of the form (K/2) Σ(A - A⁰)² + (terms independent of K) is affine in K, so two gradient evaluations determine the decomposition completely. u = d(grad E)/dK and v = grad E at K = 0.

This is what makes the K sensitivity band cheap. Sweeping K over a declared range needs no further autodiff — every gradient in the band is K u + v — and it is what best_K minimises over in closed form.

r_eq

r_eq(grad: NDArray, patch: ClampedPatch) -> float

Force residual per free degree of freedom: ||grad E||₂ / sqrt(2 N_free), free rows only.

Clamped vertices are excluded, and the exclusion is the point. A clamped vertex carries a reaction force from the environment that was never imaged; that force is not a residual, and including it would report how hard the clamp is pulling rather than how well the mechanics balances. It would also improve as the clamp stiffened, which is the wrong direction.

Normalising by sqrt(2 N_free) makes the number comparable between patches of different size.

best_K

best_K(u: NDArray, v: NDArray, patch: ClampedPatch) -> tuple[float, float]

Closed-form argmin_K ||(K u + v)_free||₂, and the residual there.

A diagnostic, not an inference. The tension field is held at its declared value, so this is the area stiffness that best balances an assumed tension field — not a fitted K. It answers "is there any K at which this configuration is close to balanced", which is a useful check on a declared band, and nothing more.

Uses the exact affine decomposition from split_gradient, so no search is involved.

Returns:

Type Description
tuple[float, float]

(K, residual). K is nan when u vanishes on the free rows, i.e. when the area term exerts no force there and no K changes anything.

relax

relax(E, patch: ClampedPatch, K: float, maxiter: int = 30000, gtol: float = 1e-12, E_exact=None) -> dict

Minimise E over the FREE vertices only, holding clamped vertices at their observed places.

The clamped coordinates never enter the optimisation vector, so the reaction forces at the boundary are simply not modelled — which is the honest treatment when the material on the other side was not imaged.

Parameters:

Name Type Description Default
E

energy E(x, K); may be smoothed via eps > 0 in patch_geometry.

required
patch ClampedPatch

the patch to relax.

required
K float

area stiffness.

required
maxiter int

L-BFGS-B iteration cap.

30000
gtol float

L-BFGS-B gradient tolerance.

1e-12
E_exact

unsmoothed energy used to report the residual. When E is smoothed, the residual must be re-evaluated without smoothing or it reports the smoothed problem's balance.

None

Returns:

Type Description
dict

A dict of the converged state and its diagnostics. Beyond the obvious keys:

  • r_eq — residual under E_exact; r_eq_smoothed — under E; r_eq_obs — at the observed configuration, i.e. before relaxing, which is the force-inference residual.
  • min_area is signed: a negative value means a face has inverted.
  • r_eq_excl_T1, n_free_at_T1, n_free_kept — see the note in the body on blocked T1s.

newton_polish

newton_polish(E, patch: ClampedPatch, K: float, x_start: NDArray, iters: int = 60, tol: float = 1e-13, return_info: bool = False) -> NDArray

Levenberg-Marquardt on the force residual, over the free coordinates only.

L-BFGS stalls on this problem at ||grad||/sqrt(2N) ~ 1e-5, and extending the smoothing continuation does not help: the floor is the quasi-Newton model rather than eps (ladders of 4, 6 and 8 smoothing steps all bottom out between 9e-6 and 1e-5). The free block is small — at most 86 x 86 on the patches this was built for — so the exact Hessian is cheap and a damped Newton step on grad E = 0 drives the residual to machine precision.

Levenberg-Marquardt rather than plain Newton because the Hessian is indefinite wherever the configuration sits near a saddle, which is common when cells are close to collapsing.

A solve that exhausts iters without reaching tol is otherwise indistinguishable, in the returned array alone, from one that converged -- there is no separate signal that the loop ran out rather than succeeded. return_info=True exposes that signal; it does not change the array returned, and when return_info is False (the default) behaviour is bit-identical to before this argument existed.

Parameters:

Name Type Description Default
return_info bool

when True, also return a dict of convergence evidence.

False

Returns:

Type Description
NDArray

The polished full vertex array; clamped vertices are unchanged. When return_info is True, returns (x, info) with info carrying grad_norm (achieved ||grad||), iterations (Newton steps actually taken), tol and converged (grad_norm < tol * max(1, n_free)).

clamped_edges_are_inert

clamped_edges_are_inert(mesh_npz: str | Path) -> dict

Check that edges bordering unimaged space exert no force on any free vertex.

This module drops the tension term on cell-background edges entirely. That is only legitimate if those edges cannot influence the force balance where it is written — and they cannot, because both endpoints of such an edge are clamped by construction. The claim is checkable, so it should be checked rather than assumed.

Builds the tension energy twice, over all edges and over cell-cell edges only, and compares the two gradients on the free components. They must agree to machine precision.

Returns:

Type Description
dict

max_abs_diff_free (expected ~1e-16), rel relative to the cell-cell gradient scale, and max_abs_diff_clamped, which is expected to be LARGE — the clamped rows are exactly where the dropped term does act, and it is not a residual there because no equation is written.