Skip to content

feat(feature): mesh features on the GPU (CUDA marching cubes, ArrayMesh) - #63

Merged
alxndrkalinin merged 129 commits into
mainfrom
feat/mesh-gpu
Nov 22, 2026
Merged

alxndrkalinin merged 129 commits into
mainfrom
feat/mesh-gpu

Conversation

@alxndrkalinin

@alxndrkalinin alxndrkalinin commented Oct 30, 2026 •

Copy link
Copy Markdown
Owner

Stacked on #62 (base feat/mesh-curvature-features). Retarget once #62 merges. #61 is merged; this branch includes main from 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:

    1. Classify each cube, then mark the edges and cube centres it uses.
    2. Number them by prefix sum and compute the vertices.
    3. Write each cube's triangles.

    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. With allow_degenerate=False the 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 host trimesh.Trimesh built on first use; a delegated method that would change the mesh in place raises TypeError.

  • GPU dispatch in mesh.py. extract_features, extract_surface_features and mask2mesh keep CuPy input on the GPU. mask2mesh returns an ArrayMesh for CuPy input and a trimesh.Trimesh for NumPy. On the GPU it accepts level, spacing and allow_degenerate among marching_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.

    • New estimator: 2 − the slope of log surface area against log blur scale, from the finest voxel spacing to curvature_sigma, with each area divided by the same area for the mask's smooth twin (its blur at curvature_sigma). The twin cancels the shrinking of curved surfaces under blur.
    • Smooth ellipsoids of nucleus size measure 2.000 ± 0.005, against 2.05–2.20 when using the blurred area alone. Band-limited roughness (0.4 µm) raises D monotonically.
    • Every step (blur, marching cubes, area) runs on the mask's device; a GPU test asserts it never builds a host trimesh, and CPU/GPU agree to rtol 1e-9. fast-simplification is no longer needed.
    • The mask is blurred at curvature_sigma once 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.
    • The ladder's other blurs pad by one voxel (commits db2d1a0, 3064a43): the field on the mask's frame is bitwise the same, and D moved by at most 1.8e-8.
    • D needs the mask, so extract_mesh_features rejects 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 the Fractal Dimension fit, in units of spacing. The default, the finest voxel spacing up to curvature_sigma, is unchanged.
    • On smooth synthetic shapes the 3D value is unbiased only while the top scale is at most a quarter of the object's Min Axis Length; above that it reads low. In that case the value is still returned, with one warning per label image.
    • Outline Fractal Dimension is 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 is outline_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).
    • Why: in a scale-window sweep on three nucleus datasets, the outline form agreed between two segmenters of the same nuclei at Spearman rho 0.85 on astrocytes and fibroblasts, against 0.44 and 0.53 for the 3D default, and separated proliferating from serum-starved fibroblasts on held-out samples at AUROC 0.66, against 0.57.
    • Wrong-type windows raise TypeError, bad values ValueError, and warnings are attributed to the line that called the public function.
  • Shared SciPy-rounding Gaussian. image_utils.gaussian_filter_like_scipy replaces the private filter in aics_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_workflows to cubic.cuda, where both kernel modules use them.

  • Meshes are oriented where they are built (commits 3b7c6e8 to d606cfa).

    • Problem: on NumPy input, a mask whose surface has an edge shared by four faces stayed inside out, because trimesh.repair.fix_normals inverts only a mesh that trimesh calls watertight. Ragged masks give such edges. The volume check then raised for the whole extract_features call, while the same label on CuPy input was measured.
    • Change: _marching_cubes reverses the faces from the known winding of marching cubes, on both devices, and leaves them as they are for gradient_direction="ascent". No volume is computed for it. ArrayMesh measures its faces as given, as trimesh.Trimesh does.
    • Output on meshes that worked before is bitwise unchanged on the CPU. Each mesh now computes its mass properties once; before, the trimesh path computed them twice for a request of the Euler characteristic alone.
    • The volume guard in extract_mesh_features detects 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 from mask2mesh are closed, because the mask is padded.
    • On a mesh with edges shared by more than two faces, five features are approximate: Euler Characteristic, Avg Mean Curvature, Total Absolute Gaussian Curvature, Avg Shape Index and Avg 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).

    • Problem: trimesh, and ArrayMesh with it, compare lengths and areas against absolute tolerances, so the features depended on the unit of spacing. 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 Index and Avg Curvedness drifted by up to 1.2e-5 at spacing 1e-2 and were 3.4 to 5.9 times off at 1e-6; Avg Mean Curvature was 28 and 94 times off at 3e-7; at 1e-7 and below the call raised unrelated errors.
    • Change: extract_surface_features, and so extract_features, divides the spacing, curvature_sigma and 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.
    • What holds: a feature converts with the unit exactly when the ratios of the spacings round alike in both units, and otherwise to about 1e-8 relative. Bounding Cylinder Volume comes from an approximate search and can then move by a few 1e-4.
    • Values at ordinary spacings move a little; see the second table under Evidence. With no spacing, or (1, 1, 1), the output is bitwise unchanged on the CPU.
    • The two direct functions work in any unit as well (commits 0558944 to b112184).
      • mask2mesh builds the mesh at spacing / 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_features measures 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-mesh Avg Shape Index and Bounding Cylinder Volume then differed between the devices by up to 11% and 8.7%, with a blurred smooth_mesh too. 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 7434 smooth_mesh comparisons. 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.
      • For a ball of radius 10 at spacings from 1 down to 1e-9, mask2mesh returns the same mesh topology (1,896 vertices, watertight) and extract_mesh_features the 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_features and extract_features are bitwise unchanged on the CPU. With spacing 1, the mesh from mask2mesh is bitwise unchanged; at (0.29, 0.108, 0.108) its vertices move by at most 2 ulps.
      • mask2mesh followed by extract_mesh_features now agrees with extract_surface_features to 1.2e-8 on the three smoothed curvature features, at ordinary and at tiny units. With the mesh built at the caller's spacing, as mask2mesh did before, the same comparison is up to 1.5e-5 apart at (0.29, 0.108, 0.108). See the third table under Evidence.
      • Two costs. Repeated calls of extract_mesh_features on 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 a Sphere of radius 3 move by 0.1–1.4%, those of a Box not at all.
      • Still unit-dependent, and outside what cubic can fix: attributes read straight off a returned 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 own integral_mean_curvature is 32 times too high; volume and area hold. The module docstring of cubic.feature.mesh states the three levels.
  • Argument checks at the public entries (commits 3e2093d, aa3f605, 24fdd36). spacing must be three finite, positive numbers in extract_features, extract_surface_features and mask2mesh, and curvature_sigma is checked whichever features are requested. Before, mask2mesh with spacing (-1, -1, -1) returned an inside-out mesh, and an all-negative spacing in extract_features returned 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 cubic package. Before, through extract_features they pointed at the per-label loop inside mesh.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 Index and Avg Curvedness share 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_blur bounds 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; mask2mesh raises). 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_curvatures sets 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-mesh Avg Shape Index agrees 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

check result
marching cubes, binary noise 40³ (all 14 Lewiner cases) identical to skimage: 99,337 vertices / 232,154 faces
marching cubes, continuous noise 64³ identical: 401,937 / 878,906; 88 ms on the GPU against 1.7 s for skimage
marching cubes, blurred noise, anisotropic balls, exact level hits (with and without degenerate removal) identical, including output dtype
marching cubes with the default level on a non-binary volume identical; a float64 midpoint moved 1,607 of 35,079 vertex coordinates by an ulp
marching cubes with the volume on GPU 1 and GPU 0 current (two-GPU node, float32 and float64 input) mesh on GPU 1, identical to skimage
ArrayMesh on NumPy against trimesh (ball, hollow ball, 58k-vertex VPA nucleus) ≤ 1.7e-16 relative on every feature
ArrayMesh against trimesh on a mesh with coincident and unreferenced vertices same vertex count, Euler number, area and angle defects
extract_features with CuPy against NumPy (three labels) rtol 1e-9 on every feature
Outline Fractal Dimension against contour lengths from find_contours on 60 real nuclei (three datasets) within 1.1e-8
default output of extract_surface_features before and after the fractal-dimension commits (8 masks, CPU) identical, except Fractal Dimension within 1.8e-8
extract_features on a label image with a ragged ball (30% of its boundary shell flipped) and a clean cube, NumPy and CuPy input both return volumes 14291.58 and 985.67; before, NumPy input raised and CuPy input returned
default output of extract_surface_features before and after the orientation commits (8 masks) CPU bitwise identical, meshes included; GPU within 1.8e-14, all in the three features that vary between runs
faces from _marching_cubes on a ball, a hollow ball, a random mask and a blurred mask, both devices enclose a positive volume
conversion with the unit, all 23 features, isotropic spacing from 1 down to 1e-9 before: wrong from 1e-2, raises at 1e-7 and below; after: off by at most 1.5e-16 on the CPU and 9.4e-15 on the GPU
shared-edge count and warning on ten masks, three ways (trimesh, ArrayMesh on NumPy, ArrayMesh on CuPy) same count each way (0, 0, 3 and 33 on a clean ball and balls with 2%, 10% and 30% of the shell flipped; 6 to 15 on random masks); the warning fires on all three or on none; the default features agree to 1.2e-14

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):

feature (0.29, 0.108, 0.108) (0.108, 0.108, 0.108)
Area, Volume, hull volume and area, oriented box volume, Sphericity, Extent, Solidity ≤ 7.4e-16 ≤ 4.9e-16
axis lengths, inertia components ≤ 1.6e-14 ≤ 8.6e-14
Euler Characteristic 0 0
Bounding Sphere Volume 3.1e-10 3.8e-11
Bounding Cylinder Volume 7.4e-6 6.3e-3
Avg Mean Curvature 1.4e-7 2.1e-7
Total Absolute Gaussian Curvature 3.9e-4 1.3e-5
Avg Shape Index 4.5e-5 1.2e-4
Avg Curvedness 8.1e-5 1.8e-6
Fractal Dimension 1.3e-8 3e-8
Outline Fractal Dimension (finite on 2 of the 9 masks) 9.8e-9 9.8e-9

Largest relative difference between extract_mesh_features on meshes from mask2mesh and extract_surface_features on 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):

feature largest difference
Area, Volume, axis lengths, inertia components, Sphericity 1.2e-14
hull volume and area, oriented box volume, Bounding Sphere Volume, Extent, Solidity 1.8e-10
Euler Characteristic 0
Avg Mean Curvature 4.8e-7
Total Absolute Gaussian Curvature, Avg Shape Index, Avg Curvedness (smoothed mesh) 1.2e-8
Bounding Cylinder Volume (approximate search) 2.6e-2

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 moves extract_mesh_features values 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-mesh Avg Shape Index by up to 57% and Bounding Cylinder Volume by 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 in extract_mesh_features at ordinary units with this change.

Timings on two real VPA nuclei (about 330k voxels each), per nucleus:

features computed CPU GPU (A40) speedup max CPU–GPU difference
GPU-native (all but the hull, bounding-shape and fractal-dimension features) 1.15 s 0.03 s 39× 4e-11
+ hull and box features, on the host 1.25 s 0.36 s 3.5× 6e-11
everything, incl. the old QEM fractal dimension, on the host (before 50cdcfd) 1.88 s 0.93 s 2.0× 5e-11

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 Dimension takes about 21 ms per mask on the CPU for a 151 × 151 footprint.

