Skip to content

The dw3d package

Delaunay-Watershed 3D (dw3d): build a multimaterial surface mesh from a 3-D segmentation mask.

The top-level names build a reconstruction algorithm (get_default_mesh_reconstruction_algorithm, MeshReconstructionAlgorithmFactory), save and reload its meshes, and read extra information from the mask (junction curves, crop faces, cell volumes).

Conventions used everywhere in the package:

  • The mask is a 3-D integer array; label 0 is the medium (the outside of the tissue), every other label is a cell.
  • Mesh points are in the mask's index order: column i of points is the position along the mask's axis i. For a microscope stack stored as (z, y, x), the order dw3d assumes, the points are (z, y, x). construct_mesh_from_segmentation_mask returns them in voxel units: the centre of voxel (i, j, k) is the point (i, j, k).
  • spacing is the voxel size along the mask's axes 0, 1, 2, so (dz, dy, dx) for a (z, y, x) stack.
  • labels[n] = (a, b), with a < b, are the two regions triangle n separates; its normal (right-hand rule on its three vertices) points out of a and into b: each triangle is the positively oriented boundary of a. dw2d's edges follow the same rule in their index order (row, column) (since 0.8.0; docs/user-guide/orientation-in-two-and-three-dimensions.md).
  • A 2-D mask given to the reconstruction is meshed by dw2d (MeshReconstructionAlgorithm's docstring).
  • min_distance (the point placement's minimum distance between points) counts voxels of the grid the mask is meshed on.

get_default_mesh_reconstruction_algorithm module-attribute

get_default_mesh_reconstruction_algorithm = MeshReconstructionAlgorithmFactory.get_default_algorithm

The default mesh reconstruction algorithm, the dithered configuration.

The same function as MeshReconstructionAlgorithmFactory.get_default_algorithm, which gives its arguments (min_distance, print_info, ...) and what it returns.

get_dithered_mesh_reconstruction_algorithm module-attribute

get_dithered_mesh_reconstruction_algorithm = MeshReconstructionAlgorithmFactory.get_dithered_algorithm

The dithered configuration, today the default: MeshReconstructionAlgorithmFactory.get_dithered_algorithm.

get_deterministic_mesh_reconstruction_algorithm module-attribute

get_deterministic_mesh_reconstruction_algorithm = MeshReconstructionAlgorithmFactory.get_deterministic_algorithm

The deterministic configuration (no dither): MeshReconstructionAlgorithmFactory.get_deterministic_algorithm.

The baseline the other point placements are measured against.

get_boundary_layer_mesh_reconstruction_algorithm module-attribute

get_boundary_layer_mesh_reconstruction_algorithm = MeshReconstructionAlgorithmFactory.get_boundary_layer_algorithm

The boundary-layer configuration, opt-in: MeshReconstructionAlgorithmFactory.get_boundary_layer_algorithm.

get_junction_protected_mesh_reconstruction_algorithm module-attribute

get_junction_protected_mesh_reconstruction_algorithm = _factory.get_junction_protected_algorithm

Boundary layer and junction protection: MeshReconstructionAlgorithmFactory.get_junction_protected_algorithm.

Opt-in: at its defaults it enlarges every interface area by about 15.7 %; see the factory.

get_link_checked_mesh_reconstruction_algorithm = _factory.get_link_checked_algorithm

The "revised meshing" configuration, opt-in: MeshReconstructionAlgorithmFactory.get_link_checked_algorithm.

Better mesh geometry, worse tension inference than the default (BENCHMARKS.md).

CellVolumeDisagreementWarning

Bases: UserWarning

Some cells of the last reconstruction have a mesh volume that disagrees with their voxel count.

Emitted by :meth:dw3d.reconstruction_algorithm.MeshReconstructionAlgorithm.construct_mesh_from_segmentation_mask once per reconstruction, when :func:compare_cell_volumes_with_mask lists at least one cell. The list is the algorithm's cell_volume_report. The mesh itself is unchanged. 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.

CellVolumeReport dataclass

CellVolumeReport(ratio_range: tuple[float, float] = CELL_VOLUME_RATIO_RANGE, n_cells: int = 0, n_cells_in_mesh: int = 0, cells: list[dict] = list())

The labels whose mesh volume disagrees with their voxel count.

Attributes:

Name Type Description
ratio_range tuple[float, float]

the inclusive range of mesh volume over voxel count that is not listed.

n_cells int

non-zero labels in the mask.

n_cells_in_mesh int

those that at least one mesh triangle carries.

cells list[dict]

one dict per listed label, in ascending label order, with label, voxels, mesh_volume (cubic voxels, None when absent), ratio (mesh_volume / voxels, None when absent) and reason ("absent", "non-positive", "below" or "above", the first that applies in that order).

labels property

labels: list[int]

The listed labels, ascending.

counts

counts() -> dict[str, int]

How many labels are listed for each reason.

as_dict

as_dict() -> dict

A JSON-serialisable copy of the report, with the counts per reason.

CropFaceReport dataclass

CropFaceReport(crop_faces: NDArray[bool_], image_face_of_triangle: NDArray[int64], cell_reaches_image_face: NDArray[bool_], cut_cells: tuple[int, ...], physical_image_faces: tuple[str, ...], image_shape: tuple[int, ...], cells_on_image_faces: tuple[tuple[int, ...], ...])

Where a reconstructed mesh meets the image box, and what that makes of its cells.

Attributes:

Name Type Description
crop_faces NDArray[bool_]

(n_triangles,) bool, aligned with the mesh's triangle rows: True on every border triangle that lies on an image face not declared physical and that its cell reaches in the mask.

image_face_of_triangle NDArray[int64]

(n_triangles,) int: the index in IMAGE_FACES of the image face a border triangle lies on, ON_NO_SINGLE_IMAGE_FACE for a border triangle on none, NOT_A_BORDER_TRIANGLE elsewhere.

cell_reaches_image_face NDArray[bool_]

(n_triangles,) bool: True on a border triangle whose cell has a voxel of the mask on the image face the triangle lies on (for a triangle on no single image face: on an image face one of its vertices lies on), physical or not.

cut_cells tuple[int, ...]

labels of the cells with a crop face or with a vertex on one, sorted.

physical_image_faces tuple[str, ...]

the image faces declared physical, in IMAGE_FACES order.

image_shape tuple[int, ...]

the mask's shape, which sets where the image faces are.

cells_on_image_faces tuple[tuple[int, ...], ...]

for each face of IMAGE_FACES, in that order, the labels of the cells with at least one voxel of the mask on it, sorted.

n_border_triangles property

n_border_triangles: int

Border triangles, crop faces and border triangles on physical image faces together.

n_crop_faces property

n_crop_faces: int

Crop faces.

n_border_triangles_the_cell_does_not_reach property

n_border_triangles_the_cell_does_not_reach: int

Border triangles on an image face their cell does not reach in the mask: medium contact.

meets_the_image_box property

meets_the_image_box: bool

Whether a border triangle lies on an image face its cell reaches, crop or physical.

This is when the crop record of a file says something: save_to_rec_mesh and save_to_vtk_mesh write it exactly then, and otherwise write the file as before crop faces were recorded.

cells_reaching_a_crop_without_a_crop_face property

cells_reaching_a_crop_without_a_crop_face: tuple[int, ...]

Cells that reach a crop image face in the mask but are not cut cells.

Such a cell continues beyond the image, but the reconstruction put no border triangle of it on that face (it reaches the face with too few voxels), so nothing marks it cut and its pressure is reported. Empty on every mask measured so far is not a guarantee.

as_dict

as_dict() -> dict

JSON-serialisable summary: counts per image face, the crop face count and the cut cells.

EnclosedMedium dataclass

EnclosedMedium(label: int, voxels: int, inscribed_radius: float, lining_cells: tuple[int, ...])

An enclosed pocket of medium that became its own region.

Attributes:

Name Type Description
label int

its label in the reconstructed mask and mesh.

voxels int

its voxel count.

inscribed_radius float

the largest distance from one of its voxels to the nearest voxel outside it, in voxels of the grid that was meshed.

lining_cells tuple[int, ...]

the labels 6-adjacent to it, ascending.

EnclosedMediumReport dataclass

EnclosedMediumReport(media: tuple[EnclosedMedium, ...] = (), pockets_left_to_cells: tuple[PocketLeftToCells, ...] = (), exterior_pieces: int = 0, min_inscribed_radius: float = 0.0, unresolved: tuple[UnresolvedRegion, ...] = (), min_distance: int | None = None, moved_seeds: tuple[int, ...] = (), exterior_seeds_changed: bool = False, has_medium: bool = False)

The pieces of medium of one reconstruction: the enclosed media made, the pockets left, the exterior.

Attributes:

Name Type Description
media tuple[EnclosedMedium, ...]

the enclosed pockets that became their own regions, by label.

pockets_left_to_cells tuple[PocketLeftToCells, ...]

the enclosed pockets left to the cells, in the order of their lowest raster index.

exterior_pieces int

the pieces of label 0 that touch a face of the array, each of which gets a seed.

min_inscribed_radius float

the size bound used, in voxels.

unresolved tuple[UnresolvedRegion, ...]

the regions of the meshed mask absent from the finished mesh, by label, each with its cause (filled by the reconstruction; UnresolvedCellWarning).

min_distance int | None

the point placement's min_distance the reconstruction used (None when unknown).

moved_seeds tuple[int, ...]

labels whose seed's nearest tetrahedron lay outside their own voxels and was replaced by the nearest one inside (filled by the reconstruction).

exterior_seeds_changed bool

whether label 0's seeds differ from the one seed a single label gets (two or more exterior pieces, or the deepest voxel of label 0 in a pocket left to the cells; filled by the reconstruction).

dropped_seeds property

dropped_seeds: tuple[int, ...]

The labels of the unresolved regions, ascending.

unresolved_cells property

unresolved_cells: tuple[int, ...]

The labels of the unresolved regions that are cells, ascending.

changes_the_mesh property

changes_the_mesh: bool

Whether any of the three rules acted, so that the mesh may differ from 0.7.0's on the same tesselation.

False means: no enclosed medium made, label 0 seeded as before, every seed already inside its label. The reconstruction is then bitwise what it was (pockets left to the cells are left as before).

medium_labels property

medium_labels: tuple[int, ...]

The labels that are media: 0 first when the mask has it, then the enclosed media, ascending.

as_dict

as_dict() -> dict

A JSON-serialisable copy of the report.

EnclosedMediumWarning

Bases: UserWarning

Enclosed pockets of medium were left to the cells around them.

Emitted once per reconstruction that leaves at least one pocket of label 0 to the cells (below the size bound, or lined by one cell). The pockets are the reconstruction's enclosed_medium_report.pockets_left_to_cells. A subclass of :class:UserWarning, so it can be silenced or promoted to an error on its own with :func:warnings.filterwarnings.

PocketLeftToCells dataclass

PocketLeftToCells(voxels: int, inscribed_radius: float, lining_cells: tuple[int, ...], reason: str, absorbed_by: int | None = None)

An enclosed pocket of medium left to the cells around it, as before 0.7.1.

Attributes:

Name Type Description
voxels int

its voxel count.

inscribed_radius float

as EnclosedMedium.inscribed_radius.

lining_cells tuple[int, ...]

the labels 6-adjacent to it, ascending.

reason str

"below the size bound", "lined by one cell", or "switched off" (the reconstruction's label_enclosed_media is False).

absorbed_by int | None

the region that took most of the volume of the tetrahedra whose centroid lies in the pocket; when none does, the region of the tetrahedron whose centroid is nearest to the pocket's deepest voxel. Usually a lining cell; it can be 0 (a pocket of a few voxels next to the exterior). None before the reconstruction's watershed has run.

UnresolvedCellWarning

Bases: UserWarning

Some regions of the mask are absent from the mesh.

Emitted once per reconstruction whose finished mesh lacks a label of the mask that was meshed, whatever the cause, naming each such region with its voxel count, the cause and the min_distance; the regions are the reconstruction's enclosed_medium_report.unresolved. A smaller min_distance may mesh them. The causes:

  • no tetrahedron centroid lies in the region's voxels (a cell a few voxels thick, or smaller than the point placement's min_distance). A region's watershed seed is the tetrahedron whose centroid is nearest to its deepest voxel; here that tetrahedron belongs to a neighbour, and before 0.7.1 the region grew from it inside the neighbour, as a phantom. Since 0.7.1 the seed is dropped.
  • the region was seeded, but the watershed left it few tetrahedra (often only its seed: the rest of the region, grouped without the seed, went to a neighbour) and mesh surgery relabelled those. Since 0.8.0 such a region is named too; before, only CellVolumeDisagreementWarning listed it, as a cell absent from the mesh.
  • the region had no watershed seed (label 0 when no piece of it touches the image box), or holds tetrahedra but no triangle of the finished mesh.

UnresolvedRegion dataclass

UnresolvedRegion(label: int, voxels: int, kind: str, cause: str = NO_TETRAHEDRON_IN_ITS_VOXELS, tetrahedra_after_the_watershed: int | None = None, tetrahedra_in_its_voxels: int | None = None)

A region of the mask that is absent from the finished mesh.

Attributes:

Name Type Description
label int

its label in the mask that was meshed.

voxels int

its voxel count.

kind str

"cell", "enclosed medium" or "exterior" (a piece of label 0 touching the image box).

cause str

"no tetrahedron in its voxels" (its seed was dropped), "removed by mesh surgery" (seeded, but surgery relabelled what the watershed left it), "no watershed seed", or "no triangle in the mesh".

tetrahedra_after_the_watershed int | None

how many tetrahedra the watershed gave it (None when its seed was dropped).

tetrahedra_in_its_voxels int | None

how many tetrahedra have their centroid in its voxels (numpy.rint), that is, what a labelling by centroids would give it (None when its seed was dropped: 0).

ThinMediumMarginWarning

Bases: UserWarning

A cell's mesh lies on a face of the image box that its voxels do not reach, and padding could not prevent it.

Emitted once per reconstruction, naming each such cell, the face, the cell's medium margin to it (the number of voxels of label 0 between the cell and the face) and why the face was not padded: a cell reaches it (it is a crop), padding is switched off, or the margin is already thin_margin_bound(min_distance) or more. The cell may have taken some of the medium between it and the face; compare its volume with its voxel count (cell_volume_report). See dw3d.thin_medium_margins.

JunctionCurve dataclass

JunctionCurve(triple: tuple[int, int, int], points: NDArray[float64], arclength: float, matched: bool, identity: str, component: int, n_estimated: int, n_estimator_refusals: int)

One trijunction polyline read from the mask.

Attributes:

Name Type Description
triple tuple[int, int, int]

the sorted material triple (a, b, c), with label 0 an ordinary material.

points NDArray[float64]

the ordered polyline, shape (n, 3), in mask voxel coordinates.

arclength float

the polyline's total discrete arc length, in voxels.

matched bool

whether the mesh has exactly one trijunction component of this same triple and this is the only component the mask gives for it.

identity str

"matched", "invented" (no mesh trijunction of this triple at all), "split" (one mesh component, several here), "merged" (several mesh components, one here) or "ambiguous" (several on both sides).

component int

index of this component within its triple, ordered by decreasing arclength.

n_estimated int

how many of points the sub-voxel estimator moved. Zero under the default "plain" estimator, which runs no linear program.

n_estimator_refusals int

how many it refused, leaving the detected position in place.

JunctionCurves dataclass

JunctionCurves(matched: tuple[JunctionCurve, ...], invented: tuple[JunctionCurve, ...], fragmented: tuple[JunctionCurve, ...], match_rate: float | None, counts: dict[str, int], spacing_voxels: float | None, estimator: str, diagnostics: dict = dict())

Every trijunction curve of one case, split by whether the mesh agrees it exists.

matched is the set a caller wanting usable geometry wants: on the benchmark at min_distance = 3 its 621 curves were measured a median 0.523 voxels from all three of their own interfaces at once, with a p99 of 4.43. The 27 invented curves are structurally different -- median 29.7 voxels and none within one voxel -- so they are never merged into the same list. fragmented holds the rest: real trijunctions the mask resolves as several pieces, or the reverse.

Attributes:

Name Type Description
matched tuple[JunctionCurve, ...]

curves one-to-one with a mesh trijunction.

invented tuple[JunctionCurve, ...]

curves whose material triple is not a trijunction of the mesh at all.

fragmented tuple[JunctionCurve, ...]

curves that are split, merged or ambiguous against the mesh.

match_rate float | None

matched mesh trijunctions over all mesh trijunctions. Measured 0.900 at min_distance = 3 and 0.908 at 4, with zero missed.

counts dict[str, int]

matched, missed, invented, split, merged, ambiguous, plus mesh_triples and extracted_triples.

spacing_voxels float | None

the reading spacing the polylines were resampled at -- the mesh's own median junction-edge length, so the curves are read at the resolution the mesh is.

estimator str

which sub-voxel estimator ran -- "plain", "anchor" or "centroid".

diagnostics dict

dropped components, estimator statuses, timings and the frame check.

all_curves

all_curves() -> tuple[JunctionCurve, ...]

Every curve, matched first. Use matched unless completeness is what you need.

Returns:

Type Description
tuple[JunctionCurve, ...]

tuple[JunctionCurve, ...]: the matched, then fragmented, then invented curves.

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.

UnmeasuredAnisotropyWarning

Bases: UserWarning

The voxels are more than MEASURED_ANISOTROPY_RATIO_MAX times longer along one axis: accuracy not measured.

Issued by MeshReconstructionAlgorithm.construct_mesh_in_physical_units. The mesh is still built; filter this category to silence it.

AbnormalEdgeWarning

Bases: UserWarning

A finished mesh still has abnormal non-manifold edges.

Emitted by :meth:dw3d.reconstruction_algorithm.MeshReconstructionAlgorithm.construct_mesh_from_segmentation_mask once per reconstruction, when the final mesh has an edge carried by four or more triangles that do not separate as many regions (_find_abnormal_non_manifold_edges): a cell surface that touches itself, or two cells that meet twice, along that edge. The message gives their number and the configuration that made the mesh (point placement and its parameters, mesh surgery, tetrahedron order, offset exclusion). Such edges come from mesh surgery being off, from an edge surgery could not remove without adding another, or from a step after surgery (the offset exclusion of the boundary-layer configurations). Downstream, a junction reader may fail or skip that edge. A subclass of :class:UserWarning, so it can be silenced or promoted to an error on its own with :func:warnings.filterwarnings.

MeshReconstructionAlgorithmFactory

MeshReconstructionAlgorithmFactory(print_info: bool = False, perform_mesh_postprocess_surgery: bool = True)

Factory to build custom algorithms for mesh reconstruction from segmentation masks.

Each set_* method chooses one step and returns the factory, so calls can be chained; make_algorithm builds the algorithm.

Initialize the factory with the steps of the deterministic configuration.

A new factory's make_algorithm builds what get_deterministic_algorithm returns: the classical EDT, deterministic EDT extrema with min_distance=3, plain Delaunay tesselation, max-value face scores, mesh surgery, junction relocation on, the canonical tetrahedron order and no physical image face. This is not get_default_algorithm, which places its points with the dithered rule (set_dithered_peak_local_points_placement_method).

Parameters:

Name Type Description Default
print_info bool

print the timing of each step. Defaults to False.

False
perform_mesh_postprocess_surgery bool

try to detect and fix problems on the output mesh. Defaults to True.

True

set_physical_image_faces

set_physical_image_faces(*faces: str) -> Self

Declare faces of the image box where the tissue really ends, for example on a coverslip.

By default every face of the image box is a crop: a cell surface lying on it is a crop face, not contact with the medium, and the cell is a cut cell (see dw3d.crop_faces and the algorithm's crop_faces and cut_cells). A face declared here is physical: the cell surfaces on it are contact with the medium, as they were before crop faces were recorded. The mesh itself is the same either way.

Parameters:

Name Type Description Default
*faces str

names among dw3d.crop_faces.IMAGE_FACES, "axis0_low" (index 0 along the mask's first axis) to "axis2_high" (the last index along its third). No argument declares none, the default.

()

Returns:

Name Type Description
Self Self

this factory, for chaining.

Raises:

Type Description
ValueError

if a name is not an image face.

set_junction_relocation

set_junction_relocation(enabled: bool = True) -> Self

Choose whether the finished mesh's trijunction vertices move onto the mask's own trijunction curves.

On by default since 0.5.0, for this factory and for every get_*_algorithm static method. set_junction_relocation(False) switches it off and reproduces the 0.4 meshes exactly. The post-process is :func:dw3d.relocate_junction_vertices; it changes vertex positions only, never connectivity or labels, under a guard that provably cannot create a self-intersection anywhere in the mesh.

Cost, in seconds: about +0.75 s on the benchmark meshes (whose reconstruction takes about 5 s, +15 %); 0.1-1.5 s per timepoint on real embryo volumes (median 0.34 s and 0.48 s on two time series, whose reconstruction takes about 0.6 s). Within one real series it grows faster than linearly with mesh size (fitted exponent 2.68 over a 2.2-fold range of triangle counts in a fixed volume -- a description of that series, not a tissue-scale law).

Measured over 40 equilibrium benchmark cases, four reconstruction spacings and four point samplers -- 16 independent adjudications, all passing: line position error, local tangent error and discrete curvature all improve with their intervals clear of zero, no pre-existing validity predicate changes, and the self-intersection count never rises. On the seed-free samplers it also improves contact angles by 2.3-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. At a point-placement min_distance of 5 or more the reconstruction emits :class:dw3d.CoarseSpacingRelocationWarning once.

Parameters:

Name Type Description Default
enabled bool

whether the post-process runs. Defaults to True, so that set_junction_relocation() reads as switching it on.

True

Returns:

Name Type Description
Self Self

this factory, for chaining.

set_canonical_tetrahedron_order

set_canonical_tetrahedron_order(enabled: bool = True) -> Self

Choose whether the tesselation's tetrahedra are put in canonical order before anything reads them.

On by default since 0.7.1, for this factory and for every get_*_algorithm static method. The canonical order sorts the vertex indices within each tetrahedron and the tetrahedra lexicographically (dw3d.tesselation.canonical_tetrahedron_order), so the mesh no longer depends on the row order in which Qhull returns the same tetrahedra. set_canonical_tetrahedron_order(False) keeps Qhull's row order, which reproduces the meshes of dw3d 0.7 and earlier on the machine they were made on. See MeshReconstructionAlgorithm.__init__ for what the row order changes.

Parameters:

Name Type Description Default
enabled bool

whether the tetrahedra are put in canonical order. Defaults to True, so that set_canonical_tetrahedron_order() reads as switching it on.

True

Returns:

Name Type Description
Self Self

this factory, for chaining.

set_classical_edt_method

set_classical_edt_method() -> Self

Use the classical method to create the Euclidean Distance Transform from a segmentation mask (the default).

Returns:

Name Type Description
Self Self

this factory, for chaining.

set_edt_boundary_bias_method

set_edt_boundary_bias_method() -> Self

Use the biased method to create the Euclidean Distance Transform from a segmentation mask.

Returns:

Name Type Description
Self Self

this factory, for chaining.

set_float32_edt_method

set_float32_edt_method(parallel: int = 1) -> Self

Use the float32 EDT: the same field, 2 full-volume arrays instead of ~7.

Bit-identical to set_classical_edt_method, not an approximation — see dw3d.edt's module docstring for why (edt.edt already returns float32; the classical path's float64 is an int32 promotion artifact). Safe as a drop-in.

Parameters:

Name Type Description Default
parallel int

Threads for edt.edt. 1 matches the classical path and keeps the timing comparison honest; the result does not depend on it.

1

Returns:

Name Type Description
Self Self

this factory, for chaining.

set_tiled_edt_method

set_tiled_edt_method(tile_size: int = 256, halo: int = 16, parallel: int = 1, dtype: type = np.float32) -> Self

Use the tiled EDT: 1 full-volume array plus O(tile_size**3) scratch.

Bit-identical in value to the classical path, by the certified escalating-halo argument in dw3d.edt's module docstring; it raises rather than returning an upper bound if a core ever fails to certify.

dtype is not cosmetic — it decides whether this composes with the current default. At the default (np.float32) the field matches the classical one bit for bit but its dtype does not, and the junction-protected configuration reads the EDT's last bits (the boundary-layer scheme's Hessian eigenvector normals, the 27-sample face score interpolation), so the finished reconstruction moves on 8 of 8 in-repo configurations — see tests/test_edt_dtype_composition.py. Passing dtype=np.float64 gives a field that reproduces the default bit for bit (tests/test_edt_float64_tiling.py) at 8 bytes/voxel instead of 4.

Parameters:

Name Type Description Default
tile_size int

Core side length. Keep it well above the cells' inradius: the per-tile work factor is ((tile_size + 2*halo)/tile_size)**3. Defaults to 256.

256
halo int

Initial halo; tiles escalate once if they need more.

16
parallel int

Threads for edt.edt. Defaults to 1.

1
dtype type

np.float32 (this EDT's own contract) or np.float64 (composes with the current default). Defaults to np.float32, so this method's existing behaviour and every fixture pinned to it are unchanged.

float32

Returns:

Name Type Description
Self Self

this factory, for chaining.

set_peak_local_points_placement_method

set_peak_local_points_placement_method(min_distance: int | None = None) -> Self

Place points on the EDT image using local extrema of the EDT (and corners), deterministically.

This is the placement of get_deterministic_algorithm and of a new factory.

Parameters:

Name Type Description Default
min_distance int | None

Minimum distance between extrema, in voxels of the grid the mask is meshed on. Defaults to None: 3 voxels, and dw2d's 4 pixels for a 2-D mask.

None

Returns:

Name Type Description
Self Self

this factory, for chaining.

set_dithered_peak_local_points_placement_method

set_dithered_peak_local_points_placement_method(min_distance: int | None = None, seed: int = 42) -> Self

Place points using the randomly dithered EDT (dw3d <= 0.3.6 behaviour).

This is the placement of get_dithered_algorithm, which get_default_algorithm returns; a new factory uses the deterministic placement instead (set_peak_local_points_placement_method). See dw3d.points_on_edt for the difference.

Parameters:

Name Type Description Default
min_distance int | None

Minimum distance between extrema, in voxels of the grid the mask is meshed on. Defaults to None: 3 voxels, and dw2d's 4 pixels for a 2-D mask.

None
seed int

Seed of the U(0, 1e-5) dither. Defaults to 42, the value that was hard-wired before point placement was made deterministic.

42

Returns:

Name Type Description
Self Self

this factory, for chaining.

set_boundary_layer_points_placement_method

set_boundary_layer_points_placement_method(min_distance: int = 3, delta: float | None = None) -> Self

Place points using the boundary-layer scheme.

The deterministic extrema plus a structured layer of offset points a distance delta into each material adjacent to a genuine interface; see dw3d.points_on_edt for the construction. Opt-in: the default algorithm does not use it.

Parameters:

Name Type Description Default
min_distance int

Minimum distance between extrema, in voxels. Defaults to 3.

3
delta float | None

Offset distance into each material. Defaults to min_distance (the interface spacing h_S) when None.

None

Returns:

Name Type Description
Self Self

this factory, for chaining.

set_junction_protected_points_placement_method

set_junction_protected_points_placement_method(min_distance: int = 3, delta: float | None = None, junction_spacing: float | None = None, shell_coarsening: int = 1) -> Self

Place points using the junction-protected scheme.

The boundary layer plus 0-/1-junction detection, protecting balls and a junction boundary layer; see dw3d.points_on_edt for the construction. This scheme returns per-point weights, so pair it with set_weighted_delaunay_tesselation_method -- get_junction_protected_algorithm does that for you. Opt-in: the default algorithm does not use it.

Its defaults are those of the junction-protection scheme as first designed, not those of get_junction_protected_algorithm: the junction boundary layer is on and the shell coarsening is off (get_junction_protected_algorithm defaults to junction_boundary_layer=False and shell_coarsening=3).

Parameters:

Name Type Description Default
min_distance int

Minimum distance between extrema, in voxels. Defaults to 3.

3
delta float | None

Boundary-layer offset distance. Defaults to min_distance.

None
junction_spacing float | None

Arclength h_J between 1-junction samples. Defaults to 2*min_distance + 1, the effective interface spacing.

None
shell_coarsening int

Re-pack the bounding-box / background shell minima at this multiple of 2*min_distance + 1. 1 is off. Defaults to 1.

1

Returns:

Name Type Description
Self Self

this factory, for chaining.

set_weighted_delaunay_tesselation_method

set_weighted_delaunay_tesselation_method() -> Self

Use a regular (weighted Delaunay) triangulation, driven by the point weights.

Falls back to simple_delaunay_tesselation bit-for-bit when the point-placing function supplies no weights, or supplies all-zero ones (see dw3d.tesselation).

Returns:

Name Type Description
Self Self

this factory, for chaining.

set_peak_local_points_bias_boundary_placement_method

set_peak_local_points_bias_boundary_placement_method(min_distance: int = 3) -> Self

Place points on the EDT image using local extrema of the EDT (and corners) and boundaries.

Parameters:

Name Type Description Default
min_distance int

Minimum distance between extrema, in voxels. Defaults to 3.

3

Returns:

Name Type Description
Self Self

this factory, for chaining.

set_delaunay_tesselation_method

set_delaunay_tesselation_method() -> Self

Use Delaunay algorithm to create the tesselation from a list of points (the default).

Returns:

Name Type Description
Self Self

this factory, for chaining.

set_score_computation_by_mean_value

set_score_computation_by_mean_value(spline_order: int = 1) -> Self

Use the mean value of the EDT image on triangle faces of the tesselation to compute scores for Watershed.

Parameters:

Name Type Description Default
spline_order int

1 for trilinear interpolation of the EDT (the historical behaviour), 3 for the cubic B-spline interpolant. Defaults to 1.

1

Returns:

Name Type Description
Self Self

this factory, for chaining.

set_score_computation_by_max_value

set_score_computation_by_max_value(spline_order: int = 1) -> Self

Use the max value of the EDT image on triangle faces of the tesselation to compute scores for Watershed.

Parameters:

Name Type Description Default
spline_order int

1 for trilinear interpolation of the EDT (the historical behaviour), 3 for the cubic B-spline interpolant. Defaults to 1. The cubic interpolant is C2 where trilinear is only C0, which both smooths the score field and is a prerequisite for sub-voxel extremum refinement (not implemented here). It changes the labelling, so it is opt-in.

1

Returns:

Name Type Description
Self Self

this factory, for chaining.

make_algorithm

make_algorithm() -> MeshReconstructionAlgorithm

Build a new mesh reconstruction algorithm using the previously set methods.

Returns:

Name Type Description
MeshReconstructionAlgorithm MeshReconstructionAlgorithm

Mesh Reconstruction Algorithm ready to be executed.

get_default_algorithm staticmethod

get_default_algorithm(min_distance: int | None = None, print_info: bool = False) -> MeshReconstructionAlgorithm

Return the default mesh reconstruction algorithm with sensible default values.

This is get_dithered_algorithm at its own defaults: the published dw3d 0.3.6 configuration. The default was for a time the junction-protected, offset-excluded configuration (get_link_checked_algorithm); it went back to the dithered one because the end-to-end tension-inference accuracy that the meshing pipeline exists to serve is worse with the revised meshing than with the dithered configuration, on every method measured, despite the revised mesh's better geometric quality in isolation:

method dithered E_total (gauge-matched median) revised (link_checked) E_total
YoungDupre 0.0763 0.1003
YoungDupreLocal 0.0911 0.1266
ForceBalanceKKT 0.1138 0.3262
BayesianMAP 0.1186 0.3149

(42 equilibrium cases of foambryo's benchmarking dataset, min_distance 3, dw3d 0.7.1, paired per case; see BENCHMARKS.md at the repository root.) The revised pipeline is real, deterministic, junction-protected and topologically cleaner than the dithered default by every meshing-only metric (interface-area bias, sliver fraction, score-gap degeneracy, non-manifold edges) -- it is kept, fully reachable, as an opt-in variant: get_link_checked_algorithm, a name that describes its mechanism (a link-condition-checked, topology-preserving offset collapse). Use it when meshing quality (junction placement, interface smoothness, topology) matters more than today's downstream tension-inference accuracy; use the default when tension inference is the goal, which is the common case.

Every configuration reachable from here keeps its own reference meshes and 51-case benchmark records:

  • get_link_checked_algorithm -- boundary layer + junction protection + link-checked offset exclusion; the opt-in "revised" variant, see above.
  • get_junction_protected_algorithm at its defaults -- boundary layer + junction protection alone, with the boundary-layer offsets left in the extracted surface. Carries a +15.7 % interface-area regression against ground truth that the link-checked exclusion removes; kept so it can be benchmarked against. (Its synonym get_offset_included_algorithm, deprecated since 0.5.0, was removed in 0.7.0.)
  • get_deterministic_algorithm -- deterministic EDT extrema only, plain Delaunay, no boundary layer or junction protection: the baseline the boundary-layer and junction-protection placements are measured against.

Every configuration, this one included, relocates junction vertices by default since 0.5.0; set relocate_junctions = False on the returned algorithm to reproduce 0.4. Every configuration puts the tetrahedra in canonical order by default since 0.7.1; set canonical_tetrahedron_order = False on the returned algorithm to keep Qhull's row order, as dw3d 0.7 did.

The EDT is compute_edt_classical. The tiled EDT (set_tiled_edt_method, reachable from a factory instance, not used here) produces a field whose values are bit-identical at a third of the peak RSS, and it is the variant to prefer at scale. Composition with a given reconstruction algorithm depends on whether that algorithm reads the EDT field's last bits (get_dithered_algorithm and get_deterministic_algorithm do not; get_link_checked_algorithm and its boundary-layer-derived relatives do, through the Hessian-eigenvector normals and the 27-sample face score interpolation -- see tests/test_edt_dtype_composition.py, and tests/test_edt_float64_tiling.py for the dtype=np.float64 variant that does compose with them at 8 bytes/voxel instead of 4).

Parameters:

Name Type Description Default
min_distance int | None

Minimum distance (in voxels of the grid the mask is meshed on) between extrema when placing tesselation points. Defaults to None: 3 voxels; a 2-D mask given to the algorithm is meshed by dw2d with 4 pixels, dw2d's default (an explicit value is used in both dimensions).

None
print_info bool

Print algorithm details while executing. Defaults to False.

False

Returns:

Name Type Description
MeshReconstructionAlgorithm MeshReconstructionAlgorithm

a new algorithm, with junction relocation on.

get_deterministic_algorithm staticmethod

get_deterministic_algorithm(min_distance: int | None = None, print_info: bool = False) -> MeshReconstructionAlgorithm

Return the deterministic algorithm: EDT extrema only, no dither, plain Delaunay.

This was get_default_algorithm for a time, between the dithered configuration and the junction-protected one. It is kept as a named variant, with its own reference meshes (tests/golden/deterministic/) and 51-case benchmark records (dw3d_benchmarks/baseline/deterministic/), because it is the baseline the boundary-layer and junction-protection placements are measured against -- dropping it would make those measurements unreproducible. A new MeshReconstructionAlgorithmFactory builds the same configuration.

Parameters:

Name Type Description Default
min_distance int | None

Minimum distance between extrema, in voxels. Defaults to None: 3, and dw2d's 4 pixels for a 2-D mask.

None
print_info bool

Print algorithm details while executing.

False

Returns:

Name Type Description
MeshReconstructionAlgorithm MeshReconstructionAlgorithm

a new algorithm, with junction relocation on.

get_dithered_algorithm staticmethod

get_dithered_algorithm(min_distance: int | None = None, print_info: bool = False, seed: int = 42) -> MeshReconstructionAlgorithm

Return the reconstruction algorithm as it was in dw3d 0.3.6, before point placement was made deterministic.

This is get_default_algorithm again (it was the default originally, then superseded for a time by the junction-protected and link-checked configurations, then restored): the revised meshing pipeline (get_link_checked_algorithm) produces better mesh geometry in isolation but worse end-to-end tension-inference accuracy on every method measured, so the dithered configuration ships as the default and the revised pipeline is the opt-in variant; see get_default_algorithm's docstring for the numbers.

The point placement is the historical randomly dithered one, so this reproduces the 0.3.6 point set exactly. The watershed's edge ordering is not reverted: the historical ordering was a sort with no tie-break over a score field that is ~30 % exactly tied, so it has no single well-defined answer to reproduce — it depended on numpy's sorting kernel. tests/golden/dithered/ records what this factory produces on the current stack, and is therefore a point-budget reference rather than a bit-for-bit replica of published output.

Parameters:

Name Type Description Default
min_distance int | None

Minimum distance between extrema, in voxels. Defaults to None: 3, and dw2d's 4 pixels for a 2-D mask.

None
print_info bool

Print algorithm details while executing.

False
seed int

Seed of the dither. Defaults to 42, the historical value.

42

Returns:

Name Type Description
MeshReconstructionAlgorithm MeshReconstructionAlgorithm

a new algorithm, with junction relocation on.

get_boundary_layer_algorithm staticmethod

get_boundary_layer_algorithm(min_distance: int = 3, print_info: bool = False, delta: float | None = None) -> MeshReconstructionAlgorithm

Return the boundary-layer reconstruction algorithm (opt-in, not the default).

Same as get_deterministic_algorithm but with the boundary-layer point placement (set_boundary_layer_points_placement_method): the deterministic extrema plus offset points. Kept as a named variant so its reference meshes and benchmark records live alongside the others'; it did not become the default.

Parameters:

Name Type Description Default
min_distance int

Minimum distance between extrema, in voxels. Defaults to 3.

3
print_info bool

Print algorithm details while executing.

False
delta float | None

Offset distance into each material. Defaults to min_distance when None.

None

Returns:

Name Type Description
MeshReconstructionAlgorithm MeshReconstructionAlgorithm

a new algorithm, with junction relocation on.

get_junction_protected_algorithm staticmethod

get_junction_protected_algorithm(min_distance: int = 3, print_info: bool = False, delta: float | None = None, junction_spacing: float | None = None, shell_coarsening: int = 3, protect_radius: float | None = None, junction_delta: float | None = None, protect_junctions: bool = True, junction_boundary_layer: bool = False, use_weights: bool = True, spline_order: int = 1, exclude_offsets_from_surface: bool = False, guard_duplicate_faces: bool = True, collapse_rule: str = WELD) -> MeshReconstructionAlgorithm

Return the junction-protected reconstruction algorithm.

This is the configuration get_default_algorithm returned for a time before the link-checked offset exclusion became the default (its former synonym get_offset_included_algorithm was removed in 0.7.0). It is the only way to reach the ablation switches below, and the corresponding benchmark records are keyed on it. This configuration plus the link-checked offset exclusion (get_link_checked_algorithm) is reachable from here as exclude_offsets_from_surface=True, collapse_rule=LINK_CONDITION.

The boundary layer plus 0-/1-junction detection, protecting balls and shell coarsening, tesselated by the regular (weighted) triangulation that consumes the protecting-ball radii. The boundary layer and junction protection are assessed as a pair, so this getter is that combined configuration; get_boundary_layer_algorithm remains the boundary layer alone and get_deterministic_algorithm is the configuration that predates both.

Two defaults differ from the junction-protection scheme as first designed, both on measured grounds:

  • junction_boundary_layer=False. The first design asks for the boundary layer around junction samples too, on the grounds that it prevents the "more points locally -> more small tets" failure. Measured over 11 cases it causes that failure: it takes valence->=4 edges 33 -> 119 and abnormal non-manifold edges 2 -> 91, essentially all of the added valence->=4 edges being the 3-material (pinched-triple-line) kind. The mechanism is structural, not a bad constant: the junction offsets refill the protecting balls that the same construction has just emptied, and a protecting ball only protects while it stays empty. The layer is implemented and reachable with junction_boundary_layer=True so the originally specified configuration stays reproducible.
  • shell_coarsening=3. Off (1) is a valid configuration and meets the topology criteria too; 3 is chosen for the point budget and wall time, not to make any acceptance criterion pass, on the strength of a sweep over the coarsening factor.

Parameters:

Name Type Description Default
min_distance int

Minimum distance between extrema. Defaults to 3.

3
print_info bool

Print algorithm details while executing.

False
delta float | None

Boundary-layer offset distance. Defaults to min_distance when None.

None
junction_spacing float | None

h_J; defaults to 2*min_distance + 1 when None.

None
shell_coarsening int

Shell re-packing factor; 1 is off. Defaults to 3.

3
protect_radius float | None

Protecting-ball radius. Defaults to junction_spacing / 2.

None
junction_delta float | None

Junction boundary-layer offset distance. Defaults to protect_radius.

None
protect_junctions bool

Ablation switch; see dw3d.points_on_edt.junction_protected_families. Defaults to True.

True
junction_boundary_layer bool

Ablation switch; True restores the junction-protection scheme as first designed. Defaults to False — see above.

False
use_weights bool

Ablation switch — False tesselates the same point set with plain Delaunay, isolating the regular triangulation's own contribution. Defaults to True.

True
spline_order int

EDT interpolation order for the watershed scores; 3 selects the cubic B-spline. Defaults to 1, trilinear, which is what the default algorithm uses. See dw3d.score_computation.

1
exclude_offsets_from_surface bool

Keep the boundary-layer offsets in the tesselation and out of the extracted surface. The tesselation, the watershed and the labelling are bit-identical either way. Defaults to False.

False
guard_duplicate_faces bool

Offset-exclusion ablation switch — refuse the merges that would duplicate a face. False reproduces the unguarded construction, which trades 4 boundary edges for 38 fewer offsets on 3.tif. Defaults to True. Ignored under the "link_condition" collapse rule, which forbids the same thing.

True
collapse_rule str

"weld" merges every offset it can (the unconditional-merge rule, which regressed valence->=4 edges 115 -> 184 and abnormal non-manifold edges 7 -> 76), "link_condition" accepts only the merges that cannot change the surface topology. See dw3d.mesh_utilities.exclude_offsets_from_surface. Defaults to "weld" so that the unconditional-merge benchmark records stay reproducible; get_link_checked_algorithm is the link-condition configuration.

WELD

Returns:

Name Type Description
MeshReconstructionAlgorithm MeshReconstructionAlgorithm

a new algorithm, with junction relocation on.

get_link_checked_algorithm(min_distance: int = 3, print_info: bool = False, spline_order: int = 1) -> MeshReconstructionAlgorithm

Return the "revised meshing" variant: junction-protected with a topology-preserving offset collapse.

This was get_default_algorithm for a time, until the default went back to the dithered configuration because end-to-end tension-inference accuracy is worse with this pipeline than with the dithered one on every method measured, despite its better mesh quality in isolation (interface-area bias, sliver fraction, junction placement, topology -- see get_default_algorithm's docstring for the numbers). It is deterministic, junction-protected and topologically corrected relative to the dithered configuration; "link-checked" names its mechanism (a link-condition-checked, topology-preserving offset collapse). Use it when mesh geometry and topology matter more than today's downstream tension-inference accuracy. Its benchmark records are keyed on the variant name offset_excluded_linkcheck.

Identical to get_junction_protected_algorithm(exclude_offsets_from_surface=True) except that each offset is removed from the surface by a link-condition-checked edge contraction rather than an unconditional weld. Same EDT, same point set, same regular triangulation, same watershed, same mesh surgery, same set of candidate merges — only the test that decides which candidates are taken differs.

Why this exists. The unconditional weld bought a large geometric improvement (the offset-included default over-estimates every interface area by +15.7 %, the weld-based exclusion by +1.2 %) at the cost of a real topological regression: welding two vertices makes formerly distinct edges the same edge, so their triangle incidences add, and over the 51-case benchmark that took valence->=4 edges 115 -> 184 and abnormal non-manifold edges 7 -> 76. The link-condition-checked collapse refuses exactly the merges that would do that; see dw3d.mesh_utilities._refuse_by_link_condition for the four tests, and for the non-manifold counterexample showing why the classical link condition alone is not sufficient here.

It refuses fewer merges than the duplicate-face guard on the unconditional weld, not more, because retrying a refused candidate once its neighbours have collapsed recovers most of them.

Parameters:

Name Type Description Default
min_distance int

Minimum distance between extrema. Defaults to 3.

3
print_info bool

Print algorithm details while executing.

False
spline_order int

EDT interpolation order for the watershed scores; 3 composes this collapse rule with the cubic B-spline. Defaults to 1.

1

Returns:

Name Type Description
MeshReconstructionAlgorithm MeshReconstructionAlgorithm

a new algorithm, with junction relocation on.

compare_cell_volumes_with_mask

compare_cell_volumes_with_mask(segmented_mask: NDArray, points: NDArray[float64], triangles: NDArray[integer], labels: NDArray[integer], ratio_range: tuple[float, float] = CELL_VOLUME_RATIO_RANGE, *, media: tuple[int, ...] | list[int] = (0,)) -> CellVolumeReport

List every non-zero label whose mesh volume disagrees with its voxel count.

A label is listed when no triangle carries it ("absent"), when its mesh volume is <= 0 ("non-positive"), or when its mesh volume over voxel count is below ("below") or above ("above") the inclusive ratio_range, tested in that order.

Parameters:

Name Type Description Default
segmented_mask NDArray

the label image the mesh was reconstructed from; 0 is the medium.

required
points NDArray[float64]

mesh vertex coordinates in mask voxel units (before any pixel-size scaling, or the ratio is off by the voxel volume).

required
triangles NDArray[integer]

(m, 3) vertex indices.

required
labels NDArray[integer]

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

required
ratio_range tuple[float, float]

the inclusive range that is not listed.

CELL_VOLUME_RATIO_RANGE
media tuple[int, ...] | list[int]

the labels that are media, not cells (the exterior 0 and the enclosed media a reconstruction made, MeshReconstructionAlgorithm.medium_labels); never listed nor counted. Keyword-only. Defaults to (0,).

(0,)

Returns:

Name Type Description
CellVolumeReport CellVolumeReport

the listed labels, ascending, with their voxel count, volume and reason.

find_enclosed_media

find_enclosed_media(mask: NDArray[integer], min_inscribed_radius: float) -> tuple[NDArray, EnclosedMediumReport]

Give each enclosed pocket of label 0 lined by two or more cells, and deep enough, its own label.

Parameters:

Name Type Description Default
mask NDArray[integer]

the 3-D integer label mask; label 0 is the medium. Never modified.

required
min_inscribed_radius float

the smallest inscribed radius, in voxels, of a pocket that becomes its own region (the reconstruction uses its placement's min_distance + 1).

required

Returns:

Name Type Description
tuple NDArray

the mask to mesh (mask itself when no pocket becomes a region, else a relabelled copy whose dtype

EnclosedMediumReport

is widened if the new labels need it) and the report (absorbed_by of each pocket left is None here).

extract_junction_curves

extract_junction_curves(segmented_mask: NDArray[uint], points: NDArray[float64], triangles: NDArray[int64], labels: NDArray[int64], *, estimator: Estimator = 'plain') -> JunctionCurves

Trijunction curves from the mask, keyed to the mesh's own trijunctions.

The one line a user writes::

curves = extract_junction_curves(mask, *load_rec("000_mesh.rec"))

curves.matched is the usable set. Every one of its members has exactly one counterpart among the mesh's own trijunctions of the same material triple, so it can be joined to the interfaces and the dihedral angles the reconstruction already reports. curves.invented is everything the mask says is a junction and the mesh does not have; none of 27 of those were measured within one voxel of all three of their interfaces, against a median of 0.524 voxels for the matched ones, so they are kept apart rather than merged. curves.fragmented holds real trijunctions the mask resolves as several pieces.

Reading spacing is not a parameter: the polylines are resampled at the mesh's own median trijunction-edge length, so accuracy is compared at the resolution the mesh states its lines at rather than at whatever resolution the lattice happens to give.

Cost, and why "plain" is the default. "plain" is detection only -- no linear program -- and costs about 0.8 s per benchmark case against the 1.49 s dw3d spends reconstructing that case. "anchor" solves one small linear program per returned vertex and costs roughly fifteen times as much, about eight times the whole reconstruction it annotates, and buys 9-11 % of the position error. Nobody meshing a large tissue should pay that by default, so they do not.

"anchor"'s real argument is not that 9 %: it is that the polytope's deepest interior point carries only the irreducible narrow-wedge term (a) of the mask's identifiability floor, where the detected position and the centroid both carry more. Reach for it when a systematic bias against narrow wedges would corrupt what you are inferring, not to shave a tenth of a voxel. "centroid" is kept for comparison only: it was measured carrying (a) + (b), so it is the larger systematic, not the smaller one, and it costs about thirty times the anchor's linear programs on top.

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[int64]

triangle vertex indices, (m, 3).

required
labels NDArray[int64]

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

required
estimator Estimator

"plain" (default, no linear program), "anchor" or "centroid". See the cost paragraph above before changing it.

'plain'

Raises:

Type Description
ValueError

if estimator is not one of the three, or if the mesh's coordinates do not lie inside the mask's extent.

Returns:

Name Type Description
JunctionCurves JunctionCurves

the curves, the match rate, the identity counts and the diagnostics.

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.

resample_to_isotropic

resample_to_isotropic(mask: NDArray, spacing: tuple[float, float, float], method: str = 'shape') -> NDArray

Resample a label mask with one coarse axis to cubic voxels of the short spacing.

Parameters:

Name Type Description Default
mask NDArray

3-D integer label image (0 = medium or background).

required
spacing tuple[float, float, float]

voxel size along axes 0, 1, 2, so (dz, dy, dx) for a (z, y, x) stack (see the module's conventions).

required
method str

"shape" (default) or "nearest", see RESAMPLING_METHODS.

'shape'

Returns:

Type Description
NDArray

The resampled mask, same dtype, on cubic voxels of size isotropic_spacing(spacing). Along the coarse axis

NDArray

it has floor((n - 1) k) + 1 voxels for n input voxels. **When the voxels are already cubic the input

NDArray

array itself is returned**, unchanged and uncopied, so an isotropic mask goes through bitwise.

Raises:

Type Description
ValueError

for an unknown method, a mask that is not 3-D, or an unsupported spacing.

The shape-based method (Raya & Udupa, 1990): for every label, including 0, its 2-D signed distance is computed on every input slice across the coarse axis (positive inside, zero half-way between voxel centres) and interpolated linearly between slice centres; each output voxel takes the label with the largest value, ties to the smaller label. Where a label is present in one slice and absent from the next, the absent slice's value is min(d - k, -1/2) (d the present slice's): the surface keeps closing at one voxel per voxel, but never reaches the centre of a slice where the mask says the label is absent. Known bias: linear interpolation of a concave distance profile underestimates it, so small convex cells shrink slightly (measured on balls of radius 9-14 voxels: -1 to -5 % of their volume at k = 3, -5 to -11 % at k = 4). Each label is computed only in its bounding box (SHAPE_INTERPOLATION_MARGIN), so the cost grows with the cells' volume, not with the number of labels times the volume: about 40 s and 23 GiB for a 1 866-cell tissue of 4.98e8 voxels at k = 5/3. The measurements behind the choice are summarised in the module docstring.

reconstruct_mask_from_dict

reconstruct_mask_from_dict(dict_mask: dict[str]) -> NDArray[np.int64]

Reconstruct a segmentation image from a saved dict of points, triangles, seeds coords and desired image shape.

Each voxel centre takes the label of the region of space the mesh's triangles enclose it in: two neighbouring centres are in the same region when the segment between them crosses no triangle, and a region takes the index of the seed it holds. A centre lying exactly on a triangle belongs to the region it enters when moved infinitesimally towards increasing index along axis 0, then 1, then 2 (towards decreasing index on the last voxel of an axis, so that a cell cut by the image box keeps its outermost voxels). A region holding no seed (a few centres cut off by a sliver thinner than a voxel) takes the label of the region it shares the most neighbouring centres with. Every test is exact, so the result does not depend on the NumPy or SciPy version.

Parameters:

Name Type Description Default
dict_mask dict[str]

the dictionary MeshReconstructionAlgorithm.last_compressed_segmentation returns, with keys points, triangles, seeds and image_shape. The points must be in voxel units of the mask, as the reconstruction returns them (not scaled by set_pixel_size or built by construct_mesh_in_physical_units). After construct_mesh_in_physical_units, divide the points by the resampled spacing (the shortest spacing) first: the seeds and image_shape are those of the resampled cubic grid, and that is the mask this rebuilds.

required

Returns:

Type Description
NDArray[int64]

NDArray[np.int64]: the rebuilt mask, of shape image_shape, in 64-bit integer labels (not the original mask's dtype). Seed k (in the ascending label order of the original mask, label 0 included when present) fills its region with label k, so the labels are those of the original mask only when these were 0, 1, ..., n - 1.

reconstruct_mask_from_saved_file_dict

reconstruct_mask_from_saved_file_dict(filename_dict: str) -> NDArray[np.int64]

Reconstruct a segmentation image from a saved dict of points, triangles, seeds coords and desired image shape.

Parameters:

Name Type Description Default
filename_dict str

a .npy file written by dw3d.save_compressed_segmentation. It is unpickled (allow_pickle=True), so read only files you trust.

required

Returns:

Type Description
NDArray[int64]

NDArray[np.int64]: the rebuilt mask, as reconstruct_mask_from_dict returns it.

count_self_intersections

count_self_intersections(points: NDArray[float64], triangles: NDArray[integer]) -> dict

The nonlocal self-intersection counts, without the pair arrays.

A thin, JSON-serialisable projection of :func:find_self_intersections carrying exactly :data:SELF_INTERSECTION_KEYS and no array.

Parameters:

Name Type Description Default
points NDArray[float64]

vertex coordinates, the mesh's own units.

required
triangles NDArray[integer]

triangle vertex indices.

required

Returns:

Name Type Description
dict dict

the six keys of :data:SELF_INTERSECTION_KEYS. A count, never a score.

find_self_intersections

find_self_intersections(points: NDArray[float64], triangles: NDArray[integer]) -> dict

Every nonlocal triangle-triangle intersection of one surface mesh, and the pairs themselves.

Parameters:

Name Type Description Default
points NDArray[float64]

vertex coordinates, the mesh's own units.

required
triangles NDArray[integer]

triangle vertex indices, (m, 3).

required

Returns:

Name Type Description
dict dict

the six counts of :data:SELF_INTERSECTION_KEYS plus intersecting_pairs and touching_pairs, each an (k, 2) array of indices into the input triangles, so a caller can draw or diagnose a specific crossing. Degenerate triangles are excluded from the test and counted.

center_points_around_zero

center_points_around_zero(points: NDArray[float64]) -> NDArray[np.float64]

Translate mesh points so that the centre of their bounding box is the origin.

Parameters:

Name Type Description Default
points NDArray[float64]

(n, 3) mesh points.

required

Returns:

Type Description
NDArray[float64]

NDArray[np.float64]: a new (n, 3) array; points is not modified.

set_points_pixel_size

set_points_pixel_size(points: NDArray[float64], xy_pixel_size: float, z_pixel_size: float) -> NDArray[np.float64]

Scale points from voxel coordinates to physical coordinates, given the microscope's xy and z pixel sizes.

The points are in the mask's (z, y, x) index order: column 0 is scaled by z_pixel_size, columns 1 and 2 by xy_pixel_size (see dw3d.mesh_utilities.set_pixel_size). Changed in 0.7.0: before, z was multiplied by the xy size and x by the z size. For a mask whose voxels are longer along z, prefer MeshReconstructionAlgorithm.construct_mesh_in_physical_units, which is more accurate.

Parameters:

Name Type Description Default
points NDArray[float64]

(n, 3) mesh points in voxel units, (z, y, x) order.

required
xy_pixel_size float

the pixel size in the image plane, which multiplies columns 1 and 2.

required
z_pixel_size float

the z step, which multiplies column 0.

required

Returns:

Type Description
NDArray[float64]

NDArray[np.float64]: a new (n, 3) array; points is not modified.

set_points_global_min_max

set_points_global_min_max(points: NDArray[float64], global_min: float, global_max: float) -> NDArray[np.float64]

Scale and shift points, by one factor on every axis, so their coordinates span [global_min, global_max].

The minimum and maximum are taken over all coordinates of all points together, not per axis, so the shape is kept: the smallest coordinate becomes global_min and the largest global_max.

Parameters:

Name Type Description Default
points NDArray[float64]

(n, 3) mesh points.

required
global_min float

the new smallest coordinate.

required
global_max float

the new largest coordinate.

required

Returns:

Type Description
NDArray[float64]

NDArray[np.float64]: a new (n, 3) array; points is not modified.

save_mesh_to_rec_mesh

save_mesh_to_rec_mesh(points: NDArray[float64], triangles: NDArray[int64], labels: NDArray[int64], filename: str | Path, binary_mode: bool = False, crop_faces: NDArray[bool_] | None = None) -> None

Save a mesh on disk in the rec format.

crop_faces (the algorithm's crop_faces), when given, puts the crop faces in the last block of triangle rows and records the block in the file's appendix; see dw3d.io.save_rec. No other metadata is written: MeshReconstructionAlgorithm.save_to_rec_mesh also records the physical frame and the physical image faces.

Parameters:

Name Type Description Default
points NDArray[float64]

(n, 3) mesh points, written as given.

required
triangles NDArray[int64]

(m, 3) vertex indices.

required
labels NDArray[int64]

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

required
filename str | Path

where to write the file.

required
binary_mode bool

write the binary variant of the format. Defaults to False.

False
crop_faces NDArray[bool_] | None

(m,) bool, True on the crop faces. Defaults to None, which writes no appendix.

None

save_mesh_to_vtk_mesh

save_mesh_to_vtk_mesh(points: NDArray[float64], triangles: NDArray[int64], labels: NDArray[int64], filename: str | Path, binary_mode: bool = False, crop_faces: NDArray[bool_] | None = None) -> None

Save a mesh on disk in the vtk format (or any format meshio infers from the file extension).

crop_faces, when given, is written as the cell array crop_face; see dw3d.io.save_vtk.

Parameters:

Name Type Description Default
points NDArray[float64]

(n, 3) mesh points, written as given.

required
triangles NDArray[int64]

(m, 3) vertex indices.

required
labels NDArray[int64]

(m, 2) the two regions each triangle separates, written as the cell arrays label1 and label2.

required
filename str | Path

where to write the file.

required
binary_mode bool

write a binary file. Defaults to False.

False
crop_faces NDArray[bool_] | None

(m,) bool, True on the crop faces. Defaults to None.

None

save_compressed_segmentation

save_compressed_segmentation(filename: str | Path, compressed_segmentation: dict[str]) -> None

Save a compressed segmentation on disk with numpy.save.

The dictionary is pickled into a .npy file (numpy adds the extension when filename has none). Read it back with reconstruct_mask_from_saved_file_dict.

Parameters:

Name Type Description Default
filename str | Path

where to write the file.

required
compressed_segmentation dict[str]

the dictionary MeshReconstructionAlgorithm.last_compressed_segmentation returns.

required