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
0is the medium (the outside of the tissue), every other label is a cell. - Mesh points are in the mask's index order: column
iofpointsis the position along the mask's axisi. For a microscope stack stored as(z, y, x), the order dw3d assumes, the points are(z, y, x).construct_mesh_from_segmentation_maskreturns them in voxel units: the centre of voxel(i, j, k)is the point(i, j, k). spacingis 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), witha < b, are the two regions trianglenseparates; its normal (right-hand rule on its three vertices) points out ofaand intob: each triangle is the positively oriented boundary ofa. 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
module-attribute
¶
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 |
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_]
|
|
image_face_of_triangle |
NDArray[int64]
|
|
cell_reaches_image_face |
NDArray[bool_]
|
|
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_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 |
n_border_triangles
property
¶
n_border_triangles: int
Border triangles, crop faces and border triangles on physical image faces together.
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; |
min_distance |
int | None
|
the point placement's |
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.
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 |
lining_cells |
tuple[int, ...]
|
the labels 6-adjacent to it, ascending. |
reason |
str
|
|
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). |
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
CellVolumeDisagreementWarninglisted 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
|
|
cause |
str
|
|
tetrahedra_after_the_watershed |
int | None
|
how many tetrahedra the watershed gave it ( |
tetrahedra_in_its_voxels |
int | None
|
how many tetrahedra have their centroid in its voxels ( |
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 |
points |
NDArray[float64]
|
the ordered polyline, shape |
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
|
|
component |
int
|
index of this component within its triple, ordered by decreasing arclength. |
n_estimated |
int
|
how many of |
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 |
match_rate |
float | None
|
matched mesh trijunctions over all mesh trijunctions. Measured 0.900 at
|
counts |
dict[str, int]
|
|
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 -- |
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 |
n_self_intersections_after |
int | None
|
whole-mesh crossings after the pass, or |
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 |
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 |
()
|
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
|
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 |
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 |
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 |
256
|
halo
|
int
|
Initial halo; tiles escalate once if they need more. |
16
|
parallel
|
int
|
Threads for |
1
|
dtype
|
type
|
|
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 |
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
|
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
|
None
|
junction_spacing
|
float | None
|
Arclength |
None
|
shell_coarsening
|
int
|
Re-pack the bounding-box / background shell
minima at this multiple of |
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 |
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_algorithmat 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 synonymget_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
|
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 withjunction_boundary_layer=Trueso 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
|
None
|
junction_spacing
|
float | 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
|
None
|
junction_delta
|
float | None
|
Junction boundary-layer offset
distance. Defaults to |
None
|
protect_junctions
|
bool
|
Ablation switch; see
|
True
|
junction_boundary_layer
|
bool
|
Ablation switch; |
False
|
use_weights
|
bool
|
Ablation switch — |
True
|
spline_order
|
int
|
EDT interpolation order for the watershed scores;
|
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. |
True
|
collapse_rule
|
str
|
|
WELD
|
Returns:
| Name | Type | Description |
|---|---|---|
MeshReconstructionAlgorithm |
MeshReconstructionAlgorithm
|
a new algorithm, with junction relocation on. |
get_link_checked_algorithm
staticmethod
¶
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;
|
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]
|
|
required |
labels
|
NDArray[integer]
|
|
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, |
(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 |
required |
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
NDArray
|
the mask to mesh ( |
EnclosedMediumReport
|
is widened if the new labels need it) and the report ( |
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, |
required |
triangles
|
NDArray[int64]
|
triangle vertex indices, |
required |
labels
|
NDArray[int64]
|
the two materials each triangle separates, |
required |
estimator
|
Estimator
|
|
'plain'
|
Raises:
| Type | Description |
|---|---|
ValueError
|
if |
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, |
required |
triangles
|
NDArray[integer]
|
triangle vertex indices, |
required |
labels
|
NDArray[integer]
|
the two materials each triangle separates, |
required |
estimator
|
Estimator
|
which sub-voxel estimator
:func: |
'plain'
|
curves
|
JunctionCurves | None
|
a precomputed :class: |
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]
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
propagated from the extractor if the mesh does not lie in the mask's frame. |
RuntimeError
|
if |
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 ( |
required |
spacing
|
tuple[float, float, float]
|
voxel size along axes 0, 1, 2, so |
required |
method
|
str
|
|
'shape'
|
Returns:
| Type | Description |
|---|---|
NDArray
|
The resampled mask, same dtype, on cubic voxels of size |
NDArray
|
it has |
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 |
required |
Returns:
| Type | Description |
|---|---|
NDArray[int64]
|
NDArray[np.int64]: the rebuilt mask, of shape |
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 |
required |
Returns:
| Type | Description |
|---|---|
NDArray[int64]
|
NDArray[np.int64]: the rebuilt mask, as |
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: |
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, |
required |
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict
|
the six counts of :data: |
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]
|
|
required |
Returns:
| Type | Description |
|---|---|
NDArray[float64]
|
NDArray[np.float64]: a new |
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]
|
|
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 |
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]
|
|
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 |
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]
|
|
required |
triangles
|
NDArray[int64]
|
|
required |
labels
|
NDArray[int64]
|
|
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
|
|
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]
|
|
required |
triangles
|
NDArray[int64]
|
|
required |
labels
|
NDArray[int64]
|
|
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
|
|
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
|
required |