Reconstruction algorithms¶
Build mesh reconstruction algorithms: the named configurations and a factory for custom ones.
MeshReconstructionAlgorithmFactory's static get_*_algorithm methods return the named
configurations (get_default_algorithm is the one to use for tension inference); an instance of
the factory combines the steps one by one and make_algorithm builds the result.
Matthieu Perez 2024
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. |
The mesh reconstruction algorithm: from a 3-D segmentation mask to a multimaterial surface mesh.
MeshReconstructionAlgorithm runs the pipeline (distance transform, point placement, tesselation,
seeded watershed, mesh extraction and surgery, crop-face marking, junction relocation, cell-volume
check) and keeps the last mesh it built. Get one from dw3d.MeshReconstructionAlgorithmFactory or
dw3d.get_default_mesh_reconstruction_algorithm.
Sacha Ichbiah 2021 Matthieu Perez 2024
MeshReconstructionAlgorithm ¶
MeshReconstructionAlgorithm(print_info: bool, edt_creation_function: EdtCreationFunction, point_placing_function: PointPlacingFunction, tesselation_creation_function: TesselationCreationFunction, score_computation_function: ScoreComputationFunction, perform_mesh_postprocess_surgery: bool, relocate_junctions: bool = True, physical_image_faces: tuple[str, ...] = (), canonical_tetrahedron_order: bool = True, label_enclosed_media: bool = True, pad_thin_medium_margins: bool = True)
Algorithm that builds a multimaterial surface mesh from a 3-D segmentation mask (and a 2-D mesh from a 2-D one).
A 2-D mask given to construct_mesh_from_segmentation_mask or construct_mesh_in_physical_units is meshed by
dw2d (imported then, on first use): the algorithm builds a dw2d.MeshReconstructionAlgorithm from its settings
that have a 2-D meaning (min_distance, junction relocation, canonical order, print_info) and returns dw2d's
(points (n, 2), segments (m, 2), labels (m, 2)). Until the object meets a 3-D mask again, last_constructed_mesh,
last_compressed_segmentation, save_to_rec_mesh, relocation_report, cut_cells and medium_labels are dw2d's,
two_dimensional_algorithm is that object, and the 3-D-only reports (crop_faces, crop_face_report,
cell_volume_report, enclosed_medium_report) are None. min_distance is the one given to the factory, or
dw2d's default (4 pixels) when none was given (requested_min_distance). A configuration with no 2-D meaning
(boundary-layer, junction-protected or link-checked placement, another EDT, tesselation or face score, physical
image faces, mesh surgery off) raises ValueError naming it; the default (dithered) and the deterministic
placements are both meshed by dw2d's placement, which has no dither. See _mask_dimension for the input checks.
Build one with dw3d.MeshReconstructionAlgorithmFactory (or one of its get_*_algorithm
methods) rather than by calling the constructor. The same object can reconstruct several
masks; each reconstruction replaces the last mesh and every report about it.
The mesh is (points, triangles, labels): points (n, 3) float64, in the mask's index order
((z, y, x) for a (z, y, x) stack) and in voxel units unless built by
construct_mesh_in_physical_units; triangles (m, 3) vertex indices; labels (m, 2), the
two regions each triangle separates, smaller label first, label 0 being the medium.
Attributes:
| Name | Type | Description |
|---|---|---|
print_info |
bool
|
whether to print the timing of each step. |
relocate_junctions |
bool
|
whether the next reconstruction runs junction relocation. |
canonical_tetrahedron_order |
bool
|
whether the next reconstruction puts the tetrahedra in
canonical order before anything reads them; see |
physical_image_faces |
tuple[str, ...]
|
the image faces declared physical; see |
Set the methods used by this algorithm to reconstruct a mesh from a segmentation mask.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
print_info
|
bool
|
Whether to show details about the computation during the algorithm's execution. |
required |
edt_creation_function
|
EdtCreationFunction
|
Function used to compute an EDT from the segmentation mask. |
required |
point_placing_function
|
PointPlacingFunction
|
Function used to place points on the EDT for a tesselation. |
required |
tesselation_creation_function
|
TesselationCreationFunction
|
Function used to tesselate the points. |
required |
score_computation_function
|
ScoreComputationFunction
|
Function used to compute the scores for Watershed. |
required |
perform_mesh_postprocess_surgery
|
bool
|
Whether to try to detect and fix problems on the output mesh. |
required |
relocate_junctions
|
bool
|
Whether to move the finished mesh's trijunction vertices onto
the trijunction curves the mask itself gives, as a post-process. Defaults to
|
True
|
physical_image_faces
|
tuple[str, ...]
|
the faces of the image box, among
|
()
|
canonical_tetrahedron_order
|
bool
|
Whether to put the tesselation's tetrahedra in
canonical order ( |
True
|
label_enclosed_media
|
bool
|
Whether an enclosed pocket of label 0 (a lumen, a cavity: a 6-connected
piece of label 0 touching no face of the array) becomes its own region, flagged as a medium, when
its inscribed radius is at least the placement's |
True
|
pad_thin_medium_margins
|
bool
|
Whether a mask whose first mesh has a vertex on a face of the image box
that no cell reaches is meshed again, padded with label 0 on every such face whose margin is below
|
True
|
medium_margin_padding
property
¶
medium_margin_padding: dict[str, int] | None
The label-0 padding the last reconstruction added to the mask's image faces, in voxels, by face name.
Empty when the mask was meshed as given (the common case); None before any reconstruction. After a 2-D mask,
dw2d's (sides, in pixels). Faces are padded only when the first mesh had a vertex on an image face no cell
reaches; see dw3d.thin_medium_margins and pad_thin_medium_margins.
crop_faces
property
¶
crop_faces: NDArray[bool_] | None
Which triangles of the last constructed mesh are crop faces.
A crop face is a triangle on a face of the image box that was not declared physical
(physical_image_faces) and that the mask's cell reaches: the cell it closes goes on
beyond the image, so the triangle is not contact with the medium, and no tension or angle
should be read on it. A triangle the reconstruction put on an image face the mask's cell
does not reach stays contact with the medium. foambryo
reads this mask (DcelData(..., crop_faces=...)) and keeps crop faces, and every
junction edge and vertex that touches them, out of its equations.
Returns:
| Type | Description |
|---|---|
NDArray[bool_] | None
|
NDArray[np.bool_] | None: |
NDArray[bool_] | None
|
|
NDArray[bool_] | None
|
mask reaches a crop image face. |
cut_cells
property
¶
cut_cells: tuple[int, ...] | None
The cells of the last constructed mesh that the crop cuts.
A cell is cut when it has a crop face or a vertex on one. Its volume and part of its surface were not observed, so its pressure is not a measurement.
Returns:
| Type | Description |
|---|---|
tuple[int, ...] | None
|
tuple[int, ...] | None: sorted labels; empty when nothing is cut; |
tuple[int, ...] | None
|
first reconstruction. |
crop_face_report
property
¶
crop_face_report: CropFaceReport | None
The crop faces, the image face of each border triangle and the cut cells; None before a reconstruction.
enclosed_medium_report
property
¶
enclosed_medium_report: EnclosedMediumReport | None
The pieces of medium of the last reconstruction, or None before any.
Returns:
| Type | Description |
|---|---|
EnclosedMediumReport | None
|
dw3d.enclosed_media.EnclosedMediumReport | None: the enclosed media made ( |
medium_labels
property
¶
medium_labels: tuple[int, ...]
The labels of the last mesh that are media, not cells: 0 first, then the enclosed media; (0,) before any.
Returns:
| Type | Description |
|---|---|
tuple[int, ...]
|
tuple[int, ...]: ascending after 0. A mask without label 0 has no 0 here. |
cell_volume_report
property
¶
cell_volume_report: CellVolumeReport | None
The cells of the last constructed mesh whose volume disagrees with their voxel count.
A cell is listed when its mesh volume over its voxel count is outside [0.5, 1.5], when its
mesh volume is not positive, or when no triangle carries it. Computed on the mesh as
construct_mesh_from_segmentation_mask returned it, in voxel units of the grid it was meshed
on, before any later pixel-size scaling.
Returns:
| Type | Description |
|---|---|
CellVolumeReport | None
|
dw3d.cell_volume_agreement.CellVolumeReport | None: the listed cells with their voxel
count, mesh volume, ratio and reason, or |
placement_min_distance
property
¶
placement_min_distance: int | None
The point placement's min_distance, or None when it cannot be read.
The factory's placements are functools.partial objects carrying min_distance as a
keyword; a custom placement callable carries none, and then this is None and
CoarseSpacingRelocationWarning is never emitted.
Returns:
| Type | Description |
|---|---|
int | None
|
int | None: the minimum distance between placed points, in voxels of the grid the mask is meshed on. |
relocation_provenance
property
¶
relocation_provenance: dict
Whether junction relocation ran on the last constructed mesh, with which guard, and what it warned.
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict
|
|
dict
|
last mesh), |
|
dict
|
|
|
dict
|
fired for the last mesh) and |
|
dict
|
when it did not run). JSON-serialisable. |
relocation_report
property
¶
relocation_report: JunctionRelocationReport | JunctionRelocationReport | None
What the junction relocation did on the last constructed mesh, or None if it was off.
Returns:
| Type | Description |
|---|---|
JunctionRelocationReport | JunctionRelocationReport | None
|
dw3d.junction_relocation.JunctionRelocationReport | dw2d.JunctionRelocationReport | None: the accepted and refused move counts, the displacement distribution, and the whole-mesh self-intersection count before and after (for a 2-D mask, the 2-D algorithm's report). |
last_constructed_mesh
property
¶
last_constructed_mesh: tuple[NDArray[float64], NDArray[uint], NDArray[uint]]
The last mesh built, (points, triangles, labels), after any later scaling or centring.
These are the algorithm's own arrays, not copies: modifying them modifies the mesh that
save_to_rec_mesh and save_to_vtk_mesh write. After a 2-D mask, dw2d's (points, segments, labels).
two_dimensional_algorithm
property
¶
two_dimensional_algorithm
The dw2d.MeshReconstructionAlgorithm that meshed the last mask when it was 2-D, else None.
last_compressed_segmentation
property
¶
last_compressed_segmentation: dict[str]
The last mesh's points and triangles, the watershed seeds and the mask's shape, as a dictionary.
Keys: points, triangles, seeds (one voxel index per label of the mask, label 0 included when present,
in ascending label order) and image_shape. Save it with dw3d.save_compressed_segmentation
(numpy.save). dw3d.reconstruct_mask_from_dict expects the points in voxel units of the
mask, so read this before any scaling (set_pixel_size, set_global_min_max).
The frame of each entry:
pointsare the mesh's current points,last_constructed_mesh[0]itself: voxel indices of the meshed grid afterconstruct_mesh_from_segmentation_mask, but in physical units (the unit ofspacing) afterconstruct_mesh_in_physical_units, and as scaled by any laterset_pixel_size,set_global_min_maxorcenter_around_zero.seedsandimage_shapeare always voxel indices and the shape of the grid that was meshed. Afterconstruct_mesh_in_physical_unitsthat is the mask resampled to cubic voxels ofresampled_spacing(the shortest spacing), not the mask that was passed in.
So after construct_mesh_in_physical_units the points are not in the frame of the seeds: divide them by
resampled_spacing before dw3d.reconstruct_mask_from_dict, which then rebuilds the resampled cubic-grid
mask. Passed as they are, the mesh is rasterised at the wrong scale (measured on a two-cell mask with
spacing (0.6, 0.3, 0.3): 7 % of voxels agree with the resampled mask, against 96 % after the division).
construct_mesh_from_segmentation_mask ¶
construct_mesh_from_segmentation_mask(segmented_image: NDArray[uint]) -> tuple[NDArray[np.float64], NDArray[np.uint], NDArray[np.uint]]
Build a 3D mesh from a segmentation mask.
The mask is meshed on its own voxel grid, whatever its voxel size: for a mask whose voxels
are longer along one axis, use construct_mesh_in_physical_units. The point placement's
min_distance counts voxels of this grid.
After the call, last_constructed_mesh, crop_faces, cut_cells, crop_face_report,
cell_volume_report, relocation_report and relocation_provenance describe this mesh,
and save_to_rec_mesh writes no physical frame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
segmented_image
|
NDArray[uint]
|
the 3-D integer label mask; label 0 is the medium, every other label a cell. |
required |
Returns:
| Type | Description |
|---|---|
tuple[NDArray[float64], NDArray[uint], NDArray[uint]]
|
tuple[NDArray[np.float64], NDArray[np.uint], NDArray[np.uint]]: |
Warns:
| Type | Description |
|---|---|
CoarseSpacingRelocationWarning
|
once, when junction relocation is on and the point
placement's |
CellVolumeDisagreementWarning
|
once, when some cells' mesh volume disagrees with their
voxel count (see |
AbnormalEdgeWarning
|
once, when the finished mesh has abnormal non-manifold edges, with their number and the configuration. |
UnresolvedCellWarning
|
once, when a label of the mask is absent from the finished mesh,
whatever the cause, naming each such region (see |
ThinMediumMarginWarning
|
once, when a cell's mesh lies on a face of the image box that its voxels do
not reach and that could not be padded (see |
A mask whose first mesh has a vertex on an image face that no cell reaches is meshed a second time, padded
with label 0 on the faces no cell reaches (pad_thin_medium_margins, medium_margin_padding); the mesh, the
reports and last_compressed_segmentation are in the mask's frame either way.
Raises:
| Type | Description |
|---|---|
ValueError
|
for a mask that is neither 2-D nor 3-D, or a 3-D mask with an axis of length 1 (pass
|
ImportError
|
for a 2-D mask when dw2d is not installed ( |
construct_mesh_in_physical_units ¶
construct_mesh_in_physical_units(segmented_image: NDArray[uint], spacing: tuple[float, float, float], *, resampling: str = 'shape', spacing_unit: str | None = None, axis_order: str = 'zyx', pad_thin_medium_margins: bool | None = None) -> tuple[NDArray[np.float64], NDArray[np.uint], NDArray[np.uint]]
Build a mesh, in physical units, from a mask whose voxels may be longer along one axis.
The mask is first resampled to cubic voxels of the shortest spacing by
dw3d.mask_preprocessing.resample_to_isotropic (shape-based interpolation by default), then meshed by
construct_mesh_from_segmentation_mask with this algorithm's settings unchanged (min_distance counts voxels
of the resampled cubic grid), and the mesh is scaled to physical units: a point at voxel index i of the
cubic grid is at i * h, h = min(spacing), so the centre of the mask's first voxel is the origin. The
columns stay in the mask's index order, (z, y, x) for a (z, y, x) stack.
Why resample rather than mesh the native grid and scale it: measured on 12 simulated tissues of 90 and 165
cells at a real cell size, down-sampled along z, against the same tissues meshed at full resolution,
meshing the native grid costs +1.38, +1.97 and +4.10 degrees of contact-angle error at k = 5/3, 2 and 3
(k = long spacing / short spacing), and resampling first +0.83, +0.71 and +1.17 (on dw3d 0.7.0's meshes,
before 0.8.0 pads thin margins of medium on the native grid; not measured again); see
dw3d.mask_preprocessing. The cost is that of a mask acquired at the short spacing: k times the voxels.
The reports (crop_faces, cut_cells, crop_face_report, cell_volume_report, relocation_report)
describe the mesh on the resampled cubic grid, in its voxel units, before the scaling.
After this call save_to_rec_mesh writes, in the file's metadata appendix, coordinate_frame = physical,
axis_order, spacing (the mask's own voxel size, which the mesh coordinates are already scaled by),
spacing_unit when given, source_shape, resampling and resampled_spacing. Any later reconstruction
clears them. Do not call set_pixel_size on the result: it is already in physical units.
last_compressed_segmentation then holds the physical points with the seeds and the shape of the resampled
cubic grid: divide its points by resampled_spacing before dw3d.reconstruct_mask_from_dict (see that
property).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
segmented_image
|
NDArray[uint]
|
the 3-D integer label mask; label 0 is the medium. |
required |
spacing
|
tuple[float, float, float]
|
voxel size along the mask's axes 0, 1, 2, so |
required |
resampling
|
str
|
|
'shape'
|
spacing_unit
|
str | None
|
the unit of |
None
|
axis_order
|
str
|
what the mask's axes are, recorded, not used. Defaults to |
'zyx'
|
pad_thin_medium_margins
|
bool | None
|
whether thin medium margins are padded (see the class's
option of that name), for this call only. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
tuple[NDArray[float64], NDArray[uint], NDArray[uint]]
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
for a spacing that is not three positive finite numbers or has two different fine axes, an
unknown |
Warns:
| Type | Description |
|---|---|
UnmeasuredAnisotropyWarning
|
when the voxels are more than |
CoarseSpacingRelocationWarning
|
as in |
CellVolumeDisagreementWarning
|
as in |
AbnormalEdgeWarning
|
as in |
compress_segmentation_mask ¶
compress_segmentation_mask(segmented_image: NDArray[uint]) -> dict[str]
Compress a segmentation mask using a 3D mesh reconstruction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
segmented_image
|
NDArray[uint]
|
the 3-D integer label mask; label 0 is the medium. |
required |
Returns:
| Type | Description |
|---|---|
dict[str]
|
dict[str]: the compressed segmentation (see |
both_construct_mesh_and_compressed_segmentation ¶
both_construct_mesh_and_compressed_segmentation(segmented_image: NDArray[uint]) -> tuple[NDArray[np.float64], NDArray[np.uint], NDArray[np.uint], dict[str, Any]]
Construct and return a 3D mesh from segmentation and obtain the dictionary of the compressed segmentation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
segmented_image
|
NDArray[uint]
|
the 3-D integer label mask; label 0 is the medium. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
tuple[NDArray[float64], NDArray[uint], NDArray[uint], dict[str, Any]]
|
four items, |
center_around_zero ¶
center_around_zero() -> None
Translate the mesh, in place, so that the centre of its bounding box is the origin.
set_pixel_size ¶
set_pixel_size(xy_pixel_size: float, z_pixel_size: float) -> None
Scale the mesh, in place, from voxel coordinates to physical coordinates, given the xy and z pixel sizes.
The mesh 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
construct_mesh_in_physical_units, which is more accurate; do not call this method on its result, which is
already in physical units. The reports (cell_volume_report, crop_face_report, ...) are not rescaled.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
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 |
set_global_min_max ¶
set_global_min_max(global_min: float, global_max: float) -> None
Scale and shift the mesh in place, one factor on all axes, so it spans [global_min, global_max].
The minimum and maximum are taken over all coordinates together, not per axis, so the shape is kept.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
global_min
|
float
|
the new smallest coordinate. |
required |
global_max
|
float
|
the new largest coordinate. |
required |
save_to_rec_mesh ¶
save_to_rec_mesh(filename: str | Path, binary_mode: bool = False) -> None
Save the last mesh on disk in the rec format, with its current points.
A mesh made by construct_mesh_in_physical_units gets its physical frame recorded in the file's metadata
appendix (see that method); a mesh made by construct_mesh_from_segmentation_mask gets none.
When the mesh lies on an image face that one of its cells reaches in the mask, the crop
faces are written as the last block of triangles and the file's metadata appendix
records crop_faces = <first row> <count> and physical_image_faces, so the triangle rows
of the file differ in order from last_constructed_mesh. Read them back with
dw3d.io.load_rec_with_crop_faces. Otherwise (in particular for every mask none of whose
cells reaches the image box) the file is byte for byte what it was before crop faces were
recorded. Whenever an appendix is written it records dimension = 3 (since 0.8.0), so that
readers can tell the file from a 2-D one without probing its layout (dw3d.io.rec_dimension).
After a 2-D mask, dw2d's save_to_rec_mesh writes the file (with dimension = 2).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
str | Path
|
where to write the file ( |
required |
binary_mode
|
bool
|
write the binary variant of the format. Defaults to False. |
False
|
save_to_vtk_mesh ¶
save_to_vtk_mesh(filename: str | Path, binary_mode: bool = False) -> None
Save the last mesh on disk in the vtk format, with its current points.
When the mesh lies on an image face that one of its cells reaches in the mask, a
crop_face cell array (1 on crop faces) is written beside label1 and label2; otherwise
the file is what it was before. No physical frame is recorded.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
str | Path
|
where to write the file; meshio picks the format from its extension. |
required |
binary_mode
|
bool
|
write a binary file. Defaults to False. |
False
|
Raises:
| Type | Description |
|---|---|
ValueError
|
when the mesh has no triangle (nothing is written; |
save_compressed_segmentation ¶
save_compressed_segmentation(filename: str | Path, compressed_segmentation: dict[str]) -> None
Save a compressed segmentation on disk with numpy.save (same as dw3d.save_compressed_segmentation).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
str | Path
|
where to write the file; numpy adds |
required |
compressed_segmentation
|
dict[str]
|
the dictionary |
required |