Notes

  • Compiling the CUDA kernels needs the CUDA headers. Point CUDA_PATH at a CUDA toolkit install and put its lib64 on LD_LIBRARY_PATH for NVRTC's builtins. CuPy's [ctk] extra provided neither. The aics_workflows kernels 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 bincount accumulates with atomic adds. Every other feature and every mesh is bitwise repeatable.

  • On a raw voxel mesh, without a smoothed mesh, Avg Shape Index now 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 Index reads about 0.1 below the truth, Avg Curvedness about 6% above it and Total Absolute Gaussian Curvature about 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 Volume and Extent come from trimesh's oriented_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):

  • full suite on CPU (uv run python -m pytest -q): 969 passed, 223 skipped
  • tests/feature tests/test_image_utils.py tests/segmentation with CuPy 14.2.0 on an A40: 509 passed, 23 skipped (22 need cellpose or itk, 1 needs two GPUs)
  • tests/feature/test_mesh_gpu.py on a two-GPU node (2× A40): 43 passed, none skipped
  • on the same node, extract_surface_features on 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. Through mask2mesh the 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/
  • CI (the GPU tests skip there)

🤖 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:

  • Add GPU-native mesh extraction and feature measurement for NumPy and CuPy label images and masks.
  • Provide CUDA marching cubes compatible with scikit-image output and a device-aware ArrayMesh implementation.
  • Add configurable 3D and optional in-plane outline fractal-dimension features.
  • Add a SciPy-compatible Gaussian filter for consistent CPU/GPU image processing.

Bug Fixes:

  • Ensure generated mask meshes have outward orientation, including non-watertight and ascent-direction meshes.
  • Keep GPU meshing and fractal-dimension calculations on the input device without unintended host mesh construction.

Enhancements:

  • Replace decimation-based fractal dimension with a blur-scale surface-area estimator normalized by a smooth twin, including validation and thin-object warnings.
  • Support GPU dispatch for mesh feature extraction while retaining host fallbacks for hull and bounding-shape operations.
  • Centralize CUDA compilation and launch helpers for reuse across GPU modules.
  • Remove the fast-simplification dependency from mesh features.

Documentation:

  • Document GPU mesh support, ArrayMesh behavior, fractal-dimension estimators, and optional outline measurements.

Tests:

  • Add CPU/GPU parity, marching-cubes compatibility, ArrayMesh equivalence, fractal-dimension, warning, orientation, and Gaussian-filter coverage.

alxndrkalinin and others added 30 commits October 29, 2026 15:03
extract_mesh_features computed all 20 features whatever was asked for.
Mean curvature alone took 15.4 s of a 15.8 s per-label total on a
13k-vertex nucleus, so extract_features(img, ["Volume"]) paid for it on
every label. Each feature is now a registry entry evaluated only when
requested; trimesh caches the shared convex hull and bounding
primitives, so features that share them still compute them once.
Default output is bitwise identical to before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
The test job synced only the dev extra, so trimesh was missing and
tests/feature/test_mesh.py skipped at import on every run: all of its
tests had never executed in CI.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
Min/Med/Max Axis Length were the sorted extents of the axis-aligned
bounding box, so they measured how an object sat in the image rather
than its shape: turning an ellipsoid with axes (12, 16, 48) by 45
degrees about z gave (12, 36, 36). Extent divided by the same box and
fell from 0.52 to 0.31.

The axis lengths are now the full axes of the ellipsoid with the same
principal moments of inertia, regionprops' axis_major_length
convention: (12.02, 15.96, 47.70) at 0 degrees, (12.12, 16.01, 47.66)
at 45. Extent divides by the oriented bounding box volume (0.50-0.55
across 0/30/45 degrees, against pi/6 = 0.524 for an ideal ellipsoid).

Scale (the axis-aligned box diagonal) and Bounding Box Volume are
dropped: both are defined on the image axes, and the oriented box
volume and the axis lengths already carry what they measured.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
Both curvature features were vertex averages of trimesh's curvature
measures integrated over balls of radius 1 in the units of spacing. The
radius did not follow the unit or the resolution: the same voxels with
spacing 0.1 instead of 1 changed them 78x and 11x rather than 100x and
10x, and sampling the same physical sphere twice as finely changed the
Gaussian one 0.46x. The mean curvature measure also looped over
vertices in Python and took 15.4 s of a 15.8 s per-label total for a
13k-vertex nucleus.

They are now surface averages. The mean curvature integrates as half
the sum of edge length times signed dihedral angle (Cohen-Steiner and
Morvan), giving 1/R within 2.2% on voxelized spheres of radius 4-24 and
converging under finer sampling. The Gaussian curvature integrates to
the angle-defect sum, 2 pi times the Euler characteristic exactly, so
it is 4 pi / area for objects without handles or cavities. Both are
vectorized: the full default feature set now takes 0.29 s for the
13k-vertex nucleus and 0.83 s for a 51k-vertex one (was 208 s).

Neither needs mesh.face_adjacency_tree, so rtree leaves the mesh extra
and the per-function dependency guard goes back to a trimesh check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
The formula is Wadell's sphericity for any body, nothing specific to
ellipsoids, and the name suggested otherwise. No caller outside mesh.py
used the old name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
An unknown name raised a bare KeyError only after every feature of the
first label had been computed, and an image without labels accepted it
silently. Names are now checked up front in extract_features and
extract_mesh_features, and the ValueError lists the available ones.

