Repository navigation
feat(feature): mesh features on the GPU (CUDA marching cubes, ArrayMesh) - #63
alxndrkalinin wants to merge 87 commits into
Conversation
aics_workflows kept a private Gaussian that runs each pass on a float64 copy on the GPU, so that cupyx rounds like SciPy, which accumulates float32 input in float64. The mesh curvature blur needs the same bitwise parity with a different mode and truncation, so the filter is now image_utils.gaussian_filter_like_scipy(image, sigma, mode, truncate), and _gaussian_nearest calls it with mode="nearest", truncate=3. Measured bitwise equal to scipy.ndimage.gaussian_filter for reflect/truncate=4 at sigmas (1.5,4,4), (2,7.39,7.39) and (2,2,2), where plain cupyx differs by up to 1.8e-7. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
cuCIM has no marching cubes, so the GPU mesh path needs its own. This ports scikit-image's Cython implementation to CUDA kernels that run on scikit-image's own lookup tables and the same face and interior ambiguity tests, in three passes: classify each cube and mark the edges and cube centres it uses; number them by prefix sum and compute the vertices; write each cube's triangles. An edge vertex depends only on its edge's two corner values (the reference's interpolation sums the same two terms in whichever cube creates it), so with float64 corner arithmetic in the reference's operation order and --fmad=false the vertices round to skimage's float32 values. Measured identical to skimage up to vertex and face order, including orientation and output dtype: binary noise 40^3 (all 14 Lewiner cases, 99,337 vertices / 232,154 faces), continuous noise 64^3 (401,937 / 878,906), blurred noise, anisotropic balls, and volumes with exact level hits with and without degenerate-face removal. 64^3: 88 ms on an A40 shared with another job, against 1.7 s for skimage. allow_degenerate=False merges coincident vertices by a lexicographic sort; cp.unique(axis=0) took hours on a few thousand vertices. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
The mesh feature registry reads trimesh attributes. ArrayMesh provides the ones it uses (face areas and normals, mass properties and inertia, Euler number, face adjacency with dihedral angles and convexity, integral mean curvature, face angles and angle defects), computed with trimesh's own formulas on NumPy or CuPy arrays, so the features run on whichever device holds the mesh. Anything else (convex hull, bounding box, cylinder and sphere, QEM decimation) goes to a trimesh.Trimesh built on the host on first use. A mesh with negative enclosed volume is flipped, as trimesh.repair.fix_normals does for consistent winding. On NumPy arrays every feature matches trimesh to 1.7e-16 relative or better on a ball, a hollow ball and a 58k-vertex VPA nucleus. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
extract_features, extract_surface_features and mask2mesh now keep a CuPy label image or mask on the GPU, following cubic's device-agnostic API: each label's crop is meshed with the CUDA marching cubes and measured as an ArrayMesh, while labels and bounding boxes come from a host copy. The curvature blur uses gaussian_filter_like_scipy, so the smoothed mesh is identical on both devices. mask2mesh returns an ArrayMesh for CuPy input (a trimesh.Trimesh for NumPy), and accepts only spacing among marching_cubes_kwargs on the GPU. Features agree with the CPU path to rtol 1e-9 on a three-label image. On VPA nuclei (2 nuclei, ~330k voxels each, A40 shared with another job): the GPU-native features take 0.16 s/nucleus against 2.47 s on CPU (15x); with the hull and box features, computed by trimesh on the host, 0.63 s against 4.26 s (6.7x); with the QEM fractal dimension, also on the host, 1.90 s against 4.14 s (2.2x). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
Reviewer's GuideData structuresReview ArrayMesh’s device-resident mesh representation and its trimesh-compatible geometry, topology, and mass-property calculations, which the GPU feature path depends on.
APIReview the mesh extraction and feature interfaces together, including GPU dispatch, optional fractal features, scale-window validation, and their supporting behavior.
Uses of the APIReview the segmentation workflow’s use of the shared SciPy-rounding Gaussian and CUDA helpers after removing its private implementations.
ImplementationReview the CUDA Lewiner marching-cubes implementation and its lookup-table handling, then the shared CUDA compilation and launch helpers it uses.
ConfigurationReview removal of the now-unneeded fast-simplification dependency from the mesh extra.
DocumentationReview the project guidance documenting GPU mesh support and the new mesh-feature behavior.
TestsReview the mesh feature tests covering public behavior, fractal estimators, warnings, and mesh orientation.
Review GPU parity and device-placement tests for marching cubes, ArrayMesh, and mesh feature extraction.
Review coverage for the shared Gaussian filter, including complex-valued GPU input.
Review the shared ragged-mask fixture used by CPU and GPU mesh tests.
Lock files and vendored codeReview the dependency lockfile updates associated with the mesh-extra change.
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
There was a problem hiding this comment.
🟡 Changes recommended
Unresolved correctness issues can cause cross-device CUDA launch failures, inconsistent mesh state, inflated curvature metrics, and loss of imaginary data during GPU filtering.
4 open issues
What changed in this PR
Extends cubic’s mesh feature extraction to GPU inputs, building on the earlier mesh and curvature work while preserving the CPU path.
Changes:
- Adds CUDA Lewiner marching cubes and device-native
ArrayMeshmeasurements, with host fallbacks for selected operations. - Routes CuPy masks through GPU meshing and shares SciPy-compatible Gaussian filtering across curvature and segmentation workflows.
- Adds CPU/GPU parity tests and updates project documentation.
| File | Description |
|---|---|
tests/feature/test_mesh_gpu.py |
Tests marching-cubes and mesh-feature parity across devices. |
cubic/segmentation/aics_workflows.py |
Reuses the shared Gaussian helper. |
cubic/image_utils.py |
Adds Gaussian filtering with SciPy-compatible GPU rounding. |
cubic/feature/mesh.py |
Dispatches CuPy inputs to GPU meshing and measurements. |
cubic/feature/_marching_cubes_cuda.py |
Implements CUDA Lewiner marching cubes. |
cubic/feature/_array_mesh.py |
Provides device-native mesh properties and host fallbacks. |
AGENTS.md |
Documents GPU mesh support and the new modules. |
Review effort: Balanced
The decimation estimator returned 2.0001 +- 0.0001 on every nucleus: QEM decimation of a smooth (blurred) mesh preserves its area, so the slope was zero. It also ran QEM on the host for GPU input. Fractal Dimension is now 2 - slope of log surface area against log blur scale, from the finest voxel spacing to curvature_sigma, divided by the same areas for the mask's smooth twin (its blur at curvature_sigma). The twin shares the coarse shape and voxel grid, so the shrinking of curved surfaces under blur cancels: smooth ellipsoids of nucleus size measure 2.000 +- 0.005, against 2.05-2.20 for the area of the blurred mask alone, and band-limited roughness raises D monotonically. It describes the detail finer than the scale the curvature features use. Blur, marching cubes and area all run on the mask's device, so the feature no longer builds a host trimesh (guarded by a GPU test), and fast-simplification is dropped from the mesh extra. The feature needs the mask, so extract_mesh_features rejects it and leaves it out of its defaults. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
…than the blur A sheet a few planes thick survives the blur at curvature_sigma, but its thinner smooth twin vanishes when blurred again, and Fractal Dimension returned NaN silently while every other NaN path warns. One of 781 PC3 nuclei on the CPSAM v2 masks (a 4-plane, 1.3 um sheet) hit it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
… trimesh Marching cubes with degenerate faces removed leaves coincident and unreferenced vertices after an exact level hit. The CPU path's trimesh.Trimesh (process=True) merges them, but ArrayMesh kept them, so each unreferenced vertex added a 2 pi angle defect (0.5 to total |K|) and each duplicate split defects and edges at a seam: on a level-hit test mesh total |K| was 480.9 against trimesh's 496.1. ArrayMesh now drops unreferenced vertices and merges those equal to trimesh's 8-decimal key (vertices * 1e8, rounded, as merge_vertices does) with a lexsort on the mesh's device; cupy.unique(axis=0) took seconds for a few thousand rows. Meshes without such vertices are left untouched. The fractal-dimension areas use a new face_areas helper, which needs no merging. Reported by Copilot on #63. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
…mesh ArrayMesh forwards attributes it does not compute to a host trimesh.Trimesh copy, including in-place mutators. So mask2mesh(cupy_mask).apply_scale(2) scaled only the host copy: the device vertices and the cached volume and area stayed as they were, while delegated bounding primitives described the scaled mesh. Delegated methods now run under a check of trimesh's data hash (which covers vertices and faces, not caches). A call that changes it raises TypeError and drops the host copy, which is rebuilt from the device arrays on next use; read-only methods such as copy() work as before. A hash check covers every mutator without a list to keep in sync with trimesh. Reported by Copilot on #63. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
The kernels and lookup tables are compiled per device (_kernels(id)), but the contiguous-float32 copy, the scratch arrays and the launches ran on whichever device was current. With the volume on GPU 1 and GPU 0 current, a float64 volume was copied to GPU 0 and meshed there (the mesh came back on GPU 0); a contiguous float32 volume would launch GPU 1's kernels with GPU 0's scratch arrays. marching_cubes now enters the input array's device for the whole call. Tested on a two-GPU node for float32 and float64 input; the unfixed body returned the float64 mesh on device 0. Reported by Copilot on #63. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
The GPU branch cast each pass to float64, which drops the imaginary part of a complex image, while SciPy on the CPU filters both parts. It now works in np.result_type(image.dtype, float64): float64 for real input as before, complex128 for complex input. Real-valued results are unchanged. Reported by Copilot on #63. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
_edge_groups, face_adjacency and face_adjacency_unshared looked up the array module for calls that NumPy already dispatches to CuPy: ones_like, flatnonzero, stack, diff with append=, and take_along_axis in place of arange fancy indexing. Each was checked on CuPy input to return a CuPy array with NumPy's dtype and bytes. mesh.py moves its host vertex offsets with cubic.cuda.to_same_device instead of get_array_module(verts).asarray; the offsets stay float64. On 16 masks and spacings, every feature and mask2mesh mesh is bitwise unchanged on the CPU and the GPU, apart from the GPU's run-to-run noise (below 5e-14) in the three curvature features that CuPy's weighted bincount sums with atomic adds. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5
_edge_groups stored the sorted edges in self._edges_sorted, face_adjacency assigned self.face_adjacency_edges as a side effect, and the face_adjacency_edges property read it back out of __dict__, so each property depended on another one having run first. _edge_groups now returns the edges with their grouping, and one cached _face_adjacency returns (pairs, shared edges), which face_adjacency and face_adjacency_edges index. Features and meshes are bitwise unchanged on the CPU and the GPU (the GPU's three weighted-bincount curvature features aside, which vary below 5e-14 between runs). Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5
_merge_vertices, ArrayMesh._edge_groups and the CUDA marching cubes' _remove_degenerate_faces each sorted rows and marked the first row of each run of equal rows. _group_rows(keys) -> (order, is_new) in _array_mesh.py now does it with np. calls for all three. The two modules gave different figures for why unique(axis=0) is avoided; the helper keeps the measured one: cupy.unique(axis=0) took about 7 s per 1,000 rows, against 1.5 ms per 300,000 rows for the lexsort. _edge_groups now lexsorts the (vertex, vertex) rows instead of argsorting a combined scalar key. Equal edges still form the same runs and the pairs are sorted per row afterwards, so the adjacency is unchanged; on a 48,716-face mesh the grouping takes 0.60 ms instead of 0.45 ms on the GPU. Marching-cubes faces stay int32. Features and meshes are bitwise unchanged on the CPU and the GPU (the GPU's three weighted-bincount curvature features aside, which vary below 5e-14 between runs). Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5
_marching_cubes_on_device raises for any volume with an axis shorter than 2, so by the time it counts vertices and faces there are at least 8 grid points and one cube, and the cumulative sums it reads the last element of are never empty. The "if n", "if ncubes" fallbacks could not be taken; an all-background volume still raises "No surface found". Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5
The CUDA marching cubes compiled its kernels and sized its grids with
copies of _cuda_functions and _launch_config from aics_workflows.py:
the same RawModule(..., options=("--fmad=false",)) per device and the
same grid-stride formula. Both helpers now live in cubic/cuda.py under
the same names, and aics_workflows.py imports them, so its kernels
resolve them as before. _launch_config keeps the marching-cubes
version's floor of one block, which only changes a zero-size launch.
_kernels still caches each device's lookup-table upload. cubic/cuda.py
imports nothing from cubic, so there is no import cycle.
Mesh features and meshes are bitwise unchanged on the CPU and the GPU
(the GPU's three weighted-bincount curvature features aside, which
vary below 5e-14 between runs); the aics workflow GPU tests pass.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5
mask2mesh had its own device branch: on the GPU it checked the keywords and rebuilt skimage's default level from the volume's range, on the CPU it called skimage directly, around _marching_cubes, which exists to own that choice. _marching_cubes now takes skimage's call shape (level=None for the midpoint, keyword-only spacing and allow_degenerate, any other keyword passed to skimage on the CPU and refused with the same ValueError on the GPU), the CUDA marching_cubes accepts level=None and takes the midpoint from the min and max it already reads for its range check, and mask2mesh calls the seam once. A NumPy bool mask still goes to skimage unchanged. On the GPU, marching_cubes_kwargs now also accept level and allow_degenerate, which the port supports; step_size and the rest still raise. Features and meshes are bitwise unchanged on the CPU and the GPU (the GPU's three weighted-bincount curvature features aside, which vary below 5e-14 between runs). Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5
extract_surface_features blurred the mask at sigma in _smooth_mask2mesh, _fractal_dimension blurred it again to make the smooth twin and a third time as its last scale (geomspace returns sigma itself as the last scale), and marching cubes ran twice on that same volume. With features=["Fractal Dimension"] the smoothed mesh was built only to check that the mask survives the blur. extract_surface_features now blurs at sigma and takes its 0.5 level set once. The smoothed mesh is built from that level set only when a smoothed curvature feature is requested; _fractal_dimension thresholds the same blur for the twin and takes the mask's area at the last scale from the same (verts, faces), computed as before. _level_set folds the "max <= 0.5, else marching cubes at 0.5" that _smooth_mask2mesh and _level_set_area each repeated. The raw mesh and its validation, the vanishing warning and NaN result, and mask2mesh(mask, sigma=...) are unchanged. Per extract_surface_features call (measured by patching counters, the raw mesh included): all features or Fractal Dimension alone, 12 blurs and 12 marching cubes before, 10 and 11 after; the curvature features alone, 1 and 2 before and after. Features, warnings and meshes are bitwise unchanged on the CPU and the GPU (the GPU's three weighted-bincount curvature features aside, which vary below 5e-14 between runs). The smoothing test patched _smooth_mask2mesh, which extract_surface_features no longer calls, so it now patches the blur itself; a new test checks that Fractal Dimension alone builds no smoothed mesh, and fails when the mesh is always built. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5
The smooth twin, the mask's blur at curvature_sigma thresholded at 0.5, kept that blur's padding and was padded again at every scale; on the test masks below, its five blurred volumes held 2.1-2.4x the voxels they hold cropped (3.1-3.5x for the smallest balls). Outside the mask's frame every mask voxel lies to one side along some axis, so the blur there is at most the kernel's weight beyond its centre, below 0.5: the twin fits in the mask's own frame. _smooth_twin now crops it there before the per-scale blurs. A new test checks that a box and a ball touching their frame on every face lose no twin voxels to the crop, and that the box's twin reaches every face. The twin's vertices move by whole voxels, so float32 rounding moves its areas slightly: over 12 finite cases (6 masks, at isotropic and (0.29, 0.108, 0.108) spacing) Fractal Dimension changes by at most 3.95e-7 on the CPU and on the GPU. Every other feature is unchanged. Fractal Dimension alone, per mask, median of 5 runs after a warm-up: - CPU, (0.29, 0.108, 0.108), 58k-127k voxels: 482-772 -> 374-516 ms - CPU, isotropic, 3k-7k voxels: 56-73 -> 42-53 ms - GPU, all of them: 31-45 -> 28-33 ms Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5
test_gpu_marching_cubes_runs_on_the_input_device repeated the canonicalize-and-compare block of test_gpu_marching_cubes_matches_skimage; both now call _assert_same_mesh. test_array_mesh_matches_trimesh built mesh_feature_list() minus "Fractal Dimension" by hand, which is what extract_mesh_features computes by default, so it passes no list. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5
skimage takes level=None as 0.5 * (volume.min() + volume.max()) on float32 scalars, so the sum rounds to float32 before it is halved. The CUDA port added the extremes as Python floats, which moves the level whenever that sum is not a float32: on a 20^3 uniform volume in [0.1, 3.0], 1,607 of 35,079 vertex coordinates came out an ulp away from skimage's. The sum is now rounded to float32 first, and the new test meshes that volume with level=None on both devices and compares the meshes bit for bit; it fails without the change. A mask's level (0.5) is unchanged. Features and meshes are bitwise unchanged on the CPU and the GPU (the GPU's three weighted-bincount curvature features aside, which vary below 1e-13 between runs). Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5
skimage raises ValueError("`spacing` must consist of three floats.")
for any other length. The CUDA port multiplied the vertices by it, so
spacing=(0.5,) silently scaled every axis and a two-value spacing
failed with a broadcast error after the whole mesh was computed. The
port now raises skimage's error before any GPU work, and a new test
checks both lengths on the direct call and through mask2mesh against
skimage's own message; it fails without the change.
Features and meshes are bitwise unchanged on the CPU and the GPU (the
GPU's three weighted-bincount curvature features aside, which vary
below 1e-13 between runs).
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5
…mesh ArrayMesh.__getattr__ delegated every public name to the host trimesh. Python also calls __getattr__ when one of ArrayMesh's own properties raises AttributeError, so such a failure was answered by trimesh on the host, silently and off the device. A name defined on the class now raises AttributeError saying the ArrayMesh attribute itself failed; only names ArrayMesh does not define are delegated. Features and meshes are bitwise unchanged on the CPU and the GPU (the GPU's three weighted-bincount curvature features aside, which vary below 1e-13 between runs). Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5
_fractal_dimension returned NaN only for curvature_sigma at or below the finest voxel spacing. Just above it, the five scales span a small log range and the slope fit rests on small area differences. It now warns, and still returns the value, when curvature_sigma is less than twice the finest spacing: 2 is the default range on isotropic data and the smallest one validated. The default never warns, on isotropic data or at (0.29, 0.108, 0.108); a new test checks both and that a ratio of 1.5 warns. The curvature_sigma docstring of extract_surface_features gives the range. Fractal Dimension of 12 smooth ellipsoids (semi-axes 7-17 voxels, random orientations, isotropic spacing, CPU) by curvature_sigma / spacing: ratio mean SD min max 1.05 1.9998 0.0007 1.9990 2.0014 1.1 2.0000 0.0007 1.9991 2.0016 1.25 1.9997 0.0007 1.9984 2.0009 1.5 1.9986 0.0007 1.9977 1.9995 2 1.9947 0.0012 1.9930 1.9969 3 1.9741 0.0061 1.9652 1.9846 On these smooth bodies the spread below a ratio of 2 is no larger than at 2, so the threshold rests on 2 being the smallest validated range, not on a measured rise in spread. Features, warnings and meshes are bitwise unchanged on the CPU and the GPU (the GPU's three weighted-bincount curvature features aside, which vary below 1e-13 between runs). Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5
_marching_cubes_cuda.py imported skimage.measure._marching_cubes_lewiner_luts and _marching_cubes_lewiner._to_array at module top, and mesh.py imports that module unconditionally, so a scikit-image release that moved either private name would break import cubic.feature.mesh for CPU users too. The imports stay at the top but fall back to None, and marching_cubes raises an ImportError naming the missing module before any CuPy call. A new test patches both names to None and checks that the CPU path of mask2mesh still meshes and that the GPU entry point raises that error; it runs without a GPU. Features and meshes are bitwise unchanged on the CPU and the GPU (the GPU's three weighted-bincount curvature features aside, which vary below 1e-13 between runs). Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5
The docstrings said Python's default filter shows a constant warning text once per label image. The filter keys a text by the calling line: a loop over three images that calls extract_features on one line shows the thin-object warning once, and three calling lines show it three times. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
Twice the coarsest spacing divided by the unit equals twice the coarsest normalised spacing bit for bit, so validating in the caller's units and dividing once gives the same sigma as the nested call did. The features of 36 calls (four masks, three spacings, default and explicit sigma) are bitwise unchanged. The nested call also re-checked the quotient; a sigma that overflows when divided by the unit is no longer reported. _ADJACENCY_FEATURES is derived from _CURVATURE_AVERAGES. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
When every frame up to the top of the stack belonged to cubic, the stack walk returned one level past the outermost frame, and the warning was attributed to "sys". It now names the outermost frame. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
The repository requires type annotations; the test functions and helpers added for the unit conversion, the shared-edge warning and the warning attribution had unannotated parameters. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
Brings in the five commits added to #62 during its review (20765ea to 1b2422b): the one-step opposite-edge lengths in _mixed_area, two test changes, mask2mesh refusing marching_cubes_kwargs together with sigma, and NaN for the decimation fractal dimension of a tiny mesh. Conflicts: - The decimation estimator and its tests do not exist on this branch, so the NaN guard for a mesh under 64 faces and its test are dropped. The estimator here returns NaN with a warning when a blur vanishes. - mask2mesh keeps both checks: this branch validates the spacing, and #62 refuses the keywords and names sigma in its error. - Both branches added a test after the curvature_sigma validation tests; both are kept. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
|
Changes since d606cfa, each with the commit it was addressed in. Copilot has not reviewed them (it is not available at the moment, 2026-11-18). They were reviewed locally: a quality pass with four reviewers and a correctness pass on these commits. The branch also merged #62's reviewed head (merge commit 14d47e4); the commits that came in that way were reviewed under #62. Features measured in units of the finest spacing (was #65)
Meshes with edges shared by more than two faces
Warnings point at the caller
Argument checks
Cleanups, values unchanged
|
On the branch below this one, a ball of radius 3 next to a normal one failed extract_features with the default features, through an estimator this branch replaced. The scenario had no test here: the call returns, with NaN only for the tiny object's Fractal Dimension. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
|
Sorry @alxndrkalinin, your pull request is larger than the review limit of 150,000 diff characters |
trimesh merges vertices closer than 1e-8 when it builds a mesh, and ArrayMesh rounds to the same tolerance. With the spacing in metres the merge joined vertices of the surface: a ball of radius 10 at spacing 1e-8 came back with 1,402 vertices where 1,896 are expected, not watertight, Euler number 566. mask2mesh now runs marching cubes, the pad removal and the merge with the spacing divided by its smallest value, then returns a copy scaled to the caller's units that is not merged again. ArrayMesh.scaled returns such a copy on the device; an ArrayMesh still cannot be changed in place. The sigma branch and a spacing given in marching_cubes_kwargs are handled the same way. With no spacing, or a finest spacing of exactly 1, vertices and faces are bitwise unchanged. At spacing (0.29, 0.108, 0.108) the vertices move by at most 2 float64 ulps on the plain branch and 1.3 float32 ulps with sigma, where the cast to float32 now happens at the normalised scale. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
extract_mesh_features measured the mesh in the caller's units, where trimesh's absolute tolerances depend on the unit: for a ball of radius 10 meshed at spacing 1e-7, Avg Mean Curvature was 32 times too high, and at ordinary units the curvature features drifted with the unit. It now measures copies of mesh and smooth_mesh scaled by one factor, so that the square root of the mean face area of mesh is 1, and converts the values back with the feature dimensions. The caller's meshes are not modified and nothing is cached on them. extract_surface_features already measures in units of the finest spacing and is unchanged: its CPU output is bitwise the same. Values of extract_mesh_features move at ordinary units: geometric features by at most 2e-14, Avg Mean Curvature by up to 4.8e-7, Bounding Cylinder Volume, an approximate search, by up to 2.3%. A trimesh primitive (Sphere) is now measured as its triangles and not with its analytic volume, which moves a radius-3 sphere by up to 1.4%. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
mask2mesh resolved the spacing in two steps on its plain branch and returned from two places. It now writes the normalised spacing once and returns once; the meshes of 26 calls on two masks and the errors of ten bad inputs are the same as before, on both devices. ArrayMesh.scaled built its copy with object.__new__, which would skip anything __init__ gains later. __init__ and the new _from_merged both set the state through one private initializer. _edge_unit needs no separate case for a mesh without faces: its area is zero, which the next check catches before any division. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
The docstrings named trimesh's 1e-8 tolerance as the limit for a mesh in tiny units. The attributes of a returned mesh break earlier and for another reason: trimesh sets a face normal to zero when the norm of the face's cross product is below 1e-13, which happens once edges are shorter than about 3e-7. For a ball of radius 10 every face normal is zero at spacing 3e-7, and trimesh's own integral_mean_curvature is then 32 times too high. The merge of vertices closer than 1e-8 is a second, separate tolerance. The module docstring now states the three levels once: the label-image and mask functions work in any unit, so do mask2mesh and extract_mesh_features for meshes from mask2mesh, and attributes read straight off a mesh, or a mesh the caller built, are subject to trimesh's tolerances. The parameter docstrings point to it. extract_mesh_features promises that the caller's meshes are not modified. It no longer promises that nothing is cached on them, which is false for a trimesh primitive, and it says a primitive is measured as its triangles. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
Eight deliberate breakages of mask2mesh and extract_mesh_features (no scaling, the smooth mesh scaled by its own unit, values not converted back, the bounding-box diagonal as the unit, a wrong dimension, no normalisation in mask2mesh, a second merge after scaling, scaling the caller's mesh in place) were run against every cell. The isotropic base and the factors 1e-6 and 1e-3 catch nothing the kept cells miss, and are gone; the file's CPU time goes from about 10 to about 6 s. Also: the test that the caller's meshes are left alone no longer pins trimesh's cache; two identical cases are one; the lobed mask is built by the existing helper; four copies of the patch that forbids a host trimesh are one fixture; and the once-per-call test asserts where the curvatures are shared. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
extract_mesh_features scaled `mesh` and `smooth_mesh` separately, so a caller passing one object as both had two equal copies measured: the face adjacency and the shared-edge check were built on each. That call is now measured as a call without a smooth mesh, which reads the curvature features off `mesh`. The values are the same and one copy is made where there were two. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
scaled() built its copy through a classmethod and a private initializer shared with __init__: three methods around one assignment. __init__ now takes merge=False for arrays that are already merged, and scaled() calls it. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
No test distinguished Avg Shape Index between shapes: the ball test asks for more than 0.85 and every other test compares equal values, so all 255 feature tests passed with the shape index forced to 0.9. A torus, whose inner half is saddle, reads 0.50 against the ball's 0.92. The new test asks for a gap of 0.2 and fails under that constant. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
|
Changes since 7b1a7cb, each with the commit it was addressed in. Copilot has not reviewed them (it was not available on 2026-11-17 and 18). They were reviewed locally: a quality pass with four reviewers on the first two commits and a correctness pass on the first five; the last three commits are that pass's fixes.
Clean-up and tests
Left as they are, with the reason: |
A blur width in the wrong unit made _padded_blur pad the mask by three blur widths per side before anything checked that the blurred mask still reaches 0.5: curvature_sigma at 1000 times the spacing asks for an array of terabytes around a ball 16 voxels across. A blurred value is at most the mask's voxel count times the largest kernel weight of each axis. When that bound is below 0.49, the blur is below 0.5 everywhere, so _padded_blur returns zeros in its place and the caller takes the path of a vanished mask as before: extract_surface_features warns and returns NaN for the features that need the blur, the fractal ladders warn and return NaN, and mask2mesh(sigma=...) raises. Only this provably vanishing case is removed; a wide blur of a large object still allocates what it needs. The bound holds for the kernel that SciPy and cupyx build: against SciPy's kernel at 21,197 widths it is never below the true weight and at most 1.4% above it. On the harness (3,285 values) no value changes on the CPU. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
…atures At a flat vertex the angle defect and the signed edge sum are rounding residues, and the shape index there is the arctangent of two residues. NumPy and CuPy sum them in different orders, so Avg Shape Index of a raw voxel mesh differed between the devices by 9e-4 to 5e-3, and between CuPy runs. _principal_curvatures sets an angle defect to 0 where it is at most 1e-14 rad, and an edge sum where it is at most 1e-14 of the sum of the absolute values of its terms. On three raw meshes NumPy and three CuPy runs then agree within 1e-12 (3/3 on each mesh, 0/3 before). On blurred meshes, which the default pipeline measures, no harness value changes on the CPU; on 240 real nuclei the largest change was 1.1e-6. The value on a raw mesh still depends on the scale it is measured at (0.116, 0.173 and 0.061 for one ball at three scales), so the unit-conversion test keeps leaving it out. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
The docstring of _blur_bound concluded, from the array being longer than the kernel's radius, that no output reaches images beyond both borders. That is false for a central output. What the bound needs is narrower and true: an output reaches at most one mirror image of a given voxel, because the distances to its two nearest images add up to twice the array's length. The bound itself is unchanged. _largest_kernel_weight loses its truncate parameter, which no caller passed; it uses the blur's default of 4. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
The property test compared the bound with a blur from a helper that repeated the padding and mode of _padded_blur, so a change of that rule in the library would have left the test checking the old one. It now switches the guard off and calls _padded_blur. The fixed one- and two-voxel masks are listed once. Both mutants that make the bound too small are still caught, in 6 of 10 cases each, and the largest real maximum among guarded cases is 0.48. The padded array of the wrong-unit test is 6.3 TB, not 3 TB. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
_blur_bound reduced the mask on every _padded_blur call, although the sum does not depend on the blur width: ten reductions per object for the default features and twenty with Outline Fractal Dimension, on four distinct images. The callers that blur one image at several scales now count it once and pass the count, and a boolean mask is counted with count_nonzero: three and six reductions. _padded_blur counts for itself when no count is passed, so its positional signature is unchanged. Per object on an A40 (319k-voxel mask, median of 7): 331 ms before and 308 ms after, with overlapping ranges. Values are bitwise unchanged on the CPU. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
extract_mesh_features measures scaled copies of a mesh at _edge_unit, the square root of the mean face area. The areas were summed on their device, and cupy.sum, or NumPy's sum of the same faces in another order, can land an ulp away. A NumPy and a CuPy mesh of one mask list the same faces in different orders. Units an ulp apart move the dihedral angles of coplanar faces between 0 and 1.5e-8 rad. On a noise blob at spacing (0.29, 0.108, 0.108), with bitwise-equal meshes, Avg Shape Index of the raw mesh then differed between the devices by 7.8e-3 and Bounding Cylinder Volume by 1.5e-4 relative, also with a blurred smooth_mesh. extract_surface_features does not call _edge_unit and agreed. The areas are now summed exactly with math.fsum on the host. Over three masks, two spacings and both paths, NumPy and three CuPy runs agree within the suite's tolerance in 756 of 756 comparisons (747 before). On the CPU, 58 of 252 values move where fsum differs from NumPy's sum: raw Avg Shape Index by up to 4.6e-3, which is its known scale dependence, and every other feature by at most 2e-8 relative. On a 1.5M-face mesh, _edge_unit takes 66 ms on the GPU, up from 3 ms. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
The docstring of _principal_curvatures said both tests zero rounding residues. The edge-sum test fires only where its terms cancel, which they do not at a flat vertex of a raw voxel mesh: coplanar faces read dihedral angles of 1.5e-8 to 3e-8 rad, so a raw mesh's Avg Shape Index still depends on the scale it is measured at. The docstring and the test comments now say which test gives the device agreement, and that it holds at a common measuring unit. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
30bb466 summed the face areas exactly, but the areas themselves can differ between the devices: CuPy 14.0.1 computes 14% of them an ulp away from NumPy on 120 blurred-noise meshes (CuPy 14.2.0 none). The units of _edge_unit then still differed on 6 of the 120 meshes, and the raw-mesh Avg Shape Index and Bounding Cylinder Volume of extract_mesh_features differed between NumPy and CuPy by up to 11% and 8.7%, with smooth_mesh too. The unit is now the square root of the area of the vertices' bounding box per face. It uses only per-axis maxima and minima, which are exact on any device and in any order, and the face count. On the 120 meshes in both CuPy environments the units are bitwise equal, and NumPy and three CuPy runs agree within the suite's tolerance on all 7560 raw and 7434 smooth_mesh comparisons. The unit-conversion tests pass unchanged. The new unit is 0.95 to 1.4 times the old one, so on the CPU the two features that depend on the measuring scale move once: raw Avg Shape Index by up to 57% and Bounding Cylinder Volume by up to 55% over 144 meshes. Other features move by at most 2.5e-6 relative. _edge_unit takes 72 ms instead of 214 ms on the GPU for 5.2M faces. The flat-residue test asserted no change with the threshold at 0; at the new unit the threshold zeroes 260 angle defects of one ulp of 2 pi. It now asserts that only residues of at most four ulps are zeroed and that no defect lies just above the threshold; a threshold of 1e-12 fails it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
_edge_unit masks out unreferenced vertices before taking the bounding box, but meshes from mask2mesh have none, so no test failed without the mask. A box with one stray vertex at 1e6 now does: without the mask its unit is 707107 instead of 0.707. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
|
Commits after 896eb1f, from the user's decisions on items 1 and 4 and from the review rounds on them:
|

Stacked on #62 (base
feat/mesh-curvature-features). Retarget once #62 merges. #61 is merged; this branch includesmainfrom after that merge and #62's reviewed head (1b2422b). #65 (unit normalisation) was folded into this branch.Summary
Mesh features now follow cubic's device-agnostic API: a CuPy label image or mask is meshed and measured on the GPU, and the results match the CPU path.
CUDA marching cubes (
cubic/feature/_marching_cubes_cuda.py). cuCIM has none, so this ports scikit-image's Lewiner implementation, running on scikit-image's own lookup tables and the same face and interior ambiguity tests. It works in three passes:An edge vertex depends only on its edge's two corner values. So with float64 corner arithmetic in the reference's operation order, and
--fmad=false, the vertices round to skimage's float32 values. The mesh is the same as skimage's up to vertex and face order. Withallow_degenerate=Falsethe port also merges every coincident vertex, where skimage merges only those of degenerate faces; the two meshes are equal once duplicates are merged on both sides. The call runs on the input volume's device, whichever device is current.ArrayMesh(cubic/feature/_array_mesh.py). It provides the trimesh attributes the feature registry reads, computed with trimesh's formulas on NumPy or CuPy arrays: mass properties, Euler number, adjacency with dihedral angles and convexity, integral mean curvature, angle defects. It merges coincident vertices and drops unreferenced ones as trimesh's processing does. The convex hull and the bounding box, cylinder and sphere fall back to a hosttrimesh.Trimeshbuilt on first use; a delegated method that would change the mesh in place raisesTypeError.GPU dispatch in
mesh.py.extract_features,extract_surface_featuresandmask2meshkeep CuPy input on the GPU.mask2meshreturns anArrayMeshfor CuPy input and atrimesh.Trimeshfor NumPy. On the GPU it acceptslevel,spacingandallow_degenerateamongmarching_cubes_kwargs; other keywords raise.Fractal Dimension, re-estimated so it runs on both devices (commit 50cdcfd). The QEM-decimation estimator from feat(feature): ShapeTools shape measures on a smoothed mesh (total |K|, shape index, curvedness, fractal dimension) #62 returned 2.0001 ± 0.0001 on every nucleus: decimating a smooth (blurred) mesh barely changes its area. It also needed QEM on the host.
curvature_sigma, with each area divided by the same area for the mask's smooth twin (its blur atcurvature_sigma). The twin cancels the shrinking of curved surfaces under blur.fast-simplificationis no longer needed.curvature_sigmaonce for both the smoothed mesh and D: 10 blurs and 11 marching-cubes calls per object, down from 12 and 12. The twin is blurred on the mask's own crop (commit 367ad00), which moved D by at most 3.95e-07 on the test masks.extract_mesh_featuresrejects it and leaves it out of its defaults.Settable window, thin-object warning and an in-plane variant (commits 7da2d9d to 3064a43).
fractal_scales=(lowest, highest)sets the blur scales of theFractal Dimensionfit, in units ofspacing. The default, the finest voxel spacing up tocurvature_sigma, is unchanged.Min Axis Length; above that it reads low. In that case the value is still returned, with one warning per label image.Outline Fractal Dimensionis a new optional feature, computed only when requested by name (mesh_feature_list(optional=True)lists it). It is the same estimator on the outline of the mask's projection along the first axis: 1 − slope of log contour length, about 1 for a smooth outline. Its window isoutline_fractal_scales, by default 4 to 16 in-plane voxels. The contour length comes from marching cubes on a two-layer copy of the blurred footprint, so it runs on both devices with the same result. It is meant for flat objects imaged along the first axis and is the one feature defined on the image axes. It needs a footprint about 5 times the top scale across (0.99 on a smooth disc there, NaN below 3.2 times).TypeError, bad valuesValueError, and warnings are attributed to the line that called the public function.Shared SciPy-rounding Gaussian.
image_utils.gaussian_filter_like_scipyreplaces the private filter inaics_workflows. The curvature blur now uses it too, so the smoothed mesh is identical on both devices. cupyx alone differs from SciPy by up to 1.8e-7, which moved total |K| by 7e-4 relative. Complex input keeps its imaginary part on the GPU.Shared kernel helpers. The CUDA compile and launch helpers moved from
aics_workflowstocubic.cuda, where both kernel modules use them.Meshes are oriented where they are built (commits 3b7c6e8 to d606cfa).
trimesh.repair.fix_normalsinverts only a mesh that trimesh calls watertight. Ragged masks give such edges. The volume check then raised for the wholeextract_featurescall, while the same label on CuPy input was measured._marching_cubesreverses the faces from the known winding of marching cubes, on both devices, and leaves them as they are forgradient_direction="ascent". No volume is computed for it.ArrayMeshmeasures its faces as given, astrimesh.Trimeshdoes.extract_mesh_featuresdetects an inside-out mesh. It does not detect an open surface in general, because the sign of an open surface's volume depends on the origin; its message and docstring now say so. Meshes frommask2meshare closed, because the mask is padded.Euler Characteristic,Avg Mean Curvature,Total Absolute Gaussian Curvature,Avg Shape IndexandAvg Curvedness. Each such edge is counted once in the Euler number and left out of the mean-curvature sum, and the angle defects at its ends add up the two sheets of surface that meet there. A ball with 30% of its boundary shell flipped has 33 such edges and reports an Euler number of −477. The values are returned, with one warning (commit 65c0546) when a requested feature of the five was measured on such a mesh. In the default pipeline the last three are measured on the blurred mesh, which had no such edge on any test mask.Features measured in units of the finest spacing (commits 8b7faa0 and 094822d; this is the content of fix(feature): mesh features that do not depend on the unit of spacing #65, which was folded into this branch).
ArrayMeshwith it, compare lengths and areas against absolute tolerances, so the features depended on the unit ofspacing. Two of them matter here: vertices closer than 1e-8 are merged, and a face normal is set to zero when the norm of the face's cross product is below 1e-13, which happens once edges are shorter than about 3e-7. On two synthetic masks, compared with spacing 1:Avg Shape IndexandAvg Curvednessdrifted by up to 1.2e-5 at spacing 1e-2 and were 3.4 to 5.9 times off at 1e-6;Avg Mean Curvaturewas 28 and 94 times off at 3e-7; at 1e-7 and below the call raised unrelated errors.extract_surface_features, and soextract_features, divides the spacing,curvature_sigmaand both fractal windows by the finest spacing, measures, and multiplies each feature by that unit to the power of its length dimension (_FEATURE_DIMENSIONS). Warnings and errors print lengths in the caller's units.Bounding Cylinder Volumecomes from an approximate search and can then move by a few 1e-4.(1, 1, 1), the output is bitwise unchanged on the CPU.mask2meshbuilds the mesh atspacing / min(spacing)and scales the result, so vertices are merged in units of the finest spacing and returned in the caller's units.extract_mesh_featuresmeasures copies of the caller's meshes, scaled to their own edge scale, and converts each value back. The caller's meshes are not modified. The edge scale is the square root of the area of the vertices' bounding box per face (commit 6067b79). It uses only per-axis maxima and minima and the face count, so a NumPy and a CuPy mesh of one mask are measured at bitwise the same unit. A unit from the face areas, as before (and 30bb466's exact sum of them), was not: the face areas themselves can differ by an ulp between the devices (14% of them under CuPy 14.0.1, none under 14.2.0), and units an ulp apart flip the dihedral angles of coplanar faces between 0 and 1.5e-8 rad. On 120 blurred-noise meshes at three spacings, the raw-meshAvg Shape IndexandBounding Cylinder Volumethen differed between the devices by up to 11% and 8.7%, with a blurredsmooth_meshtoo. Now the units are equal on 120 of 120 meshes under both CuPy versions, and NumPy and three CuPy runs agree within the suite's tolerance in all 7560 raw and 7434smooth_meshcomparisons. The new unit is 0.95 to 1.4 times the old one; see the cylinder note under Evidence for what that moves on the CPU.mask2meshreturns the same mesh topology (1,896 vertices, watertight) andextract_mesh_featuresthe same mean curvature. Before, the mesh lost vertices at 1e-8 (1,402 left, not watertight) and the mean curvature was 32 times too high at 1e-7.extract_surface_featuresandextract_featuresare bitwise unchanged on the CPU. With spacing 1, the mesh frommask2meshis bitwise unchanged; at(0.29, 0.108, 0.108)its vertices move by at most 2 ulps.mask2meshfollowed byextract_mesh_featuresnow agrees withextract_surface_featuresto 1.2e-8 on the three smoothed curvature features, at ordinary and at tiny units. With the mesh built at the caller's spacing, asmask2meshdid before, the same comparison is up to 1.5e-5 apart at(0.29, 0.108, 0.108). See the third table under Evidence.extract_mesh_featureson one mesh no longer reuse what trimesh caches on that mesh (0.31–0.38 s against 0.10–0.28 s in one timing). A trimesh primitive is measured as its triangles: the values of aSphereof radius 3 move by 0.1–1.4%, those of aBoxnot at all.trimesh.Trimesh, and meshes the caller builds in tiny units. For the same ball at spacing 3e-7 and below, every face normal of the returned mesh is zero and trimesh's ownintegral_mean_curvatureis 32 times too high;volumeandareahold. The module docstring ofcubic.feature.meshstates the three levels.Argument checks at the public entries (commits 3e2093d, aa3f605, 24fdd36).
spacingmust be three finite, positive numbers inextract_features,extract_surface_featuresandmask2mesh, andcurvature_sigmais checked whichever features are requested. Before,mask2meshwith spacing(-1, -1, -1)returned an inside-out mesh, and an all-negative spacing inextract_featuresreturned the features of the mirrored object.Warnings point at the caller (commits 40e4093, 8ebd41f, 13cf736, beb7226). Every warning of the module is attributed to the first frame outside the
cubicpackage. Before, throughextract_featuresthey pointed at the per-label loop insidemesh.py. Under Python's default filter a constant text is shown once per calling line.Per-vertex curvatures once per mesh (commits 88bea9d, 763fa55).
Avg Shape IndexandAvg Curvednessshare one computation; values are bitwise unchanged on the CPU.A blur that provably wipes out the mask is not run (commits d30c98c, 1a096d4, 6c649bc, 3eefac6). Before padding,
_padded_blurbounds the blurred maximum by the mask's voxel count times the largest kernel weight on each axis, mirror images included. Below 0.49 the mask cannot reach the 0.5 level, so the pad and the blur are skipped and the caller takes the existing vanished-mask path (warning and NaN;mask2meshraises). A 22-voxel crop at a wrong-unit blur width used to pad to 6.3 TB. The guard covers only this case: a large blur that leaves the mask visible still pads by about 4 sigma. On the CPU harness 0 of 3285 values moved. The mask is counted once per image for all the blur scales it is tested at (A40, 319k-voxel mask: 331 ms against 308 ms per object, ranges overlap).Rounding residues of flat vertices set to 0 in the curvatures (commits fb732db, b3ea2b4).
_principal_curvaturessets an angle defect of at most 1e-14 rad to 0, and an edge sum of at most 1e-14 of the sum of its absolute terms. With the common unit above, the raw-meshAvg Shape Indexagrees between NumPy and CuPy (to 1.1e-16 over 128 meshes under CuPy 14.0.1 and 14.2.0; up to 1.0e-2 with the threshold at 0). On the blurred meshes of 240 real nuclei the largest change was 1.1e-6 (20 of 240 nuclei moved).Evidence
ArrayMeshon NumPy against trimesh (ball, hollow ball, 58k-vertex VPA nucleus)ArrayMeshagainst trimesh on a mesh with coincident and unreferenced verticesextract_featureswith CuPy against NumPy (three labels)Outline Fractal Dimensionagainst contour lengths fromfind_contourson 60 real nuclei (three datasets)extract_surface_featuresbefore and after the fractal-dimension commits (8 masks, CPU)Fractal Dimensionwithin 1.8e-8extract_featureson a label image with a ragged ball (30% of its boundary shell flipped) and a clean cube, NumPy and CuPy inputextract_surface_featuresbefore and after the orientation commits (8 masks)_marching_cubeson a ball, a hollow ball, a random mask and a blurred mask, both devicesArrayMeshon NumPy,ArrayMeshon CuPy)Largest relative change from the unit normalisation at ordinary spacings (CPU, 9 masks: two balls, a turned ellipsoid, a hollow ball, a torus, an irregular blob, a cube at the border, two flat ellipsoids):
(0.29, 0.108, 0.108)(0.108, 0.108, 0.108)Largest relative difference between
extract_mesh_featureson meshes frommask2meshandextract_surface_featureson the same mask (CPU, 8 masks, spacings(1, 1, 1),(2.685, 1, 1),(0.29, 0.108, 0.108)and 1e-8 times the last):The table was measured at 1c84895. The commits after it leave these values bitwise unchanged on the CPU up to 3eefac6, except the flat-residue commit (
Avg Shape Index, at most 1.1e-6 on 240 real nuclei). The new edge scale of 6067b79 movesextract_mesh_featuresvalues on 144 test meshes by at most 2.5e-6 relative (Avg Mean Curvature), 1.3e-10 for the rest, except the two features that depend on the measuring scale: the raw-meshAvg Shape Indexby up to 57% andBounding Cylinder Volumeby up to 55% (141 of 144 meshes moved, most on blurred-noise blobs). The cylinder row reflects trimesh's search, which depends on the scale of the mesh alone: rescaling one mesh by ten arbitrary factors moves its bounding cylinder volume by 1.9% (ball of radius 10) and 1.5% (rough flat ellipsoid), where the bounding sphere and the oriented box move by 1e-15. So this feature differs between the two entry points, which measure at different scales, and it moved by up to 2.25e-2 inextract_mesh_featuresat ordinary units with this change.Timings on two real VPA nuclei (about 330k voxels each), per nucleus:
The timings in commit 36f4e41's message were taken while another job held the GPU at 100%. They are superseded by the table above.
Fractal Dimension alone, per mask, on synthetic masks (median of 5 runs): 28–33 ms on an A40; 374–516 ms on the CPU for anisotropic masks of 58k–127k voxels, and 42–53 ms for isotropic masks of 3k–7k voxels. These were taken before the one-voxel padding of the ladder, which cut the CPU time on 8 test masks from 1,058 to 853 ms.
Outline Fractal Dimensiontakes about 21 ms per mask on the CPU for a 151 × 151 footprint.Notes
Compiling the CUDA kernels needs the CUDA headers. On this cluster that meant
CUDA_PATH=/hpc/apps/cuda/12.8.0_570.86.10, with itslib64onLD_LIBRARY_PATHfor NVRTC's builtins. CuPy's[ctk]extra provided neither. Theaics_workflowskernels need the same setup.The lookup tables come from
skimage.measure._marching_cubes_lewiner_luts, a private module. It is imported guardedly: a scikit-image release that moves it breaks only the GPU path, with an error naming the module, and the parity tests would catch any change to the tables.On the GPU, Total Absolute Gaussian Curvature, Avg Shape Index and Avg Curvedness vary by up to 7e-14 between runs of the same code, because CuPy's weighted
bincountaccumulates with atomic adds. Every other feature and every mesh is bitwise repeatable.On a raw voxel mesh, without a smoothed mesh,
Avg Shape Indexnow agrees between NumPy and CuPy (see the two bullets above), but it still depends on the scale the mesh is measured at: 0.116, 0.173 and 0.061 for one ball at three scales (measured at fb732db), and up to 57% over 144 meshes between the old and the new edge scale. At the flat vertices of the voxel staircase two coplanar faces have a dihedral angle that is an arccos of a dot product within a few ulps of 1, which reads 0 or 1.5e-8 to 3e-8 rad depending on rounding. These vertices keep a tiny mean curvature and a shape index of 0.5 or 0. No threshold on those angles separates this noise from real angles on real nuclei (noise ceiling 2.98e-8, smallest real angle 3.33e-8). The default pipeline measures the shape index on the blurred mesh, where this does not arise.Known bias of the curvature estimator, measured after the gate and not changed here (it comes from feat(feature): ShapeTools shape measures on a smoothed mesh (total |K|, shape index, curvedness, fractal dimension) #62's per-vertex operators; follow-up PR). On an exact analytic shape meshed with marching cubes, with no staircase and no blur,
Avg Shape Indexreads about 0.1 below the truth,Avg Curvednessabout 6% above it andTotal Absolute Gaussian Curvatureabout 5% above it (spheres and ellipsoids, grid (0.29, 0.108, 0.108) µm). The error does not shrink when the grid is refined 2× and 4×. It comes from per-vertex noise on marching-cubes triangles: H² − K > 0 at 70% of a sphere's vertices, and the one-sided clamp pulls the shape index below 1. Separately, the default blur of 2× the coarsest spacing removes the voxel staircase on the anisotropic grids measured, (0.29, 0.108, 0.108) and (0.3152, 0.1318, 0.1318) µm, but leaves some on isotropic grids, where 2.5–3× is needed.Known CPU/GPU difference, found after the gate and fixed in fix(feature): deterministic bounding shapes, accurate dihedral angles, fixed-order GPU sums #66:
Oriented Bounding Box VolumeandExtentcome from trimesh'soriented_bounds, which depends on the order of the input vertices, and a NumPy and a CuPy mesh list the same vertices in different orders. On 240 real nuclei they differed between the devices by up to 9.4% and 8.6% (10 nuclei). The device tests and the two-GPU job use synthetic masks, where the box agrees.Test plan
At head 6067b79 (c9467fe after it adds one CPU test; CI passed at c9467fe):
uv run python -m pytest -q): 969 passed, 223 skippedtests/feature tests/test_image_utils.py tests/segmentationwith CuPy 14.2.0 on an A40: 509 passed, 23 skipped (22 needcellposeoritk, 1 needs two GPUs)tests/feature/test_mesh_gpu.pyon a two-GPU node (2× A40): 43 passed, none skippedextract_surface_featureson a mask that lives on GPU 1 while GPU 0 is current: every feature agrees with the CPU value (rtol 1e-9, and 1e-7 absolute on the three features that vary between runs). The same holds before the orientation commits. Throughmask2meshthe mesh lands on the current device, GPU 0, before and after; only a direct call of the kernel module keeps it on the volume's device.ruff check .,ruff format --check .,mypy --ignore-missing-imports cubic/🤖 Generated with Claude Code
https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
Summary by Sourcery
Run mesh feature extraction on the GPU while adding device-compatible mesh measurements and scale-based fractal-dimension features.
New Features:
Bug Fixes:
Enhancements:
Documentation:
Tests: