Skip to content

Junction relocation

Move a finished mesh's trijunction vertices onto the trijunction curves the mask itself gives.

What it does, and what it deliberately does not

:func:relocate_junction_vertices changes points and never triangles or labels. The connectivity is frozen, which is the whole argument for this construction over earlier attempts to improve junction geometry in this package: those moved tessellation points and let the Delaunay re-bracket the junction line, so the line could move the wrong way when the bracket changed. Here there is no bracket to change, and the treated mesh can be hashed against its own base.

The target is read from the mask, through :func:dw3d.junction_curves.extract_junction_curves, and only its matched curves are used -- the ones with exactly one counterpart among the mesh's own trijunctions of the same material triple. invented curves are never used as targets; fragmented curves are left untouched. No ground truth enters at any point: nothing here reads a reference mesh, a tension, a pressure or a Neumann angle, and the whole path has been re-run from a directory holding only the label image with a bit-identical result.

Two guards, and why both are needed

Local. Moves are applied one vertex at a time in ascending vertex index, against the configuration as it stands rather than against the original, so two neighbouring junction vertices cannot both be accepted on the strength of a geometry neither will end up in. A move is accepted only if every triangle incident to that vertex keeps its normal orientation and keeps its area above :data:MIN_TRIANGLE_AREA, and if it leaves no cell on either side of those triangles with a signed volume of zero or less (a cell that already had one before the pass is not constrained). A rejected move is dropped, never repaired: the vertex stays where it was.

The cell clause exists because the triangle clause is blind to it: on a real embryo timepoint a cell made of a single tetrahedron had one vertex moved 6.7 voxels across the opposite face, every incident triangle kept a normal within 49 degrees of its previous one, and the cell's volume went from +35 to -5.8 cubic voxels. Its surface stayed closed, oriented, manifold and free of crossings, so no other check in the package saw it. The clause tests only the sign, deliberately: a floor at a fraction of the cell's volume before relocation was tried and refused more, because for the small cells that need it that volume is itself wrong, and a refused move freezes a vertex shared by several cells.

Nonlocal. A local guard cannot certify a nonlocal property. A move can drive one sheet of the mesh through a distant sheet while every triangle incident to the moved vertex stays perfectly oriented; measured on this package's benchmark cohort, all twelve local validity predicates stayed bit-identical on 40 of 40 cases while 23 such crossings existed on 5 of them. The second guard closes that: moving one vertex v changes the geometry of exactly the triangles incident to v, so every non-adjacent triangle pair with neither member incident to v has the same status before and after. The change in the whole-mesh crossing count therefore equals the change restricted to the pairs with at least one member incident to v -- an exact identity, not a neighbourhood approximation, because those partners range over the entire mesh. Accepting a move only when that restricted change is non-positive makes the crossing count non-increasing along the accepted sequence by construction.

That argument is checked rather than trusted: with verify=True the whole-mesh certificate of :mod:dw3d.triangle_intersection runs before and after, both counts are reported, and a rise raises rather than being absorbed.

What this costs, and what it buys

Measured over 40 equilibrium benchmark cases at four reconstruction spacings and on four point samplers, 16 independent adjudications. What the pass costs is best stated in seconds, because the reconstruction it follows varies by an order of magnitude between volumes: on the benchmark meshes, whose reconstruction takes about 5 s, it adds about 0.75 s (+15 %); on real embryo volumes, whose reconstruction takes about 0.6 s, it adds 0.1 to 1.5 s per timepoint (median 0.34 s and 0.48 s on the two measured time series, +27 % to +208 %). Within one real series it grows faster than linearly with the number of triangles -- a fitted exponent of 2.68 over a 2.2-fold range of mesh sizes in a fixed imaging volume, which describes that series and is not a tissue-scale law. About half of it is the nonlocal guard's candidate-pair search and a third the mask trijunction-curve extraction. The nonlocal guard refuses between 0.04 % and 0.21 % of the moves the local guard accepts, and that is enough to take the crossing count to zero everywhere. Line position error, local tangent error and discrete curvature all improve with their confidence intervals clear of zero at every spacing and on every sampler, and no pre-existing validity predicate changes on any case. On the seed-free samplers it also improves contact angles by 2.3 to 3.5 degrees and gauge-matched tension error by 20-40 %; on the seeded default sampler the line improves and the angle does not move significantly.

Quadruple points

A junction vertex lying on two or more matched trijunction lines has targets that disagree. The rule is to leave it where it is, and report how many there are. Nothing here invents a consensus position for such a vertex.

Units and conventions

All coordinates are mask voxel units -- the frame a reconstructed dw3d mesh's points live in and the frame :func:~dw3d.junction_curves.extract_junction_curves emits its polylines in. That extractor refuses a mesh whose coordinates do not lie inside the mask's extent, which catches most permuted axis orders; a mesh scaled down into the extent, or permuted on a mask whose sides are nearly equal, passes that check. Areas are square voxels. Vertex order, array shape and dtype are preserved exactly.

Failure modes

A mesh with no matched curve is returned unchanged with n_targets = 0; that is reported, not raised. A matched curve of fewer than two vertices carries no segment and is skipped and counted. A vertex with no incident triangle is skipped. The thresholds here are fixed and are not tuning parameters; they must not be adjusted to improve a reported metric.

CoarseSpacingRelocationWarning

Bases: UserWarning

Junction relocation ran at a point spacing where its effect on tangent-based angles is unverified.

Emitted by :meth:dw3d.reconstruction_algorithm.MeshReconstructionAlgorithm.construct_mesh_from_segmentation_mask once per reconstruction, when junction relocation is on (the default) and the point-placement function's min_distance is at least :data:COARSE_SPACING_MIN_DISTANCE. A placement function that carries no min_distance (a custom callable rather than one of the factory's functools.partial placements) never triggers it, because the spacing cannot be read.

What it means: at min_distance 5 the surface-tangent description of the contact angles moved by a small amount lying within the noise of the check that reads it, and no larger spacing has been measured. Facet-based contact angles improve at every spacing measured. The warning is a subclass of :class:UserWarning, so it can be silenced or promoted to an error on its own with :func:warnings.filterwarnings, and whether it fired is recorded in the algorithm's relocation_provenance. To reproduce the 0.4 behaviour, construct the algorithm with relocate_junctions=False or call set_junction_relocation(False) on the factory.

JunctionRelocationReport dataclass

JunctionRelocationReport(n_matched_curves: int = 0, n_invented_curves: int = 0, n_fragmented_curves: int = 0, n_targets: int = 0, n_quadruple_points_skipped: int = 0, n_accepted: int = 0, n_rejected_inversion: int = 0, n_rejected_degenerate: int = 0, n_rejected_self_intersection: int = 0, n_rejected_cell_inversion: int = 0, cells_kept_from_inverting: list[int] = list(), n_cells_not_positive_before_relocation: int = 0, proposed_displacement_voxels: NDArray[float64] = (lambda: np.zeros(0, dtype=np.float64))(), applied_displacement_voxels: NDArray[float64] = (lambda: np.zeros(0, dtype=np.float64))(), n_self_intersections_before: int | None = None, n_self_intersections_after: int | None = None, n_pairs_tested: int = 0, n_degenerate_encountered: int = 0, guard_seconds: float = 0.0, index_seconds: float = 0.0, curve_counts: dict = dict(), match_rate: float | None = None, spacing_voxels: float | None = None)

Everything one relocation did.

Attributes:

Name Type Description
n_matched_curves int

matched mask curves the extractor returned.

n_invented_curves int

curves the mask has and the mesh has no trijunction for; never used as targets, counted so their number is visible.

n_fragmented_curves int

split, merged or ambiguous curves; left untouched and counted.

n_targets int

mesh junction vertices that received a target.

n_quadruple_points_skipped int

junction vertices on two or more matched triples, left where they are by this module's rule.

n_accepted int

moves applied.

n_rejected_inversion int

moves dropped because an incident triangle would have flipped.

n_rejected_degenerate int

moves dropped because an incident triangle would have collapsed.

n_rejected_self_intersection int

moves the local guard accepted and the nonlocal guard refused.

n_rejected_cell_inversion int

moves the triangle clauses accepted and the cell clause refused, because a cell they touch would have been left with a signed volume of zero or less.

cells_kept_from_inverting list[int]

the labels for which at least one move was refused, ascending.

n_cells_not_positive_before_relocation int

non-zero labels whose signed volume was already zero or less before the pass, to which the cell clause therefore does not apply.

proposed_displacement_voxels NDArray[float64]

the distance every target asked for, one per target.

applied_displacement_voxels NDArray[float64]

the distance every accepted move actually travelled.

n_self_intersections_before int | None

whole-mesh crossings before the pass, or None when verify=False.

n_self_intersections_after int | None

whole-mesh crossings after the pass, or None when verify=False. Never greater than n_self_intersections_before.

n_pairs_tested int

triangle-pair evaluations the nonlocal guard ran, both configurations.

n_degenerate_encountered int

triangles found degenerate during the pass. A non-zero value means the incremental count and the whole-mesh certificate counted different populations, and the comparison between them is void.

guard_seconds float

wall time inside the nonlocal guard.

index_seconds float

wall time building the candidate pair sets.

curve_counts dict

the extractor's own identity counts, carried through.

match_rate float | None

the extractor's matched-over-mesh-trijunction rate.

spacing_voxels float | None

the spacing the extractor resampled its polylines at.

as_dict

as_dict() -> dict

A JSON-serialisable summary, the displacement distributions reduced to quantiles.

Returns:

Name Type Description
dict dict

every count, plus the median, 90th percentile and maximum of both displacement

dict

distributions, or None for each where the distribution is empty.

project_to_segments

project_to_segments(queries: NDArray[float64], starts: NDArray[float64], ends: NDArray[float64]) -> tuple[NDArray[np.float64], NDArray[np.float64]]

Distance from each query to the nearest of a set of segments, and the foot of it.

Parameters:

Name Type Description Default
queries NDArray[float64]

query positions, (n, 3), voxel units.

required
starts NDArray[float64]

segment start points, (m, 3).

required
ends NDArray[float64]

segment end points, (m, 3).

required

Returns:

Name Type Description
tuple NDArray[float64]

(distances, feet), shapes (n,) and (n, 3). With no segment or no query the

NDArray[float64]

distances are inf and the feet are the queries themselves.

triangle_normals

triangle_normals(points: NDArray[float64], triangles: NDArray[integer]) -> NDArray[np.float64]

Unnormalised triangle normals; their length is twice the triangle's area.

Parameters:

Name Type Description Default
points NDArray[float64]

vertex coordinates.

required
triangles NDArray[integer]

triangle vertex indices.

required

Returns:

Type Description
NDArray[float64]

NDArray[np.float64]: one normal per triangle, (m, 3).

vertex_incidence

vertex_incidence(triangles: NDArray[integer], n_points: int) -> list[list[int]]

Triangle indices incident to each vertex.

Parameters:

Name Type Description Default
triangles NDArray[integer]

triangle vertex indices.

required
n_points int

number of vertices, so an isolated vertex gets an empty list.

required

Returns:

Type Description
list[list[int]]

list[list[int]]: per vertex, the indices of its incident triangles.

matched_curve_targets

matched_curve_targets(curves, points: NDArray[float64], triangles: NDArray[integer], labels: NDArray[integer]) -> tuple[dict[int, NDArray[np.float64]], dict[int, float], set[int], dict]

Per mesh junction vertex, its projection onto its own triple's matched mask curve.

A mesh vertex belonging to more than one matched triple is a quadruple point: its targets disagree, so it is excluded here and counted.

Parameters:

Name Type Description Default
curves JunctionCurves

the extractor's output for this (mask, mesh).

required
points NDArray[float64]

mesh vertex coordinates, voxel units.

required
triangles NDArray[integer]

triangle vertex indices.

required
labels NDArray[integer]

the two materials each triangle separates.

required

Returns:

Name Type Description
tuple dict[int, NDArray[float64]]

(targets, proposed_distance, quadruple_vertices, diagnostics) where targets maps

dict[int, float]

a vertex index to its projected position, proposed_distance maps the same keys to how far

set[int]

that move would travel, and quadruple_vertices are the excluded ones.

build_vertex_pair_sets

build_vertex_pair_sets(points: NDArray[float64], triangles: NDArray[integer], targets: dict[int, NDArray[float64]]) -> tuple[dict[int, NDArray[np.int64]], float]

For each vertex with a target, a superset of the pairs its move can change the status of.

The superset is built from the base centroids with an inflation that covers every displacement the pass can ever propose, so one static index serves the whole pass: a triangle's centroid moves by at most the largest displacement d of its own three vertices, its radius about that centroid grows by at most 2 d, and two triangles can meet only when their centroids lie within the sum of their radii. A pair that can ever meet therefore satisfies |c_f - c_t| <= r_f + r_t + 3 (d_f + d_t) at base. Writing reach = r + 3 d, the pairs of a vertex are every (f, t) with f incident to the vertex, t != f, |c_f - c_t| <= reach_f + reach_t (evaluated as np.linalg.norm of the centroid difference), and f and t sharing no vertex.

The neighbour search is one batched k-d tree search per pair of reach bins (:func:_neighbours_within_reach) rather than one ball query per triangle inflated by the mesh's largest reach; the exact criterion above then decides, so the pair sets are the same whatever the search proposes.

Parameters:

Name Type Description Default
points NDArray[float64]

the base vertex coordinates, voxel units.

required
triangles NDArray[integer]

triangle vertex indices, never modified.

required
targets dict[int, NDArray[float64]]

vertex index to proposed position; only these vertices move, and their displacements set the inflation.

required

Returns:

Name Type Description
tuple dict[int, NDArray[int64]]

(pairs_by_vertex, seconds). Each value is a (k, 2) int64 array of triangle

float

index pairs, each row (smaller, larger), rows in ascending lexicographic order, with

tuple[dict[int, NDArray[int64]], float]

adjacency already removed, ready for the exact predicate. A vertex whose move can change

tuple[dict[int, NDArray[int64]], float]

nothing maps to an empty (0, 2) array.

relocate_junction_vertices

relocate_junction_vertices(segmented_mask: NDArray[uint], points: NDArray[float64], triangles: NDArray[integer], labels: NDArray[integer], *, estimator: Estimator = 'plain', curves=None, verify: bool = True) -> tuple[NDArray[np.float64], JunctionRelocationReport]

Move a mesh's trijunction vertices onto the mask's own trijunction curves.

Connectivity is frozen: triangles and labels are not read for anything but the junction structure and are never modified, so only points changes and the result can be hashed against its input. See the module docstring for the two guards and for what the construction was measured to cost and to buy.

Parameters:

Name Type Description Default
segmented_mask NDArray[uint]

the label image the mesh was reconstructed from.

required
points NDArray[float64]

mesh vertex coordinates in mask voxel units, (n, 3), in the mask's index order, as construct_mesh_from_segmentation_mask returns them.

required
triangles NDArray[integer]

triangle vertex indices, (m, 3).

required
labels NDArray[integer]

the two materials each triangle separates, (m, 2).

required
estimator Estimator

which sub-voxel estimator :func:~dw3d.junction_curves.extract_junction_curves runs. "plain" is the default this construction was specified and measured against; "anchor" costs roughly fifteen times as much for 9-11 % of the line-position gain.

'plain'
curves JunctionCurves | None

a precomputed :class:~dw3d.junction_curves.JunctionCurves for this (mask, mesh), to avoid extracting twice when several treatments share one base mesh. Defaults to None, which extracts them.

None
verify bool

run the whole-mesh self-intersection certificate before and after and record both counts. Adds about 0.08 s per benchmark mesh. Leave it on unless the certificate is already being run by the caller.

True

Returns:

Name Type Description
tuple tuple[NDArray[float64], JunctionRelocationReport]

(moved_points, report). moved_points is a new float64 array with the same shape and vertex order as points; points is not modified. report is a JunctionRelocationReport.

Raises:

Type Description
ValueError

propagated from the extractor if the mesh does not lie in the mask's frame.

RuntimeError

if verify is on and the whole-mesh crossing count rose. That is impossible if the nonlocal guard is correct, so it is a defect in this module and is raised rather than absorbed.