features=[] now yields an (n_labels, 0) matrix instead of silently
falling back to the full default set.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
voxel.extract_features returns (labels, values, column_names) while the
mesh variant returned only (labels, values), so the two could not be
swapped and callers had to rebuild the names themselves. The mesh
variant now returns the same triple.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
cubic.feature did not export the mesh module, so cubic.feature.mesh
raised AttributeError unless the submodule had been imported
explicitly. A module-level __getattr__ now imports it on first access,
the pattern cubic.scipy already uses, so the 0.75-3 s trimesh import
still stays off the import path of the voxel and texture features.

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
The inline literal was split across two docstring lines, which breaks
its rendering.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
_avg_mean_curvature rebuilt Trimesh.integral_mean_curvature, a cached
trimesh property that gives the same value (equal to the last bit on a
voxelized ball). trimesh signed the dihedral angles only from 4.6.12 on;
4.6.11 returns 71.8 instead of 2 pi^2 R = 59.2 on a torus. The mesh
extra therefore now requires trimesh>=4.6.12. The mesh tests pass on
both 4.6.12 and the locked 4.11.2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
_TRIMESH_AVAILABLE restated whether the import had bound trimesh, and
was set in three places to stay in sync with it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
trimesh annotates volume, area and mass as numpy float64, which the
numpy 2.0 stubs do not treat as float. With trimesh installed, mypy
rejected the registry's Callable[..., float] values and the sphericity
call. CI's lint job runs without trimesh, so it did not see this. The
registry now returns SupportsFloat, which extract_mesh_features already
converts, and sphericity receives plain floats.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
extract_features and extract_mesh_features each repeated the same
default-then-validate block. _resolve_features now returns the
resolved list, so the default and the error message live in one place.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
_equivalent_ellipsoid_axes described the bounding-box extents it
replaced, with the numbers of one example. That history is in the tests
and the commit log; the docstring now states only what the code does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
Three tests each defined the same extract_surface_features stub, so
adding the features parameter meant three identical edits. A
surface_calls fixture now records each call's mask and spacing. The
ball, ellipsoid and torus builders share _centred_grid instead of three
spellings of a centred meshgrid, one of them with a hardcoded centre.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
The subprocess imported trimesh only to check the last assertion,
3.9 s of the file's 7.6 s. It now checks only that importing
cubic.feature skips trimesh. The in-process call to the package
__getattr__ covers the access path. The test takes 0.11 s.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
With "mesh" in __all__, `from cubic.feature import *` resolved it
through __getattr__ and loaded trimesh, undoing the lazy import, and
warned on hosts without trimesh. Attribute access still loads it on
demand.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
tests/test_plot_utils.py skipped at import in CI for want of
matplotlib, the same gap the mesh extra had. The plot extra is as light,
so the test job installs it too. cellpose stays out because it pulls in
torch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
mesh_feature_list and AGENTS.md called every feature orientation-
invariant. None is defined on the image axes any more, but voxelization
moves all of them a little, and trimesh's oriented box and bounding
cylinder come from approximate minimum searches: Extent spans 0.50-0.55
for one ellipsoid at 0, 30 and 45 degrees. The docs now say so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
mypy types every unknown attribute of a module that defines __getattr__
with that function's return type, so cubic.feature.regionprop type-
checked as a module and failed only at run time. __getattr__ is now
defined only outside type checking, and mypy learns about mesh from a
TYPE_CHECKING import. The typo is now reported ("Module has no
attribute 'regionprop'; maybe 'regionprops'?").

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
The subprocess had no timeout, so an import that hangs in the child,
such as CUDA probing on a node with a broken driver, would stall the
whole pytest run without output.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
extract_features(img, "Volume") iterated the string and reported
Unknown mesh features ['V', 'o', 'l', 'u', 'm', 'e']. A string now
raises a TypeError that names it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
…ristic

As a surface average, the Gaussian curvature is exactly
2 pi * euler_number / area by Gauss-Bonnet, so the column was 4 pi /
Area for every label without holes and carried nothing beyond Area and
one integer. That integer is now its own column: twice the separate
pieces plus cavities, minus twice the handles (2 for a ball, 4 for a
hollow ball or two balls, 0 for a torus). It is free to compute and
does not depend on the spacing unit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
A hollow ball's shells must keep their orientation relative to the
material: the cavity faces inward and counts as concave, so the hollow
ball integrates to the outer ball minus the inner one (82.1), not their
sum (244.2). mask2mesh already does this, because fix_normals runs
without multibody, but nothing tested it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
extract_surface_features built the mesh before the names reached a
check, and extract_mesh_features validated the mesh geometry first. An
unknown name with an open mesh therefore surfaced as "Mesh volume must
be finite and positive" instead of the unknown-feature error, and a
valid mask was meshed for nothing. Both entry points now resolve the
names first, as extract_features already did.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
extract_features(img, []) still meshed and validated every label just
to return an (n_labels, 0) matrix, and could raise a geometry error
instead. It now returns that matrix straight away.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
Adds Total Absolute Gaussian Curvature, Avg Shape Index and Avg
Curvedness, the ShapeTools shape measures, chosen by how well they
separate shape states rather than by parity:

- Any average of Gaussian curvature is fixed by Gauss-Bonnet, so the
  shape signal is in where K is negative. The integral of |K| over 4 pi
  is 1 for every convex body and grows with saddle regions (grooves,
  waists, the necks of lobes); unitless.
- Shape index (Koenderink) and curvedness come from per-vertex principal
  curvatures computed as in LONI ShapeTools (Meyer et al. angle defect
  and edge-based mean curvature over the mixed Voronoi area), averaged
  over the surface by area rather than by vertex, so the result does
  not depend on how the mesher distributes vertices.

Per-vertex curvature on a voxel staircase measures the staircase, so
these are computed on a mesh of the mask blurred at curvature_sigma
(default twice the coarsest spacing, isotropic in physical units), a new
option of extract_features, extract_surface_features and mask2mesh
(sigma). Nothing is blurred unless one of them is requested, and an
object too small to survive the blur gets NaN for them with a warning.

On synthetic nuclei with random size, axes, rotation, sub-voxel position
and boundary noise (3 seeds x 2 noise levels, 30 per class), total |K|
separated folded from smooth ellipsoids with AUC 1.00 and lobulated with
0.82 at rotation CV 0.000, against 0.53-0.64 for every average of K
(including the 2021 ball measure and the ShapeTools vertex mean), and
shape index and curvedness added 0.02-0.06 cross-validated AUC on top of
Solidity, Sphericity and mean curvature. On analytic shapes: ball total
|K| 1.000, torus 2.04 (exact 2), unit change rescales curvedness by 10
and leaves the rest unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
Completes the ShapeTools shape list with the LONI GSA fractal dimension,
whose module sampled the mesh at triangle counts between a minimum and a
maximum: the smoothed mesh is simplified by quadric error metrics to six
face counts from a sixteenth of its own up to all of it, and
D = 2 + 2 * slope of log area against log face count (about 2 for a
smooth surface; 2.005 on a voxelized ball).

On the synthetic nuclei it is weak on its own (AUC 0.59-0.66) and adds
signal only in some settings (+0.05 cross-validated AUC for folded
nuclei at high boundary noise, -0.03 for lobulated at low noise); box
counting on the mask boundary added nothing and was not kept.

Decimation needs fast-simplification, now in the mesh extra (>=0.1.9:
0.1.7 does not import under NumPy 2). Without it the feature raises a
RuntimeError naming the package.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
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
@sourcery-ai

sourcery-ai Bot commented Nov 18, 2026

Copy link
Copy Markdown
Contributor

Sorry @alxndrkalinin, your pull request is larger than the review limit of 150,000 diff characters

alxndrkalinin and others added 8 commits November 17, 2026 23:21
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
@alxndrkalinin

Copy link
Copy Markdown
Owner Author

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.

mask2mesh and extract_mesh_features work in any length unit

  • Fixed in 0558944: mask2mesh builds the mesh in units of the finest spacing and scales the result to the caller's units. Before, a ball of radius 10 at spacing 1e-8 came back with 1,402 of its 1,896 vertices and not watertight
  • Fixed in 1c84895: extract_mesh_features measures copies scaled to the mesh's own edge scale and converts the values back. Before, the mean curvature of that ball was 32 times too high at spacing 1e-7
  • Addressed in 57a0e95: the docstrings name the tolerance that causes it (trimesh zeroes a face normal when the face's cross product is below 1e-13, which happens for edges shorter than about 3e-7; the merge of vertices closer than 1e-8 is separate) and state in one place which attributes of a returned mesh hold in tiny units

Clean-up and tests

Left as they are, with the reason: extract_mesh_features normalises by the mesh's edge scale and extract_surface_features by the finest spacing, because the direct function has only the mesh to go by (the two agree to 1.2e-8 on the smoothed curvature features and 4.8e-7 on the mean curvature; the approximate bounding cylinder can differ by up to 2.6e-2); a trimesh primitive is measured as its triangles; repeated calls on one mesh do not reuse trimesh's cache on it.

alxndrkalinin and others added 9 commits November 18, 2026 17:13
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
@alxndrkalinin

Copy link
Copy Markdown
Owner Author

Commits after 896eb1f, from the user's decisions on items 1 and 4 and from the review rounds on them:

  • Addressed in d30c98c: a blur that provably leaves nothing of the mask is skipped and takes the vanished-mask path (large-blur thread from feat(feature): ShapeTools shape measures on a smoothed mesh (total |K|, shape index, curvedness, fractal dimension) #62).
  • Addressed in fb732db: rounding residues of flat vertices set to 0 in _principal_curvatures (item 1).
  • Addressed in 1a096d4: the blur bound's mirror-image argument stated per voxel; truncate dropped (review).
  • Addressed in 6c649bc: the guard's property test runs _padded_blur itself; 6.3 TB, not 3 TB (review).
  • Addressed in 3eefac6: the mask is counted once per image for all blur scales (review, efficiency).
  • Fixed in 30bb466: _edge_unit summed device-computed areas, so NumPy and CuPy could measure at units an ulp apart (found while checking device agreement at anisotropic spacing).
  • Addressed in b3ea2b4: docstrings of the flat-residue tests state what each zeroes.
  • Fixed in 6067b79: the face areas themselves differ between the devices under CuPy 14.0.1, so the unit is now built from the vertex extremes (review of 30bb466).
  • Addressed in c9467fe: test that the unit ignores vertices no face uses (review of 6067b79).

Base automatically changed from feat/mesh-curvature-features to main November 20, 2026 20:15
main holds #62 squashed and #67's spectral README note. The mesh files
and the mesh extra keep this branch's side: it already contains #62's
head, and it removed fast-simplification on purpose when the fractal
dimension stopped decimating. The merge adds only the README note.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
@alxndrkalinin

Copy link
Copy Markdown
Owner Author

These commits reached this branch by merging #62's branch (feat/mesh-curvature-features) into it. They belong to #62, were cited in #62's review threads, and are on main through #62's squash (308c89c). Each is accounted for under #62:

The merge of main into this branch (0792729) adds only #67's README note; the mesh files and the mesh extra keep this branch's side.

@alxndrkalinin
alxndrkalinin merged commit 3835b40 into main Nov 22, 2026
9 checks passed
alxndrkalinin added a commit that referenced this pull request Nov 22, 2026
main holds #63 squashed, whose tree equals the feat/mesh-gpu head this
branch was built on. Every conflicting file keeps this branch's side;
the merge adds only #67's spectral README note.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
alxndrkalinin added a commit that referenced this pull request Nov 25, 2026
…, fixed-order GPU sums (#66)

* perf(feature): compute only the requested mesh features

extract_mesh_features computed all 20 features whatever was asked for.
Mean curvature alone took 15.4 s of a 15.8 s per-label total on a
13k-vertex nucleus, so extract_features(img, ["Volume"]) paid for it on
every label. Each feature is now a registry entry evaluated only when
requested; trimesh caches the shared convex hull and bounding
primitives, so features that share them still compute them once.
Default output is bitwise identical to before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* ci: install the mesh extra so the mesh tests run

The test job synced only the dev extra, so trimesh was missing and
tests/feature/test_mesh.py skipped at import on every run: all of its
tests had never executed in CI.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* fix(feature): make mesh axis lengths and extent orientation-invariant

Min/Med/Max Axis Length were the sorted extents of the axis-aligned
bounding box, so they measured how an object sat in the image rather
than its shape: turning an ellipsoid with axes (12, 16, 48) by 45
degrees about z gave (12, 36, 36). Extent divided by the same box and
fell from 0.52 to 0.31.

The axis lengths are now the full axes of the ellipsoid with the same
principal moments of inertia, regionprops' axis_major_length
convention: (12.02, 15.96, 47.70) at 0 degrees, (12.12, 16.01, 47.66)
at 45. Extent divides by the oriented bounding box volume (0.50-0.55
across 0/30/45 degrees, against pi/6 = 0.524 for an ideal ellipsoid).

Scale (the axis-aligned box diagonal) and Bounding Box Volume are
dropped: both are defined on the image axes, and the oriented box
volume and the axis lengths already carry what they measured.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* fix(feature): average mesh curvature over the surface, drop rtree

Both curvature features were vertex averages of trimesh's curvature
measures integrated over balls of radius 1 in the units of spacing. The
radius did not follow the unit or the resolution: the same voxels with
spacing 0.1 instead of 1 changed them 78x and 11x rather than 100x and
10x, and sampling the same physical sphere twice as finely changed the
Gaussian one 0.46x. The mean curvature measure also looped over
vertices in Python and took 15.4 s of a 15.8 s per-label total for a
13k-vertex nucleus.

They are now surface averages. The mean curvature integrates as half
the sum of edge length times signed dihedral angle (Cohen-Steiner and
Morvan), giving 1/R within 2.2% on voxelized spheres of radius 4-24 and
converging under finer sampling. The Gaussian curvature integrates to
the angle-defect sum, 2 pi times the Euler characteristic exactly, so
it is 4 pi / area for objects without handles or cavities. Both are
vectorized: the full default feature set now takes 0.29 s for the
13k-vertex nucleus and 0.83 s for a 51k-vertex one (was 208 s).

Neither needs mesh.face_adjacency_tree, so rtree leaves the mesh extra
and the per-function dependency guard goes back to a trimesh check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* refactor(feature): rename ellipsoid_sphericity to sphericity

The formula is Wadell's sphericity for any body, nothing specific to
ellipsoids, and the name suggested otherwise. No caller outside mesh.py
used the old name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* fix(feature): reject unknown mesh feature names before meshing

An unknown name raised a bare KeyError only after every feature of the
first label had been computed, and an image without labels accepted it
silently. Names are now checked up front in extract_features and
extract_mesh_features, and the ValueError lists the available ones.

features=[] now yields an (n_labels, 0) matrix instead of silently
falling back to the full default set.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* feat(feature): return column names from mesh.extract_features

voxel.extract_features returns (labels, values, column_names) while the
mesh variant returned only (labels, values), so the two could not be
swapped and callers had to rebuild the names themselves. The mesh
variant now returns the same triple.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* feat(feature): expose cubic.feature.mesh, imported on first access

cubic.feature did not export the mesh module, so cubic.feature.mesh
raised AttributeError unless the submodule had been imported
explicitly. A module-level __getattr__ now imports it on first access,
the pattern cubic.scipy already uses, so the 0.75-3 s trimesh import
still stays off the import path of the voxel and texture features.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* docs: describe the mesh feature module in AGENTS.md

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* docs(feature): keep the equivalent-ellipsoid formula on one line

The inline literal was split across two docstring lines, which breaks
its rendering.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* refactor(feature): use trimesh's integral_mean_curvature

_avg_mean_curvature rebuilt Trimesh.integral_mean_curvature, a cached
trimesh property that gives the same value (equal to the last bit on a
voxelized ball). trimesh signed the dihedral angles only from 4.6.12 on;
4.6.11 returns 71.8 instead of 2 pi^2 R = 59.2 on a torus. The mesh
extra therefore now requires trimesh>=4.6.12. The mesh tests pass on
both 4.6.12 and the locked 4.11.2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* refactor(feature): test trimesh is None instead of a mirror flag

_TRIMESH_AVAILABLE restated whether the import had bound trimesh, and
was set in three places to stay in sync with it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* fix(feature): type the mesh feature registry for numpy float returns

trimesh annotates volume, area and mass as numpy float64, which the
numpy 2.0 stubs do not treat as float. With trimesh installed, mypy
rejected the registry's Callable[..., float] values and the sphericity
call. CI's lint job runs without trimesh, so it did not see this. The
registry now returns SupportsFloat, which extract_mesh_features already
converts, and sphericity receives plain floats.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* refactor(feature): resolve mesh feature names in one helper

extract_features and extract_mesh_features each repeated the same
default-then-validate block. _resolve_features now returns the
resolved list, so the default and the error message live in one place.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* docs(feature): keep regression history out of mesh docstrings

_equivalent_ellipsoid_axes described the bounding-box extents it
replaced, with the numbers of one example. That history is in the tests
and the commit log; the docstring now states only what the code does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* test(feature): share the meshing stub and grid helper in mesh tests

Three tests each defined the same extract_surface_features stub, so
adding the features parameter meant three identical edits. A
surface_calls fixture now records each call's mask and spacing. The
ball, ellipsoid and torus builders share _centred_grid instead of three
spellings of a centred meshgrid, one of them with a hardcoded centre.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* test(feature): keep the trimesh import out of the lazy-export test

The subprocess imported trimesh only to check the last assertion,
3.9 s of the file's 7.6 s. It now checks only that importing
cubic.feature skips trimesh. The in-process call to the package
__getattr__ covers the access path. The test takes 0.11 s.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* fix(feature): keep mesh out of cubic.feature.__all__

With "mesh" in __all__, `from cubic.feature import *` resolved it
through __getattr__ and loaded trimesh, undoing the lazy import, and
warned on hosts without trimesh. Attribute access still loads it on
demand.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* ci: install the plot extra so the plot tests run

tests/test_plot_utils.py skipped at import in CI for want of
matplotlib, the same gap the mesh extra had. The plot extra is as light,
so the test job installs it too. cellpose stays out because it pulls in
torch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* docs(feature): state how far mesh features still vary with orientation

mesh_feature_list and AGENTS.md called every feature orientation-
invariant. None is defined on the image axes any more, but voxelization
moves all of them a little, and trimesh's oriented box and bounding
cylinder come from approximate minimum searches: Extent spans 0.50-0.55
for one ellipsoid at 0, 30 and 45 degrees. The docs now say so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* fix(feature): keep the lazy __getattr__ from hiding typos from mypy

mypy types every unknown attribute of a module that defines __getattr__
with that function's return type, so cubic.feature.regionprop type-
checked as a module and failed only at run time. __getattr__ is now
defined only outside type checking, and mypy learns about mesh from a
TYPE_CHECKING import. The typo is now reported ("Module has no
attribute 'regionprop'; maybe 'regionprops'?").

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* test(feature): time out the fresh-interpreter import check

The subprocess had no timeout, so an import that hangs in the child,
such as CUDA probing on a node with a broken driver, would stall the
whole pytest run without output.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* fix(feature): reject a bare string as the mesh feature list

extract_features(img, "Volume") iterated the string and reported
Unknown mesh features ['V', 'o', 'l', 'u', 'm', 'e']. A string now
raises a TypeError that names it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* feat(feature): replace Avg Gaussian Curvature with the Euler characteristic

As a surface average, the Gaussian curvature is exactly
2 pi * euler_number / area by Gauss-Bonnet, so the column was 4 pi /
Area for every label without holes and carried nothing beyond Area and
one integer. That integer is now its own column: twice the separate
pieces plus cavities, minus twice the handles (2 for a ball, 4 for a
hollow ball or two balls, 0 for a torus). It is free to compute and
does not depend on the spacing unit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* test(feature): pin the cavity sign in the mean curvature

A hollow ball's shells must keep their orientation relative to the
material: the cavity faces inward and counts as concave, so the hollow
ball integrates to the outer ball minus the inner one (82.1), not their
sum (244.2). mask2mesh already does this, because fix_normals runs
without multibody, but nothing tested it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* fix(feature): check mesh feature names before meshing or validating

extract_surface_features built the mesh before the names reached a
check, and extract_mesh_features validated the mesh geometry first. An
unknown name with an open mesh therefore surfaced as "Mesh volume must
be finite and positive" instead of the unknown-feature error, and a
valid mask was meshed for nothing. Both entry points now resolve the
names first, as extract_features already did.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* perf(feature): skip meshing when no mesh features are requested

extract_features(img, []) still meshed and validated every label just
to return an (n_labels, 0) matrix, and could raise a geometry error
instead. It now returns that matrix straight away.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* feat(feature): curvature-distribution mesh features on a smoothed mesh

Adds Total Absolute Gaussian Curvature, Avg Shape Index and Avg
Curvedness, the ShapeTools shape measures, chosen by how well they
separate shape states rather than by parity:

- Any average of Gaussian curvature is fixed by Gauss-Bonnet, so the
  shape signal is in where K is negative. The integral of |K| over 4 pi
  is 1 for every convex body and grows with saddle regions (grooves,
  waists, the necks of lobes); unitless.
- Shape index (Koenderink) and curvedness come from per-vertex principal
  curvatures computed as in LONI ShapeTools (Meyer et al. angle defect
  and edge-based mean curvature over the mixed Voronoi area), averaged
  over the surface by area rather than by vertex, so the result does
  not depend on how the mesher distributes vertices.

Per-vertex curvature on a voxel staircase measures the staircase, so
these are computed on a mesh of the mask blurred at curvature_sigma
(default twice the coarsest spacing, isotropic in physical units), a new
option of extract_features, extract_surface_features and mask2mesh
(sigma). Nothing is blurred unless one of them is requested, and an
object too small to survive the blur gets NaN for them with a warning.

On synthetic nuclei with random size, axes, rotation, sub-voxel position
and boundary noise (3 seeds x 2 noise levels, 30 per class), total |K|
separated folded from smooth ellipsoids with AUC 1.00 and lobulated with
0.82 at rotation CV 0.000, against 0.53-0.64 for every average of K
(including the 2021 ball measure and the ShapeTools vertex mean), and
shape index and curvedness added 0.02-0.06 cross-validated AUC on top of
Solidity, Sphericity and mean curvature. On analytic shapes: ball total
|K| 1.000, torus 2.04 (exact 2), unit change rescales curvedness by 10
and leaves the rest unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* feat(feature): fractal dimension of the smoothed mesh under decimation

Completes the ShapeTools shape list with the LONI GSA fractal dimension,
whose module sampled the mesh at triangle counts between a minimum and a
maximum: the smoothed mesh is simplified by quadric error metrics to six
face counts from a sixteenth of its own up to all of it, and
D = 2 + 2 * slope of log area against log face count (about 2 for a
smooth surface; 2.005 on a voxelized ball).

On the synthetic nuclei it is weak on its own (AUC 0.59-0.66) and adds
signal only in some settings (+0.05 cross-validated AUC for folded
nuclei at high boundary noise, -0.03 for lobulated at low noise); box
counting on the mask boundary added nothing and was not kept.

Decimation needs fast-simplification, now in the mesh extra (>=0.1.9:
0.1.7 does not import under NumPy 2). Without it the feature raises a
RuntimeError naming the package.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* refactor: share the SciPy-rounding Gaussian filter in image_utils

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

* feat(feature): CUDA port of skimage's Lewiner marching cubes

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

* feat(feature): ArrayMesh, a trimesh-compatible mesh on CPU or GPU arrays

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

* feat(feature): mesh features on the GPU for CuPy input

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

* docs: describe the GPU mesh path in AGENTS.md

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* feat(feature): fractal dimension from multi-scale area, on CPU or GPU

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

* fix(feature): warn when fractal dimension is NaN for a sheet thinner 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

* fix(feature): merge equal and unreferenced vertices in ArrayMesh like 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

* fix(feature): ArrayMesh raises for delegated methods that change the 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

* fix(feature): run CUDA marching cubes on the input volume's device

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

* fix: keep the imaginary part in gaussian_filter_like_scipy on the GPU

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

* refactor(feature): call np. in ArrayMesh adjacency, not get_array_module

_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

* refactor(feature): return ArrayMesh adjacency edges, not stash them

_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

* refactor(feature): share one lexsort row-grouping helper for meshes

_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

* refactor(feature): drop empty-volume guards in CUDA marching cubes

_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

* refactor: share the CUDA compile and launch helpers in cubic.cuda

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

* refactor(feature): mesh mask2mesh through the _marching_cubes seam

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

* perf(feature): blur the mask at curvature_sigma once per object

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

* perf(feature): crop the fractal-dimension twin to the mask's frame

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(feature): share the GPU mesh comparison and use default features

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

* fix(feature): round the GPU default level like skimage's

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

* fix(feature): reject a spacing of other than three values on the GPU

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

* fix(feature): keep ArrayMesh's own attribute errors from reaching trimesh

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

* feat(feature): warn when Fractal Dimension spans under a factor of 2

_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

* fix(feature): import skimage's private marching-cubes tables guardedly

_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

* refactor(feature): upload the marching-cubes tables with cubic.cuda.ascupy

_kernels copied the lookup tables to the device with cp.asarray inside
`with cp.cuda.Device(device_id)`. ascupy is cp.asarray, so the tables
still land on the device entered there, now through the cubic.cuda
helper that AGENTS.md asks for.

The isinstance(volume, cp.ndarray) device choice in marching_cubes
stays: get_device also returns "GPU" for a CUDA torch tensor, whose
.device is a torch.device rather than a CuPy device to enter.

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

* refactor(feature): import trimesh at the top of _array_mesh.py

ArrayMesh.to_trimesh imported trimesh inside the method, so a missing
trimesh surfaced as a bare ModuleNotFoundError on first delegation.
The module now imports it at the top under the same guard as mesh.py,
without a second warning, and to_trimesh raises mesh.py's
RuntimeError ("trimesh is required for mesh operations. Install with
'cubic[mesh]'") when it is missing.

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

* docs(feature): describe mesh feature sources and GPU degenerate faces

- mesh_feature_list said its features are extracted from a trimesh
  object; Fractal Dimension is measured on the mask. It now describes
  the surface features of a label that extract_features and
  extract_surface_features return.
- The CUDA marching_cubes and its module said the mesh matches
  skimage's up to vertex and face order. With allow_degenerate=False
  it merges every coincident vertex, where skimage merges only those of
  degenerate faces, and keeps vertices used only by the dropped faces,
  which ArrayMesh drops. Both docstrings now say so; behaviour is
  unchanged.
- test_mask2mesh_on_gpu said only spacing is accepted on the GPU;
  level and allow_degenerate are too since mask2mesh goes through
  _marching_cubes.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5

* fix(feature): do not warn about a short Fractal Dimension scale range

e1d3e69 warned when curvature_sigma was under twice the finest voxel
spacing, on the argument that a fit over a short log range is
ill-conditioned. The measurement made for that commit does not show it:
over 12 smooth ellipsoids (semi-axes 7-17 voxels, isotropic spacing) the
SD of Fractal Dimension is 0.0007 at ratios 1.05, 1.1, 1.25 and 1.5,
against 0.0012 at 2 and 0.0061 at 3. The area ratio to the smooth twin
carries too little jitter for the short range to amplify, so the warning
would flag a valid setting without evidence of a problem. The NaN and
warning for a curvature_sigma at or below the finest spacing stay, and
the curvature_sigma docstring keeps that rule.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5

* feat(feature): set the Fractal Dimension scale window with fractal_scales

extract_features and extract_surface_features take fractal_scales, the
(lowest, highest) blur scale of the fit in units of spacing. The smooth
twin is the mask blurred at the highest scale, and the fit keeps 5
geometric levels. In a sweep over three nucleus datasets, the 3D
estimate was unbiased only while the top scale stayed below half the
object's smallest half-extent, and the useful window started a few
voxels above the resolved edge rather than at one voxel, so the window
needs to be set apart from curvature_sigma.

None keeps the window from the finest voxel spacing to curvature_sigma
and reuses the curvature blur. On 8 test masks (ellipsoids, rough
ellipsoids, slabs, hollow balls; isotropic and (0.29, 0.108, 0.108)
spacing) every default feature is bitwise unchanged on the CPU and on the
GPU, apart from the three curvature-distribution features, which vary by
up to 1.1e-8 between GPU runs of the unchanged code on a flat slab. A
window that is not two finite numbers with 0 < lowest < highest raises
ValueError before any meshing.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5

* feat(feature): warn for objects too thin for Fractal Dimension's scales

In a sweep over three nucleus datasets, the 3D fractal dimension was
unbiased on smooth shapes only while the top blur scale stayed at most
half the object's smallest half-extent; above that it reads low, which
makes it unreliable for flat nuclei. extract_surface_features now warns
when the top scale (curvature_sigma, or the highest of fractal_scales)
exceeds a quarter of Min Axis Length, the shortest axis of the
same-inertia ellipsoid of the raw mesh, and still returns the value.

The text is the same for every object, so Python's default filter shows
it once for a label image of many thin objects: three slabs of different
size (Min Axis Length 1.93, 2.31, 2.32 um at a 0.6 um top scale) give
one warning. The axes are computed only when Fractal Dimension is
requested and finite. Default features of the 8 baseline masks are
bitwise unchanged on the CPU, and on the GPU apart from the
run-to-run noise of the three curvature-distribution features.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5

* feat(feature): add Outline Fractal Dimension of the z-projection

Outline Fractal Dimension runs the Fractal Dimension construction on the
outline of the mask's projection along the first axis: 1 - slope of log
contour length of the blurred footprint, relative to its smooth twin,
against log blur scale. In a sweep over three nucleus datasets, this
form was unbiased at any top scale, reproduced across segmenters as well
as volume, and separated cell states better than the 3D estimate, which
reads low for flat nuclei. Its default window is 4 to 16 times the
coarser in-plane spacing; fractal_scales sets it as for the 3D feature.

The contour length comes from the existing marching cubes, so the
feature runs on the mask's device: the blurred footprint stacked twice
one unit apart meshes to a ribbon whose area is the contour length. On
5 shapes, 3 spacings and 3 blur scales the ribbon matched skimage's
find_contours to 6.2e-8 relative, and an analytic disc to its 2 pi R up
to the polygon's own deficit. On CuPy input it matches the CPU to 1e-9.

Smooth elliptical footprints measure 0.992-0.999, and 4% and 8% outline
noise raise a 0.997 disc to 1.008 and 1.054. A quarter turn about the
first axis changes it by 1e-8, a 45 degree turn by 1.8e-4. It is the one
feature defined on the image axes, which mesh_feature_list now says.
The thin-object warning of Fractal Dimension points to it.

On 20 cpdino-v2 nuclei from each of mboc2021_astr_vpa,
scirep2018_fibroblast and scirep2018_pc3, fractal_scales=(0.4, 1.6)
reproduces the sweep's find_contours values to at most 1.06e-8.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5

* feat(feature): compute Outline Fractal Dimension only on request

At its default 4-to-16-voxel window the outline feature is NaN, with a
warning, for every footprint under about 51 voxels across: a smooth disc
of radius 25 voxels gives NaN, one of 25.5 voxels -0.15, and the value
reaches 0.95 at a radius of 32 voxels and 0.99 at 40. Computed by
default, it would warn for every small object, and it would put a
feature defined on the image axes into a default set that is otherwise
orientation-invariant.

mesh_feature_list() again returns the 22 default names of 7a5ebb5,
ending in Fractal Dimension; mesh_feature_list(optional=True) appends
Outline Fractal Dimension. features=None computes the defaults, an
explicit list may name either kind, and the unknown-name error lists
both. On the 8 baseline masks, extract_surface_features at default
arguments returns exactly the 7a5ebb5 keys and values (bitwise on the
CPU; on the GPU within 1.1e-8 for the three curvature-distribution
features, their run-to-run spread on a flat slab), and extract_features
returns 22 columns.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5

* feat(feature): set the outline window with outline_fractal_scales

fractal_scales set the window of both fractal features, but their
windows differ in kind: on a flat object a window that suits the outline
(say 0.8-1.6 um) puts the 3D estimate above a quarter of the object's
thickness, where it reads low and warns. fractal_scales now applies to
Fractal Dimension only, and a new keyword, outline_fractal_scales, on
extract_features and extract_surface_features, sets the window of
Outline Fractal Dimension, with the same form and validation; each
error names its keyword. The outline default stays 4 to 16 times the
coarser in-plane spacing.

Changing either window leaves the other feature bitwise unchanged
(tested on a rough cylinder). Default features of the 8 baseline masks
are unchanged: bitwise on the CPU, and on the GPU within the run-to-run
spread of the three curvature-distribution features.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5

* refactor(feature): compute both fractal features with one estimator

_fractal_dimension and _outline_fractal_dimension repeated one estimator:
the smooth twin, the geometric ladder of blur scales, the reuse of the
top scale, the ratio list, the vanishing warning and the fit. Both now
call _blur_ladder_dimension, which takes the N-dimensional mask, its
step, the window, a measure of the 0.5 level (surface area, or contour
length of the stacked ribbon) and the already computed top blur and top
measure, and returns mask.ndim - 1 - slope.

extract_surface_features resolves each feature's (lowest, highest) once,
instead of in three branches for the 3D window and inside the outline
estimator, and reuses the blur and level set at curvature_sigma whenever
the 3D top scale equals it, also for an explicit window. The thin-object
ratio is one constant, used by the condition and the warning text.

Default features of the 8 baseline masks are bitwise unchanged on the
CPU, and on the GPU within the run-to-run spread of the three
curvature-distribution features; Outline Fractal Dimension and Fractal
Dimension over custom windows are bitwise unchanged on 7 flat masks at
three spacings.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5

* perf(feature): pad the outline's 2D blurs by one pixel

_padded_blur pads by ceil(3 sigma) + 1 voxels and blurs in reflect
mode, so at the outline's default 16-pixel top scale a 151 x 151
footprint became 249 x 249 for each of its 10 blurs. With tight=True it
pads by one pixel and blurs with zeros beyond it (constant mode). On the
mask's frame and that ring the field is bitwise the same as the wide
blur's (checked on CPU and GPU for a rough disc, a box and a disc that
touch their crop on all four sides, and noise blobs, on (0.108, 0.108),
(0.2, 0.1) and (1, 1) planes at every ladder scale), and the ring stays
below 0.5 (at most 0.4814), so every contour closes inside the array.
Only Outline Fractal Dimension uses it; the 3D blurs keep their padding.

The outline estimator takes 20.9 ms instead of 34.6 ms on that
footprint (median of 7, CPU). Values move by at most 1.7e-8 relative on
7 flat masks, because the float32 contour vertices sit at a different
offset in the array; CPU and GPU agree to 3.7e-16 relative. On 20
cpdino-v2 nuclei per dataset the outline matches the fd_sweep
find_contours values to at most 5.2e-9 (mboc2021_astr_vpa), 9.8e-9
(scirep2018_fibroblast) and 1.1e-8 (scirep2018_pc3). Default features of
the 8 baseline masks are unchanged.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5

* refactor(feature): derive the default mesh features and simplify windows

mesh_feature_list now derives the default names from _MASK_FEATURES and
_OPTIONAL_FEATURES instead of a third tuple, and _fractal_window checks
0 < lowest < highest < inf in one comparison, which is also false for
NaN and either infinity (the validation test covers NaN in both places,
+inf, -inf, reversed, equal and zero windows).

Each default window is stated once, in the keyword that sets it, and
mesh_feature_list and curvature_sigma point to it; mesh_feature_list
says once that the fractal features are measured on the mask, and its
reflowed paragraph on the axis lengths is joined again. Default features
of the 8 baseline masks are unchanged.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5

* test(feature): pin the default feature count once and fold repeated cases

The default count of 22 is now pinned only in the test of the optional
list; the background-label and default-output tests use
len(mesh_feature_list()). The thin-object test checks that its one
warning points to Outline Fractal Dimension, which replaces a separate
test that repeated its slab call to match the text. The rotation test
measures the upright ellipsoid once, outside the loop, and the
default-output test is the one place that checks the outline stays out
of the defaults.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5

* fix(feature): attribute mesh feature warnings to the calling line

extract_features and extract_surface_features are wrapped by
_require_trimesh, which adds a frame, so with stacklevel=2 every warning
raised under them was attributed to that wrapper in cubic/feature/mesh.py
instead of to the code that called the public function. The thin-object
warning, both "vanishes" warnings, the warning for curvature_sigma not
above the finest spacing and the blur-ladder warning now use one
stacklevel constant, plus the frames of the helpers that raise them, so
a direct call to extract_surface_features attributes each to the
caller's line. Against the previous code, the new test fails for all
five warnings and passes with this change.

Through extract_features the caller is its per-label loop, one line
for every label, so the constant thin-object text is still shown once
per label image under the default filter; the docstring says why.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5

* refactor(feature): memoize the mask's blur per scale in surface features

extract_surface_features bound the blur, padding and level set at
curvature_sigma inside one branch and read them later under another
(Fractal Dimension's top scale equal to curvature_sigma), correct only
through an invariant held elsewhere in the function. A per-call memo of
the mask's blur, padding and level set at a scale, each computed at
most once, now serves the curvature features at curvature_sigma and
Fractal Dimension's top scale, so the reuse when the two are equal
follows from the memo.

An empty default window (curvature_sigma not above the finest spacing)
is now decided before any blur: it returns NaN with its own warning,
without blurring, and is no longer listed as vanishing when the mask
vanishes at curvature_sigma. The default output and warning texts of
the 8 baseline masks are unchanged, as is the bitwise equality of the
explicit (finest spacing, curvature_sigma) window with the default.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5

* fix(feature): raise TypeError for a fractal window that is not numbers

_fractal_window accepted b"12" as the window (49.0, 50.0) and a dict
through its keys, and raised ValueError for a scalar or a string, where
_resolve_features raises TypeError for a string. It now raises
TypeError, naming the keyword, unless the window is a sequence or 1D
array of real numbers (so for a scalar, str, bytes, a mapping or
non-numeric elements), and ValueError when the sequence has other than
two values or they are not finite with 0 < lowest < highest. Default
features of the 8 baseline masks are unchanged.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5

* perf(feature): pad the 3D fractal ladder's blurs by one voxel

The 3D ladder's nine extra blurs and marching-cubes runs per label (4
mask scales, 5 twin scales) padded by ceil(3 sigma / step) + 1 voxels a
side, about 1.9 times the voxels of a 40 x 100 x 100 crop at nucleus
spacing. _blur_ladder_dimension now uses the one-voxel tight padding
for every ladder blur, of both fractal features, so its tight flag is
gone; the top-scale blur, shared with the curvature mesh, keeps the
wide padding.

In 3D the field on the mask's frame and the one-voxel ring is bitwise
the same as the wide blur's, and the ring stays below 0.5 (at most
0.4307), on CPU and GPU, at every ladder scale of the mask and its twin,
for a rough ellipsoid, a box filling its crop, a slab filling the first
axis and a hollow ball, at (0.29, 0.108, 0.108), (0.3, 0.13, 0.13) and
isotropic spacing. Only the float32 vertex offsets change: Fractal
Dimension of the 8 baseline masks moves by at most 1.8e-8 on CPU and
GPU, every other feature is unchanged, and CPU and GPU agree to 2.3e-16
relative. Fractal Dimension of the 8 masks takes 853 ms instead of
1058 ms on the CPU (min of 5 per mask); on the shared GPU 841 and 356 ms
instead of 986 and 567 ms in two runs.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5

* test(feature): drop timings that no longer describe the mesh code

The 15.4 s mean-curvature timing belongs to the vertex-ball measure
that this branch replaced. The trimesh import time stays stated once,
in cubic/feature/__init__.py.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* test(feature): drop the unreachable default from the meshing stub

extract_features resolves the feature names and returns early for an
empty list before it calls extract_surface_features, so the stub never
receives None or an empty list.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* ci: install the mesh extra in the lint job so mypy sees trimesh's types

Without trimesh installed, mypy treats every trimesh type in
cubic/feature/mesh.py as Any, so the lint job could not report an error
against trimesh's own annotations. For example, passing
trimesh.__version__ (typed str | None) where a str is expected is
reported only with trimesh installed.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* fix(feature): refuse a trimesh older than 4.6.12 when mesh is imported

Trimesh.integral_mean_curvature exists in older releases too, with
unsigned dihedral angles. An environment that got trimesh from
somewhere other than the mesh extra therefore returned an overstated
Avg Mean Curvature on any concave surface, without an error.

The floor from pyproject.toml is now checked when cubic.feature.mesh is
imported, and an older release raises ImportError. A version part that
is not a plain number, such as a pre-release tag, is not compared.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* fix(feature): accept a one-shot iterable as the mesh feature list

The names were iterated once to find unknown ones and a second time to
build the list, so a generator, map or filter came back empty:
extract_features returned an (n, 0) matrix and no column names, without
an error.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* fix(feature): orient CPU meshes by the sign of their volume

trimesh.repair.fix_normals inverts a mesh only when trimesh calls it
watertight, and a mesh with an edge shared by four faces is not. Ragged
masks give such edges, so their marching-cubes mesh kept skimage's
inward winding, extract_mesh_features rejected its negative volume, and
extract_features failed for the whole label image. The GPU path already
flipped ArrayMesh by the sign of its volume and measured the same label.

The NumPy path now reverses the faces before building the Trimesh when
their signed volume is negative. Output is bitwise unchanged on meshes
that worked before, gradient_direction="ascent" stays outward, a
cavity's shell still faces the material, and trimesh keeps the mass
properties it caches instead of computing them again after invert().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* fix(feature): measure mesh features in units of the finest spacing

trimesh compares lengths with absolute tolerances of about 1e-8, so the
features depended on the unit of spacing. With a 100 nm voxel given in
metres, Avg Mean Curvature was 28 to 94 times off at spacing 3e-7 and
the call raised at 1e-7; Avg Shape Index and Avg Curvedness already
drifted by 1e-5 at spacing 1e-2.

extract_surface_features now divides the spacing, curvature_sigma and
both fractal windows by the finest spacing, measures, and multiplies
each feature by that unit to the power of its length dimension
(_FEATURE_DIMENSIONS). The computation sees only the ratios of the
spacings, so a feature converts with the unit to the rounding of one
multiplication, from 1e-9 to 1e3. Warnings and errors still print
lengths in the caller's units.

A spacing that is not finite and positive now raises ValueError. It
used to fail inside the blur, or, when all negative, to return the
features of the mirrored object.

Values at ordinary spacings move a little, because the approximate
searches and the tolerance tests now run at another scale: on nine test
masks at spacing (0.29, 0.108, 0.108) and 0.108, Bounding Cylinder
Volume by up to 6e-3, Total Absolute Gaussian Curvature by up to 4e-4,
Avg Shape Index and Avg Curvedness by up to 1.2e-4, and every other
feature by less than 1e-6. With no spacing or (1, 1, 1) the output is
bitwise unchanged.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* fix(feature): orient marching-cubes faces by their known winding

3b7c6e8 flipped CPU meshes by the sign of their volume. That needs a
pass over every face, its sign depends on the origin for an open surface
(a half-masked ball measured -1766.75, -4386.75 and +853.25 at three
shifts, reachable through marching_cubes_kwargs={"mask": ...}), and the
rule lived in _closed_mesh while ArrayMesh kept its own copy.

skimage winds every face inward for the default
gradient_direction="descent" and outward for "ascent", and the CUDA port
reverses its triangles as skimage does for "descent". _marching_cubes,
which both devices go through, now reverses the faces unless skimage was
asked for "ascent", so _closed_mesh is a plain wrapper again. ArrayMesh
keeps its flip for inward faces built directly from marching-cubes
output; given outward faces it no longer flips, so it computes its
integrals once per mesh instead of twice.

Output is bitwise unchanged on CPU against the code before 3b7c6e8 and
within 5e-15 on GPU. A new test checks that _marching_cubes' faces
enclose a positive volume on both devices.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* fix(feature): name both causes of a non-positive mesh volume

The volume guard in extract_mesh_features said the mesh was "likely not
watertight". Now that marching-cubes faces are oriented by their known
winding, that diagnosis is wrong both ways: a watertight but inverted
icosphere raises with it, and an open hemisphere with a positive s…
alxndrkalinin added a commit that referenced this pull request Nov 25, 2026
#68)

* perf(feature): compute only the requested mesh features

extract_mesh_features computed all 20 features whatever was asked for.
Mean curvature alone took 15.4 s of a 15.8 s per-label total on a
13k-vertex nucleus, so extract_features(img, ["Volume"]) paid for it on
every label. Each feature is now a registry entry evaluated only when
requested; trimesh caches the shared convex hull and bounding
primitives, so features that share them still compute them once.
Default output is bitwise identical to before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* ci: install the mesh extra so the mesh tests run

The test job synced only the dev extra, so trimesh was missing and
tests/feature/test_mesh.py skipped at import on every run: all of its
tests had never executed in CI.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* fix(feature): make mesh axis lengths and extent orientation-invariant

Min/Med/Max Axis Length were the sorted extents of the axis-aligned
bounding box, so they measured how an object sat in the image rather
than its shape: turning an ellipsoid with axes (12, 16, 48) by 45
degrees about z gave (12, 36, 36). Extent divided by the same box and
fell from 0.52 to 0.31.

The axis lengths are now the full axes of the ellipsoid with the same
principal moments of inertia, regionprops' axis_major_length
convention: (12.02, 15.96, 47.70) at 0 degrees, (12.12, 16.01, 47.66)
at 45. Extent divides by the oriented bounding box volume (0.50-0.55
across 0/30/45 degrees, against pi/6 = 0.524 for an ideal ellipsoid).

Scale (the axis-aligned box diagonal) and Bounding Box Volume are
dropped: both are defined on the image axes, and the oriented box
volume and the axis lengths already carry what they measured.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* fix(feature): average mesh curvature over the surface, drop rtree

Both curvature features were vertex averages of trimesh's curvature
measures integrated over balls of radius 1 in the units of spacing. The
radius did not follow the unit or the resolution: the same voxels with
spacing 0.1 instead of 1 changed them 78x and 11x rather than 100x and
10x, and sampling the same physical sphere twice as finely changed the
Gaussian one 0.46x. The mean curvature measure also looped over
vertices in Python and took 15.4 s of a 15.8 s per-label total for a
13k-vertex nucleus.

They are now surface averages. The mean curvature integrates as half
the sum of edge length times signed dihedral angle (Cohen-Steiner and
Morvan), giving 1/R within 2.2% on voxelized spheres of radius 4-24 and
converging under finer sampling. The Gaussian curvature integrates to
the angle-defect sum, 2 pi times the Euler characteristic exactly, so
it is 4 pi / area for objects without handles or cavities. Both are
vectorized: the full default feature set now takes 0.29 s for the
13k-vertex nucleus and 0.83 s for a 51k-vertex one (was 208 s).

Neither needs mesh.face_adjacency_tree, so rtree leaves the mesh extra
and the per-function dependency guard goes back to a trimesh check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* refactor(feature): rename ellipsoid_sphericity to sphericity

The formula is Wadell's sphericity for any body, nothing specific to
ellipsoids, and the name suggested otherwise. No caller outside mesh.py
used the old name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* fix(feature): reject unknown mesh feature names before meshing

An unknown name raised a bare KeyError only after every feature of the
first label had been computed, and an image without labels accepted it
silently. Names are now checked up front in extract_features and
extract_mesh_features, and the ValueError lists the available ones.

features=[] now yields an (n_labels, 0) matrix instead of silently
falling back to the full default set.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* feat(feature): return column names from mesh.extract_features

voxel.extract_features returns (labels, values, column_names) while the
mesh variant returned only (labels, values), so the two could not be
swapped and callers had to rebuild the names themselves. The mesh
variant now returns the same triple.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* feat(feature): expose cubic.feature.mesh, imported on first access

cubic.feature did not export the mesh module, so cubic.feature.mesh
raised AttributeError unless the submodule had been imported
explicitly. A module-level __getattr__ now imports it on first access,
the pattern cubic.scipy already uses, so the 0.75-3 s trimesh import
still stays off the import path of the voxel and texture features.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* docs: describe the mesh feature module in AGENTS.md

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* docs(feature): keep the equivalent-ellipsoid formula on one line

The inline literal was split across two docstring lines, which breaks
its rendering.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* refactor(feature): use trimesh's integral_mean_curvature

_avg_mean_curvature rebuilt Trimesh.integral_mean_curvature, a cached
trimesh property that gives the same value (equal to the last bit on a
voxelized ball). trimesh signed the dihedral angles only from 4.6.12 on;
4.6.11 returns 71.8 instead of 2 pi^2 R = 59.2 on a torus. The mesh
extra therefore now requires trimesh>=4.6.12. The mesh tests pass on
both 4.6.12 and the locked 4.11.2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* refactor(feature): test trimesh is None instead of a mirror flag

_TRIMESH_AVAILABLE restated whether the import had bound trimesh, and
was set in three places to stay in sync with it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* fix(feature): type the mesh feature registry for numpy float returns

trimesh annotates volume, area and mass as numpy float64, which the
numpy 2.0 stubs do not treat as float. With trimesh installed, mypy
rejected the registry's Callable[..., float] values and the sphericity
call. CI's lint job runs without trimesh, so it did not see this. The
registry now returns SupportsFloat, which extract_mesh_features already
converts, and sphericity receives plain floats.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* refactor(feature): resolve mesh feature names in one helper

extract_features and extract_mesh_features each repeated the same
default-then-validate block. _resolve_features now returns the
resolved list, so the default and the error message live in one place.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* docs(feature): keep regression history out of mesh docstrings

_equivalent_ellipsoid_axes described the bounding-box extents it
replaced, with the numbers of one example. That history is in the tests
and the commit log; the docstring now states only what the code does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* test(feature): share the meshing stub and grid helper in mesh tests

Three tests each defined the same extract_surface_features stub, so
adding the features parameter meant three identical edits. A
surface_calls fixture now records each call's mask and spacing. The
ball, ellipsoid and torus builders share _centred_grid instead of three
spellings of a centred meshgrid, one of them with a hardcoded centre.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* test(feature): keep the trimesh import out of the lazy-export test

The subprocess imported trimesh only to check the last assertion,
3.9 s of the file's 7.6 s. It now checks only that importing
cubic.feature skips trimesh. The in-process call to the package
__getattr__ covers the access path. The test takes 0.11 s.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* fix(feature): keep mesh out of cubic.feature.__all__

With "mesh" in __all__, `from cubic.feature import *` resolved it
through __getattr__ and loaded trimesh, undoing the lazy import, and
warned on hosts without trimesh. Attribute access still loads it on
demand.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* ci: install the plot extra so the plot tests run

tests/test_plot_utils.py skipped at import in CI for want of
matplotlib, the same gap the mesh extra had. The plot extra is as light,
so the test job installs it too. cellpose stays out because it pulls in
torch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* docs(feature): state how far mesh features still vary with orientation

mesh_feature_list and AGENTS.md called every feature orientation-
invariant. None is defined on the image axes any more, but voxelization
moves all of them a little, and trimesh's oriented box and bounding
cylinder come from approximate minimum searches: Extent spans 0.50-0.55
for one ellipsoid at 0, 30 and 45 degrees. The docs now say so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* fix(feature): keep the lazy __getattr__ from hiding typos from mypy

mypy types every unknown attribute of a module that defines __getattr__
with that function's return type, so cubic.feature.regionprop type-
checked as a module and failed only at run time. __getattr__ is now
defined only outside type checking, and mypy learns about mesh from a
TYPE_CHECKING import. The typo is now reported ("Module has no
attribute 'regionprop'; maybe 'regionprops'?").

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* test(feature): time out the fresh-interpreter import check

The subprocess had no timeout, so an import that hangs in the child,
such as CUDA probing on a node with a broken driver, would stall the
whole pytest run without output.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* fix(feature): reject a bare string as the mesh feature list

extract_features(img, "Volume") iterated the string and reported
Unknown mesh features ['V', 'o', 'l', 'u', 'm', 'e']. A string now
raises a TypeError that names it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* feat(feature): replace Avg Gaussian Curvature with the Euler characteristic

As a surface average, the Gaussian curvature is exactly
2 pi * euler_number / area by Gauss-Bonnet, so the column was 4 pi /
Area for every label without holes and carried nothing beyond Area and
one integer. That integer is now its own column: twice the separate
pieces plus cavities, minus twice the handles (2 for a ball, 4 for a
hollow ball or two balls, 0 for a torus). It is free to compute and
does not depend on the spacing unit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* test(feature): pin the cavity sign in the mean curvature

A hollow ball's shells must keep their orientation relative to the
material: the cavity faces inward and counts as concave, so the hollow
ball integrates to the outer ball minus the inner one (82.1), not their
sum (244.2). mask2mesh already does this, because fix_normals runs
without multibody, but nothing tested it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* fix(feature): check mesh feature names before meshing or validating

extract_surface_features built the mesh before the names reached a
check, and extract_mesh_features validated the mesh geometry first. An
unknown name with an open mesh therefore surfaced as "Mesh volume must
be finite and positive" instead of the unknown-feature error, and a
valid mask was meshed for nothing. Both entry points now resolve the
names first, as extract_features already did.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* perf(feature): skip meshing when no mesh features are requested

extract_features(img, []) still meshed and validated every label just
to return an (n_labels, 0) matrix, and could raise a geometry error
instead. It now returns that matrix straight away.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* feat(feature): curvature-distribution mesh features on a smoothed mesh

Adds Total Absolute Gaussian Curvature, Avg Shape Index and Avg
Curvedness, the ShapeTools shape measures, chosen by how well they
separate shape states rather than by parity:

- Any average of Gaussian curvature is fixed by Gauss-Bonnet, so the
  shape signal is in where K is negative. The integral of |K| over 4 pi
  is 1 for every convex body and grows with saddle regions (grooves,
  waists, the necks of lobes); unitless.
- Shape index (Koenderink) and curvedness come from per-vertex principal
  curvatures computed as in LONI ShapeTools (Meyer et al. angle defect
  and edge-based mean curvature over the mixed Voronoi area), averaged
  over the surface by area rather than by vertex, so the result does
  not depend on how the mesher distributes vertices.

Per-vertex curvature on a voxel staircase measures the staircase, so
these are computed on a mesh of the mask blurred at curvature_sigma
(default twice the coarsest spacing, isotropic in physical units), a new
option of extract_features, extract_surface_features and mask2mesh
(sigma). Nothing is blurred unless one of them is requested, and an
object too small to survive the blur gets NaN for them with a warning.

On synthetic nuclei with random size, axes, rotation, sub-voxel position
and boundary noise (3 seeds x 2 noise levels, 30 per class), total |K|
separated folded from smooth ellipsoids with AUC 1.00 and lobulated with
0.82 at rotation CV 0.000, against 0.53-0.64 for every average of K
(including the 2021 ball measure and the ShapeTools vertex mean), and
shape index and curvedness added 0.02-0.06 cross-validated AUC on top of
Solidity, Sphericity and mean curvature. On analytic shapes: ball total
|K| 1.000, torus 2.04 (exact 2), unit change rescales curvedness by 10
and leaves the rest unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* feat(feature): fractal dimension of the smoothed mesh under decimation

Completes the ShapeTools shape list with the LONI GSA fractal dimension,
whose module sampled the mesh at triangle counts between a minimum and a
maximum: the smoothed mesh is simplified by quadric error metrics to six
face counts from a sixteenth of its own up to all of it, and
D = 2 + 2 * slope of log area against log face count (about 2 for a
smooth surface; 2.005 on a voxelized ball).

On the synthetic nuclei it is weak on its own (AUC 0.59-0.66) and adds
signal only in some settings (+0.05 cross-validated AUC for folded
nuclei at high boundary noise, -0.03 for lobulated at low noise); box
counting on the mask boundary added nothing and was not kept.

Decimation needs fast-simplification, now in the mesh extra (>=0.1.9:
0.1.7 does not import under NumPy 2). Without it the feature raises a
RuntimeError naming the package.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* refactor: share the SciPy-rounding Gaussian filter in image_utils

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

* feat(feature): CUDA port of skimage's Lewiner marching cubes

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

* feat(feature): ArrayMesh, a trimesh-compatible mesh on CPU or GPU arrays

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

* feat(feature): mesh features on the GPU for CuPy input

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

* docs: describe the GPU mesh path in AGENTS.md

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* feat(feature): fractal dimension from multi-scale area, on CPU or GPU

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

* fix(feature): warn when fractal dimension is NaN for a sheet thinner 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

* fix(feature): merge equal and unreferenced vertices in ArrayMesh like 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

* fix(feature): ArrayMesh raises for delegated methods that change the 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

* fix(feature): run CUDA marching cubes on the input volume's device

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

* fix: keep the imaginary part in gaussian_filter_like_scipy on the GPU

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

* refactor(feature): call np. in ArrayMesh adjacency, not get_array_module

_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

* refactor(feature): return ArrayMesh adjacency edges, not stash them

_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

* refactor(feature): share one lexsort row-grouping helper for meshes

_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

* refactor(feature): drop empty-volume guards in CUDA marching cubes

_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

* refactor: share the CUDA compile and launch helpers in cubic.cuda

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

* refactor(feature): mesh mask2mesh through the _marching_cubes seam

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

* perf(feature): blur the mask at curvature_sigma once per object

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

* perf(feature): crop the fractal-dimension twin to the mask's frame

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(feature): share the GPU mesh comparison and use default features

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

* fix(feature): round the GPU default level like skimage's

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

* fix(feature): reject a spacing of other than three values on the GPU

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

* fix(feature): keep ArrayMesh's own attribute errors from reaching trimesh

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

* feat(feature): warn when Fractal Dimension spans under a factor of 2

_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

* fix(feature): import skimage's private marching-cubes tables guardedly

_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

* refactor(feature): upload the marching-cubes tables with cubic.cuda.ascupy

_kernels copied the lookup tables to the device with cp.asarray inside
`with cp.cuda.Device(device_id)`. ascupy is cp.asarray, so the tables
still land on the device entered there, now through the cubic.cuda
helper that AGENTS.md asks for.

The isinstance(volume, cp.ndarray) device choice in marching_cubes
stays: get_device also returns "GPU" for a CUDA torch tensor, whose
.device is a torch.device rather than a CuPy device to enter.

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

* refactor(feature): import trimesh at the top of _array_mesh.py

ArrayMesh.to_trimesh imported trimesh inside the method, so a missing
trimesh surfaced as a bare ModuleNotFoundError on first delegation.
The module now imports it at the top under the same guard as mesh.py,
without a second warning, and to_trimesh raises mesh.py's
RuntimeError ("trimesh is required for mesh operations. Install with
'cubic[mesh]'") when it is missing.

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

* docs(feature): describe mesh feature sources and GPU degenerate faces

- mesh_feature_list said its features are extracted from a trimesh
  object; Fractal Dimension is measured on the mask. It now describes
  the surface features of a label that extract_features and
  extract_surface_features return.
- The CUDA marching_cubes and its module said the mesh matches
  skimage's up to vertex and face order. With allow_degenerate=False
  it merges every coincident vertex, where skimage merges only those of
  degenerate faces, and keeps vertices used only by the dropped faces,
  which ArrayMesh drops. Both docstrings now say so; behaviour is
  unchanged.
- test_mask2mesh_on_gpu said only spacing is accepted on the GPU;
  level and allow_degenerate are too since mask2mesh goes through
  _marching_cubes.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5

* fix(feature): do not warn about a short Fractal Dimension scale range

e1d3e69 warned when curvature_sigma was under twice the finest voxel
spacing, on the argument that a fit over a short log range is
ill-conditioned. The measurement made for that commit does not show it:
over 12 smooth ellipsoids (semi-axes 7-17 voxels, isotropic spacing) the
SD of Fractal Dimension is 0.0007 at ratios 1.05, 1.1, 1.25 and 1.5,
against 0.0012 at 2 and 0.0061 at 3. The area ratio to the smooth twin
carries too little jitter for the short range to amplify, so the warning
would flag a valid setting without evidence of a problem. The NaN and
warning for a curvature_sigma at or below the finest spacing stay, and
the curvature_sigma docstring keeps that rule.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5

* feat(feature): set the Fractal Dimension scale window with fractal_scales

extract_features and extract_surface_features take fractal_scales, the
(lowest, highest) blur scale of the fit in units of spacing. The smooth
twin is the mask blurred at the highest scale, and the fit keeps 5
geometric levels. In a sweep over three nucleus datasets, the 3D
estimate was unbiased only while the top scale stayed below half the
object's smallest half-extent, and the useful window started a few
voxels above the resolved edge rather than at one voxel, so the window
needs to be set apart from curvature_sigma.

None keeps the window from the finest voxel spacing to curvature_sigma
and reuses the curvature blur. On 8 test masks (ellipsoids, rough
ellipsoids, slabs, hollow balls; isotropic and (0.29, 0.108, 0.108)
spacing) every default feature is bitwise unchanged on the CPU and on the
GPU, apart from the three curvature-distribution features, which vary by
up to 1.1e-8 between GPU runs of the unchanged code on a flat slab. A
window that is not two finite numbers with 0 < lowest < highest raises
ValueError before any meshing.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5

* feat(feature): warn for objects too thin for Fractal Dimension's scales

In a sweep over three nucleus datasets, the 3D fractal dimension was
unbiased on smooth shapes only while the top blur scale stayed at most
half the object's smallest half-extent; above that it reads low, which
makes it unreliable for flat nuclei. extract_surface_features now warns
when the top scale (curvature_sigma, or the highest of fractal_scales)
exceeds a quarter of Min Axis Length, the shortest axis of the
same-inertia ellipsoid of the raw mesh, and still returns the value.

The text is the same for every object, so Python's default filter shows
it once for a label image of many thin objects: three slabs of different
size (Min Axis Length 1.93, 2.31, 2.32 um at a 0.6 um top scale) give
one warning. The axes are computed only when Fractal Dimension is
requested and finite. Default features of the 8 baseline masks are
bitwise unchanged on the CPU, and on the GPU apart from the
run-to-run noise of the three curvature-distribution features.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5

* feat(feature): add Outline Fractal Dimension of the z-projection

Outline Fractal Dimension runs the Fractal Dimension construction on the
outline of the mask's projection along the first axis: 1 - slope of log
contour length of the blurred footprint, relative to its smooth twin,
against log blur scale. In a sweep over three nucleus datasets, this
form was unbiased at any top scale, reproduced across segmenters as well
as volume, and separated cell states better than the 3D estimate, which
reads low for flat nuclei. Its default window is 4 to 16 times the
coarser in-plane spacing; fractal_scales sets it as for the 3D feature.

The contour length comes from the existing marching cubes, so the
feature runs on the mask's device: the blurred footprint stacked twice
one unit apart meshes to a ribbon whose area is the contour length. On
5 shapes, 3 spacings and 3 blur scales the ribbon matched skimage's
find_contours to 6.2e-8 relative, and an analytic disc to its 2 pi R up
to the polygon's own deficit. On CuPy input it matches the CPU to 1e-9.

Smooth elliptical footprints measure 0.992-0.999, and 4% and 8% outline
noise raise a 0.997 disc to 1.008 and 1.054. A quarter turn about the
first axis changes it by 1e-8, a 45 degree turn by 1.8e-4. It is the one
feature defined on the image axes, which mesh_feature_list now says.
The thin-object warning of Fractal Dimension points to it.

On 20 cpdino-v2 nuclei from each of mboc2021_astr_vpa,
scirep2018_fibroblast and scirep2018_pc3, fractal_scales=(0.4, 1.6)
reproduces the sweep's find_contours values to at most 1.06e-8.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5

* feat(feature): compute Outline Fractal Dimension only on request

At its default 4-to-16-voxel window the outline feature is NaN, with a
warning, for every footprint under about 51 voxels across: a smooth disc
of radius 25 voxels gives NaN, one of 25.5 voxels -0.15, and the value
reaches 0.95 at a radius of 32 voxels and 0.99 at 40. Computed by
default, it would warn for every small object, and it would put a
feature defined on the image axes into a default set that is otherwise
orientation-invariant.

mesh_feature_list() again returns the 22 default names of 7a5ebb5,
ending in Fractal Dimension; mesh_feature_list(optional=True) appends
Outline Fractal Dimension. features=None computes the defaults, an
explicit list may name either kind, and the unknown-name error lists
both. On the 8 baseline masks, extract_surface_features at default
arguments returns exactly the 7a5ebb5 keys and values (bitwise on the
CPU; on the GPU within 1.1e-8 for the three curvature-distribution
features, their run-to-run spread on a flat slab), and extract_features
returns 22 columns.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5

* feat(feature): set the outline window with outline_fractal_scales

fractal_scales set the window of both fractal features, but their
windows differ in kind: on a flat object a window that suits the outline
(say 0.8-1.6 um) puts the 3D estimate above a quarter of the object's
thickness, where it reads low and warns. fractal_scales now applies to
Fractal Dimension only, and a new keyword, outline_fractal_scales, on
extract_features and extract_surface_features, sets the window of
Outline Fractal Dimension, with the same form and validation; each
error names its keyword. The outline default stays 4 to 16 times the
coarser in-plane spacing.

Changing either window leaves the other feature bitwise unchanged
(tested on a rough cylinder). Default features of the 8 baseline masks
are unchanged: bitwise on the CPU, and on the GPU within the run-to-run
spread of the three curvature-distribution features.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5

* refactor(feature): compute both fractal features with one estimator

_fractal_dimension and _outline_fractal_dimension repeated one estimator:
the smooth twin, the geometric ladder of blur scales, the reuse of the
top scale, the ratio list, the vanishing warning and the fit. Both now
call _blur_ladder_dimension, which takes the N-dimensional mask, its
step, the window, a measure of the 0.5 level (surface area, or contour
length of the stacked ribbon) and the already computed top blur and top
measure, and returns mask.ndim - 1 - slope.

extract_surface_features resolves each feature's (lowest, highest) once,
instead of in three branches for the 3D window and inside the outline
estimator, and reuses the blur and level set at curvature_sigma whenever
the 3D top scale equals it, also for an explicit window. The thin-object
ratio is one constant, used by the condition and the warning text.

Default features of the 8 baseline masks are bitwise unchanged on the
CPU, and on the GPU within the run-to-run spread of the three
curvature-distribution features; Outline Fractal Dimension and Fractal
Dimension over custom windows are bitwise unchanged on 7 flat masks at
three spacings.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5

* perf(feature): pad the outline's 2D blurs by one pixel

_padded_blur pads by ceil(3 sigma) + 1 voxels and blurs in reflect
mode, so at the outline's default 16-pixel top scale a 151 x 151
footprint became 249 x 249 for each of its 10 blurs. With tight=True it
pads by one pixel and blurs with zeros beyond it (constant mode). On the
mask's frame and that ring the field is bitwise the same as the wide
blur's (checked on CPU and GPU for a rough disc, a box and a disc that
touch their crop on all four sides, and noise blobs, on (0.108, 0.108),
(0.2, 0.1) and (1, 1) planes at every ladder scale), and the ring stays
below 0.5 (at most 0.4814), so every contour closes inside the array.
Only Outline Fractal Dimension uses it; the 3D blurs keep their padding.

The outline estimator takes 20.9 ms instead of 34.6 ms on that
footprint (median of 7, CPU). Values move by at most 1.7e-8 relative on
7 flat masks, because the float32 contour vertices sit at a different
offset in the array; CPU and GPU agree to 3.7e-16 relative. On 20
cpdino-v2 nuclei per dataset the outline matches the fd_sweep
find_contours values to at most 5.2e-9 (mboc2021_astr_vpa), 9.8e-9
(scirep2018_fibroblast) and 1.1e-8 (scirep2018_pc3). Default features of
the 8 baseline masks are unchanged.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5

* refactor(feature): derive the default mesh features and simplify windows

mesh_feature_list now derives the default names from _MASK_FEATURES and
_OPTIONAL_FEATURES instead of a third tuple, and _fractal_window checks
0 < lowest < highest < inf in one comparison, which is also false for
NaN and either infinity (the validation test covers NaN in both places,
+inf, -inf, reversed, equal and zero windows).

Each default window is stated once, in the keyword that sets it, and
mesh_feature_list and curvature_sigma point to it; mesh_feature_list
says once that the fractal features are measured on the mask, and its
reflowed paragraph on the axis lengths is joined again. Default features
of the 8 baseline masks are unchanged.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5

* test(feature): pin the default feature count once and fold repeated cases

The default count of 22 is now pinned only in the test of the optional
list; the background-label and default-output tests use
len(mesh_feature_list()). The thin-object test checks that its one
warning points to Outline Fractal Dimension, which replaces a separate
test that repeated its slab call to match the text. The rotation test
measures the upright ellipsoid once, outside the loop, and the
default-output test is the one place that checks the outline stays out
of the defaults.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5

* fix(feature): attribute mesh feature warnings to the calling line

extract_features and extract_surface_features are wrapped by
_require_trimesh, which adds a frame, so with stacklevel=2 every warning
raised under them was attributed to that wrapper in cubic/feature/mesh.py
instead of to the code that called the public function. The thin-object
warning, both "vanishes" warnings, the warning for curvature_sigma not
above the finest spacing and the blur-ladder warning now use one
stacklevel constant, plus the frames of the helpers that raise them, so
a direct call to extract_surface_features attributes each to the
caller's line. Against the previous code, the new test fails for all
five warnings and passes with this change.

Through extract_features the caller is its per-label loop, one line
for every label, so the constant thin-object text is still shown once
per label image under the default filter; the docstring says why.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5

* refactor(feature): memoize the mask's blur per scale in surface features

extract_surface_features bound the blur, padding and level set at
curvature_sigma inside one branch and read them later under another
(Fractal Dimension's top scale equal to curvature_sigma), correct only
through an invariant held elsewhere in the function. A per-call memo of
the mask's blur, padding and level set at a scale, each computed at
most once, now serves the curvature features at curvature_sigma and
Fractal Dimension's top scale, so the reuse when the two are equal
follows from the memo.

An empty default window (curvature_sigma not above the finest spacing)
is now decided before any blur: it returns NaN with its own warning,
without blurring, and is no longer listed as vanishing when the mask
vanishes at curvature_sigma. The default output and warning texts of
the 8 baseline masks are unchanged, as is the bitwise equality of the
explicit (finest spacing, curvature_sigma) window with the default.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5

* fix(feature): raise TypeError for a fractal window that is not numbers

_fractal_window accepted b"12" as the window (49.0, 50.0) and a dict
through its keys, and raised ValueError for a scalar or a string, where
_resolve_features raises TypeError for a string. It now raises
TypeError, naming the keyword, unless the window is a sequence or 1D
array of real numbers (so for a scalar, str, bytes, a mapping or
non-numeric elements), and ValueError when the sequence has other than
two values or they are not finite with 0 < lowest < highest. Default
features of the 8 baseline masks are unchanged.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5

* perf(feature): pad the 3D fractal ladder's blurs by one voxel

The 3D ladder's nine extra blurs and marching-cubes runs per label (4
mask scales, 5 twin scales) padded by ceil(3 sigma / step) + 1 voxels a
side, about 1.9 times the voxels of a 40 x 100 x 100 crop at nucleus
spacing. _blur_ladder_dimension now uses the one-voxel tight padding
for every ladder blur, of both fractal features, so its tight flag is
gone; the top-scale blur, shared with the curvature mesh, keeps the
wide padding.

In 3D the field on the mask's frame and the one-voxel ring is bitwise
the same as the wide blur's, and the ring stays below 0.5 (at most
0.4307), on CPU and GPU, at every ladder scale of the mask and its twin,
for a rough ellipsoid, a box filling its crop, a slab filling the first
axis and a hollow ball, at (0.29, 0.108, 0.108), (0.3, 0.13, 0.13) and
isotropic spacing. Only the float32 vertex offsets change: Fractal
Dimension of the 8 baseline masks moves by at most 1.8e-8 on CPU and
GPU, every other feature is unchanged, and CPU and GPU agree to 2.3e-16
relative. Fractal Dimension of the 8 masks takes 853 ms instead of
1058 ms on the CPU (min of 5 per mask); on the shared GPU 841 and 356 ms
instead of 986 and 567 ms in two runs.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5

* test(feature): drop timings that no longer describe the mesh code

The 15.4 s mean-curvature timing belongs to the vertex-ball measure
that this branch replaced. The trimesh import time stays stated once,
in cubic/feature/__init__.py.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* test(feature): drop the unreachable default from the meshing stub

extract_features resolves the feature names and returns early for an
empty list before it calls extract_surface_features, so the stub never
receives None or an empty list.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* ci: install the mesh extra in the lint job so mypy sees trimesh's types

Without trimesh installed, mypy treats every trimesh type in
cubic/feature/mesh.py as Any, so the lint job could not report an error
against trimesh's own annotations. For example, passing
trimesh.__version__ (typed str | None) where a str is expected is
reported only with trimesh installed.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* fix(feature): refuse a trimesh older than 4.6.12 when mesh is imported

Trimesh.integral_mean_curvature exists in older releases too, with
unsigned dihedral angles. An environment that got trimesh from
somewhere other than the mesh extra therefore returned an overstated
Avg Mean Curvature on any concave surface, without an error.

The floor from pyproject.toml is now checked when cubic.feature.mesh is
imported, and an older release raises ImportError. A version part that
is not a plain number, such as a pre-release tag, is not compared.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* fix(feature): accept a one-shot iterable as the mesh feature list

The names were iterated once to find unknown ones and a second time to
build the list, so a generator, map or filter came back empty:
extract_features returned an (n, 0) matrix and no column names, without
an error.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* fix(feature): orient CPU meshes by the sign of their volume

trimesh.repair.fix_normals inverts a mesh only when trimesh calls it
watertight, and a mesh with an edge shared by four faces is not. Ragged
masks give such edges, so their marching-cubes mesh kept skimage's
inward winding, extract_mesh_features rejected its negative volume, and
extract_features failed for the whole label image. The GPU path already
flipped ArrayMesh by the sign of its volume and measured the same label.

The NumPy path now reverses the faces before building the Trimesh when
their signed volume is negative. Output is bitwise unchanged on meshes
that worked before, gradient_direction="ascent" stays outward, a
cavity's shell still faces the material, and trimesh keeps the mass
properties it caches instead of computing them again after invert().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* fix(feature): measure mesh features in units of the finest spacing

trimesh compares lengths with absolute tolerances of about 1e-8, so the
features depended on the unit of spacing. With a 100 nm voxel given in
metres, Avg Mean Curvature was 28 to 94 times off at spacing 3e-7 and
the call raised at 1e-7; Avg Shape Index and Avg Curvedness already
drifted by 1e-5 at spacing 1e-2.

extract_surface_features now divides the spacing, curvature_sigma and
both fractal windows by the finest spacing, measures, and multiplies
each feature by that unit to the power of its length dimension
(_FEATURE_DIMENSIONS). The computation sees only the ratios of the
spacings, so a feature converts with the unit to the rounding of one
multiplication, from 1e-9 to 1e3. Warnings and errors still print
lengths in the caller's units.

A spacing that is not finite and positive now raises ValueError. It
used to fail inside the blur, or, when all negative, to return the
features of the mirrored object.

Values at ordinary spacings move a little, because the approximate
searches and the tolerance tests now run at another scale: on nine test
masks at spacing (0.29, 0.108, 0.108) and 0.108, Bounding Cylinder
Volume by up to 6e-3, Total Absolute Gaussian Curvature by up to 4e-4,
Avg Shape Index and Avg Curvedness by up to 1.2e-4, and every other
feature by less than 1e-6. With no spacing or (1, 1, 1) the output is
bitwise unchanged.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* fix(feature): orient marching-cubes faces by their known winding

3b7c6e8 flipped CPU meshes by the sign of their volume. That needs a
pass over every face, its sign depends on the origin for an open surface
(a half-masked ball measured -1766.75, -4386.75 and +853.25 at three
shifts, reachable through marching_cubes_kwargs={"mask": ...}), and the
rule lived in _closed_mesh while ArrayMesh kept its own copy.

skimage winds every face inward for the default
gradient_direction="descent" and outward for "ascent", and the CUDA port
reverses its triangles as skimage does for "descent". _marching_cubes,
which both devices go through, now reverses the faces unless skimage was
asked for "ascent", so _closed_mesh is a plain wrapper again. ArrayMesh
keeps its flip for inward faces built directly from marching-cubes
output; given outward faces it no longer flips, so it computes its
integrals once per mesh instead of twice.

Output is bitwise unchanged on CPU against the code before 3b7c6e8 and
within 5e-15 on GPU. A new test checks that _marching_cubes' faces
enclose a positive volume on both devices.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

* fix(feature): name both causes of a non-positive mesh volume

The volume guard in extract_mesh_features said the mesh was "likely not
watertight". Now that marching-cubes faces are oriented by their known
winding, that diagnosis is wrong both ways: a watertight but inverted
icosphere raises with it, and an open hemisphere with a positive signed
volume passes. …
alxndrkalinin added a commit that referenced this pull request Nov 25, 2026
main holds #61-#63, #66 and #68 squashed. This branch carried an older
feat/mesh-gpu, so every file outside its own four takes main's version,
and its own changes to AGENTS.md, cubic/segmentation/__init__.py,
aics_workflows.py and their tests are applied on top. In
aics_workflows.py, main moved _cuda_functions and _launch_config to
cubic.cuda; the import keeps main's list and adds to_same_device, which
this branch uses.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
@alxndrkalinin
alxndrkalinin deleted the feat/mesh-gpu branch November 25, 2026 06:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants