Repository navigation
feat(feature): ShapeTools shape measures on a smoothed mesh (total |K|, shape index, curvedness, fractal dimension) - #62
Conversation
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
Reviewer's GuideAPIExpose curvature smoothing through per-label extraction and document its physical-scale behavior.
Expose smoothing and optional smoothed-mesh input through the surface and mesh APIs, documenting their behavior.
ImplementationDefine the new shape measures and their smoothed-mesh interpretation in the mesh feature documentation and registry.
Build and select a blurred mesh only for requested shape measures, preserving other features and returning NaNs when the mask vanishes.
Add physical-unit blur validation and Gaussian-smoothed mask meshing, including explicit handling of ignored marching-cubes options.
Implement mixed-area principal-curvature estimates, area-weighted shape statistics, and QEM fractal dimension.
ConfigurationAdd the optional fast-simplification dependency required to calculate fractal dimension.
TestsAdd and update mesh tests for smoothed shape measures, scale and orientation behavior, fractal dimension, invalid inputs, and vanished masks.
Lock files and vendored codeUpdate the dependency lockfile to record the optional mesh dependency change.
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
There was a problem hiding this comment.
🟡 Changes recommended
Closed meshes with fewer than 64 faces generate invalid decimation targets, which can cause fractal-dimension extraction to fail even with the default feature set.
1 open issue
What changed in this PR
Adds ShapeTools-inspired measures to cubic’s mesh feature extraction, building on #61 while preserving raw-mesh measurements for existing features.
Changes:
- Adds total absolute Gaussian curvature, area-weighted shape index and curvedness, and fractal dimension.
- Introduces configurable, physical-scale smoothing with warnings and NaN results for objects that vanish under blur.
- Adds the simplification dependency and tests for the new measurements and smoothing behavior.
| File | Description |
|---|---|
uv.lock |
Locks fast-simplification and includes it in the mesh and all extras. |
tests/feature/test_mesh.py |
Tests new measures, scaling, rotation, smoothing, and dependency handling. |
pyproject.toml |
Adds fast-simplification to the mesh extra. |
cubic/feature/mesh.py |
Implements the new measures and smoothed-mesh APIs. |
Review effort: Balanced
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
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
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
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
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
Brings in the five commits added to #61 before it merged (4ae2e33 to b2e0de2): the trimesh version floor at import, the one-shot iterable fix, the lint job's mesh extra and two test cleanups. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
main's tree at 99b9e67 equals fix/mesh-features at b2e0de2, which the previous commit merged, so this merge uses the "ours" strategy and changes no file. It makes the squash commit an ancestor of this branch, so that the pull request compares against main without repeating #61. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
_mixed_area encoded the cyclic order of a triangle's corners twice: as modular indices in a list comprehension, and as the two index lists used two lines below. One fancy-indexed expression with those lists gives the same array bit for bit. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
test_curvature_distribution_converts_with_the_spacing_unit repeated the ball and the two spacings of test_curvature_converts_with_the_spacing_unit, which now carries its assertions. The torus mask was written out in two tests and is one helper. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
Every test of the smoothed features used an isotropic spacing, so none could tell twice the coarsest spacing from twice the finest or the mean. The new test fails when _curvature_sigma takes min(spacing). Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
With sigma, mask2mesh blurs the mask and meshes it without marching_cubes_kwargs. A spacing passed there was dropped without an error, which left the mesh in voxel units while the same call without sigma honoured it. The combination now raises ValueError. A sigma that is not finite and positive was reported as "curvature_sigma", a parameter this function does not have. The error now names sigma. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
The lowest decimation target is 64 faces. A smoothed mesh with fewer faces got targets above its own face count, and the decimation raised "target_count must be less than the number of faces". A ball of radius 3 voxels survives the default blur as a 44-face mesh, so one small object failed extract_features with the default features for the whole label image. Such a mesh now gets NaN, like one with fewer than three distinct levels. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
|
Changes since Copilot's review at a293b3d, each with the commit it was addressed in. Copilot has not reviewed them (it is not available at the moment, 2026-11-17). They were reviewed locally: a quality pass with four reviewers and a correctness pass on the whole PR. The one open Copilot thread is answered and resolved (fixed in 1b2422b). Came in with
From the local review of this PR
|
Brings in the five commits added to #62 during its review (20765ea to 1b2422b): the one-step opposite-edge lengths in _mixed_area, two test changes, mask2mesh refusing marching_cubes_kwargs together with sigma, and NaN for the decimation fractal dimension of a tiny mesh. Conflicts: - The decimation estimator and its tests do not exist on this branch, so the NaN guard for a mesh under 64 faces and its test are dropped. The estimator here returns NaN with a warning when a blur vanishes. - mask2mesh keeps both checks: this branch validates the spacing, and #62 refuses the keywords and names sigma in its error. - Both branches added a test after the curvature_sigma validation tests; both are kept. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
There was a problem hiding this comment.
Hey - I've found 8 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="cubic/feature/mesh.py" line_range="260-262" />
<code_context>
+ # Pad past the blur's reach so it neither clips at the crop nor touches the
+ # border, which would leave the surface open.
+ pad = np.ceil(3 * sigma_voxels).astype(int) + 1
+ volume = ndimage.gaussian_filter(
+ np.pad(mask_3d.astype(np.float32), [(p, p) for p in pad]), sigma_voxels
+ )
+ if volume.max() <= 0.5:
+ return None
</code_context>
<issue_to_address>
**Smoothed meshes reject GPU masks**
When a caller passes a CuPy mask to `extract_surface_features` requesting a smoothed feature or to `mask2mesh(..., sigma=...)`, `_smooth_mask2mesh` sends the mask through `np.pad` and `ndimage.gaussian_filter` without transferring a CuPy input to the CPU, so smoothed-mesh calls with GPU masks fail instead of supporting the input device.
Transfer the mask to CPU with the project’s `asnumpy` helper before running the NumPy/SciPy smoothing pipeline.
</issue_to_address>
### Comment 2
<location path="cubic/feature/mesh.py" line_range="259" />
<code_context>
+ sigma_voxels = sigma / step
+ # Pad past the blur's reach so it neither clips at the crop nor touches the
+ # border, which would leave the surface open.
+ pad = np.ceil(3 * sigma_voxels).astype(int) + 1
+ volume = ndimage.gaussian_filter(
+ np.pad(mask_3d.astype(np.float32), [(p, p) for p in pad]), sigma_voxels
</code_context>
<issue_to_address>
**Large blurs exhaust worker memory**
When `curvature_sigma` is very large relative to the voxel spacing and per-label crop, or a caller supplies extremely anisotropic spacing, `_smooth_mask2mesh` pads the mask by an amount proportional to the blur width on every axis before checking whether the mask survives. `np.pad` and `ndimage.gaussian_filter` can exhaust process memory and terminate the worker instead of returning the vanished-mask result.
Check whether the blur can preserve the mask before allocating the padded volume, and avoid constructing an oversized padded array.
</issue_to_address>
### Comment 3
<location path="cubic/feature/mesh.py" line_range="543" />
<code_context>
+ else mesh.simplify_quadric_decimation(face_count=int(n)).area
+ for n in counts
+ ]
+ return 2 + 2 * float(np.polyfit(np.log(counts), np.log(areas), 1)[0])
+
+
</code_context>
<issue_to_address>
**Fractal dimension stays near two**
When QEM decimation largely preserves the mesh area, `_fractal_dimension` fits area against face count, so the fitted slope stays near zero and the returned value stays near 2, giving callers no useful surface-complexity signal on ordinary nuclei.
Change `_fractal_dimension` to use a measure that captures surface complexity when QEM decimation preserves area.
</issue_to_address>
### Comment 4
<location path="cubic/feature/mesh.py" line_range="263" />
<code_context>
+ volume = ndimage.gaussian_filter(
+ np.pad(mask_3d.astype(np.float32), [(p, p) for p in pad]), sigma_voxels
+ )
+ if volume.max() <= 0.5:
+ return None
+ verts, faces, _, _ = marching_cubes(
</code_context>
<issue_to_address>
**Small components disappear silently**
When a label contains disconnected components of different sizes and the smaller component falls below the blur threshold, the global maximum check only detects when the entire blurred mask vanishes; if a label contains both large and small disconnected components, the large component keeps the check false while the small component disappears from the returned mesh, so the curvature features describe only part of the label.
Check survival per connected component and warn or return NaN when any component is lost, rather than returning measurements for only the surviving components.
</issue_to_address>
### Comment 5
<location path="cubic/feature/mesh.py" line_range="525" />
<code_context>
+ of fewer than 64 faces, the lowest target, is too small to decimate and
+ gets NaN.
+ """
+ if importlib.util.find_spec("fast_simplification") is None:
+ raise RuntimeError(
+ "Fractal Dimension needs fast-simplification. Install with 'cubic[mesh]'"
</code_context>
<issue_to_address>
**Tiny meshes abort extraction**
When `fast_simplification` is absent and the requested fractal-dimension mesh has fewer than 64 faces, `_fractal_dimension` checks for `fast_simplification` before applying the 64-face cutoff, so it raises `RuntimeError` instead of returning NaN and `extract_features` aborts extraction for the label.
Apply the fewer-than-64-faces cutoff before checking for `fast_simplification`.
</issue_to_address>
### Comment 6
<location path="tests/feature/test_mesh.py" line_range="499" />
<code_context>
from __future__ import annotations
import warnings
+import importlib.util
</code_context>
<issue_to_address>
**Fractal dimension stays constant**
When the estimator returns 2 for every mesh, `test_fractal_dimension_of_a_smooth_surface_is_two` checks only a ball and accepts any value within 0.02 of 2 at this assertion, so an estimator that always returns 2 passes while reporting no surface complexity.
Add an assertion that distinguishes a rough surface from a smooth one, rather than checking only the smooth-surface value.
</issue_to_address>
### Comment 7
<location path="tests/feature/test_mesh.py" line_range="573" />
<code_context>
+ mask, features=_CURVATURE_FEATURES + ["Volume"]
+ )
+
+ assert from_meshes == pytest.approx(from_mask)
+
+
</code_context>
<issue_to_address>
**Smooth-mesh regression goes undetected**
When `extract_mesh_features` ignores its `smooth_mesh` argument, `from_meshes` and `from_mask` both reach `extract_mesh_features`, so if it ignores `smooth_mesh`, both measure curvature on the raw mesh and this equality still passes without verifying that the smooth mesh was used.
Compare the curvature results against an independent extraction from the smoothed mesh, or assert they differ from the raw-mesh results.
</issue_to_address>
### Comment 8
<location path="tests/feature/test_mesh.py" line_range="445" />
<code_context>
+ assert features["Total Absolute Gaussian Curvature"] == pytest.approx(1, rel=1e-6)
+ # Per-vertex principal curvatures are noisy, which pulls the area-average
+ # below 1 (0.92 here).
+ assert features["Avg Shape Index"] > 0.85
+ # The blur shrinks a convex body by about sigma^2 / R, raising curvedness.
+ assert features["Avg Curvedness"] == pytest.approx(1 / 10, rel=0.15)
</code_context>
<issue_to_address>
**Shape index can be constant**
When the shape-index calculation returns 0.9 for every non-vanished mesh, `test_curvature_distribution_of_a_ball` accepts any shape index above 0.85 here, and the unit-scale and orientation assertions only require equal values. An implementation returning 0.9 for every non-vanished mesh passes while reporting no distinction between caps, saddles, and cups.
Assert a shape-index result for a saddle or cup that distinguishes it from the ball result.
Also at `tests/feature/test_mesh.py:363`, `tests/feature/test_mesh.py:486`.
</issue_to_address>Sourcery assessment
Approval pending. 8 findings to address first.
Blocking findings: cubic/feature/mesh.py:262, cubic/feature/mesh.py:259, cubic/feature/mesh.py:543, cubic/feature/mesh.py:263, cubic/feature/mesh.py:525, and 3 more

Based on
main: #61 is merged, and this branch includesmainfrom after that merge. #63 is stacked on this PR.The Fractal Dimension of this PR is superseded. On the real nuclei below, the decimation estimator added here returns 2.0001 ± 0.0001 for every nucleus (found later, see #63): decimating a blurred mesh barely changes its area. #63 replaces it with a multi-scale estimator on the mask and removes
fast-simplificationagain. The fractal-dimension numbers in this description are measurements of this PR's estimator, kept for the record; they are not evidence about surface roughness.Summary
Adds the LONI ShapeTools shape measures to
cubic.feature.mesh. Each one is formulated to separate cell states as well as possible, rather than to match ShapeTools exactly.fast-simplification, which is now in themeshextra (>=0.1.9; 0.1.7 doesn't import under NumPy 2).Per-vertex curvature on a voxel staircase measures the staircase. So these four are computed on a mesh of the mask blurred at
curvature_sigma, a new parameter ofextract_features/extract_surface_features(sigmaonmask2mesh).extract_featureswith the default features for the whole label image: a ball of radius 3 voxels is a 44-face mesh after the default blur.mask2mesh(..., sigma=...)meshes the blurred mask withoutmarching_cubes_kwargs, so the two can no longer be combined (commit 2b99c10). Before, aspacingpassed in those keywords was dropped without an error and the mesh came out in voxel units.Evidence (synthetic)
The synthetic nuclei are smooth ellipsoids, folded ones (a waist groove), lobulated ones and wrinkled ones. Each gets a random size, axis ratios, rotation, sub-voxel position and smooth boundary noise. Runs: 3 seeds × 2 noise levels, 30 nuclei per class.
On top of Solidity + Sphericity + mean curvature (5-fold CV logistic regression), shape index, curvedness and total |K| add 0.02–0.06 AUC in the cases not already at ceiling. Fractal dimension is mixed: +0.05 on folded nuclei at high noise, −0.03 on lobulated at low noise.
On analytic shapes:
Real data
The test data are nuclear masks only, from three published cell-state comparisons:
Voxel sizes come from the Zeiss metadata of each slide or tile series, because the tile names aren't reliable: NHA day 5 is labelled 80 nm in XY but is 87.86 nm. Three PROLIF slides ship no metadata. They are given 0.1318 × 0.1318 × 0.3152 µm, which all 14 slides with metadata state. Their median volumes, 388–503 µm³, bracket the 447 µm³ of slide 157, the one PROLIF slide with metadata.
Validation. Each slide holds a single class, so a classifier can learn the slide instead of the cell state. The folds therefore hold out whole groups:
AUC is computed within each test fold. Δ is the paired difference to the baseline on the same folds. The baseline is the 18 size/shape features from #61. Every cell reads logistic regression / gradient boosting.
The four features carry signal, but the baseline already has most of it. On their own they reach 0.59–0.64 AUC on fibroblasts and VPA, yet they add at most 0.03 to the baseline. The only gain that holds across folds is Fractal Dimension with logistic regression on VPA: 22 of 25 tile folds and 3 of 3 days. Read this with the note at the top: the column behind that gain spans about 2.0001 ± 0.0001, so whatever the classifier used is not surface roughness in the intended sense, and the estimator is replaced in feat(feature): mesh features on the GPU (CUDA marching cubes, ArrayMesh) #63.
PC3 shape stays near chance across slides with every feature set and blur (0.36–0.61 AUC). Nucleus-level cross-validation reports 0.74 → 0.83 there, and that comes from slide identity. For example, EMT slide 179 alone has a median total |K| of 1.27, against 1.44–1.59 on the other five slides.
The 2021 ball measure of Gaussian curvature adds nothing consistent either. On PC3 its direction flips between slide pairs: its AUC is 0.06 on 171 vs 168 and 0.95 on 172 vs 179.
Blur. For Δ with all four features, 1× the coarsest spacing does better than the 2× default on VPA:
With fold sd of Δ up to 0.03 and only 3 day folds, the default stays at 2×.
Against LONI Mask2Mesh. Mask2Mesh is the iterative Laplace–Beltrami surface reconstruction in the 2018 pipeline, run with the 2018 parameters. The comparison uses 15 nuclei per class per dataset. Masks were downsampled 3× in x and y so that Mask2Mesh finishes, and both methods mesh the same downsampled mask. The table gives the Spearman ρ of each feature against Mask2Mesh, per dataset (PC3 / VPA / fibroblast):
Known limits, not changed here
extract_mesh_features(mesh)withoutsmooth_meshmeasures the three curvature features on the mesh it is given. On a raw voxel mesh that is the staircase: a ball of radius 10 on a 25³ grid reads total |K| 17.0, shape index 0.10 and curvedness 0.53, against 1.0, 0.91 and 0.11 with the smoothed mesh (7.0, 0.15 and 0.43 against 1.0, 0.92 and 0.11 on a 26³ grid). The docstring says so; nothing warns.Avg Shape Indexaverages over all vertices, including nearly flat ones, where the shape index is not defined.Test plan
tests/feature/test_mesh.pyat the first push: 38 passed with the locked versions, 38 with the floor versions (trimesh 4.6.12, fast-simplification 0.1.9), and 36 passed + 2 skipped without fast-simplificationtests/feature/test_mesh.py47 passed; full suite 785 passed, 166 skippedruff check .,ruff format --check .,mypy --ignore-missing-imports cubic/🤖 Generated with Claude Code
https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
Summary by Sourcery
Add smoothed-mesh shape measures to surface feature extraction for curvature, local shape, and fractal-complexity analysis.
New Features:
Bug Fixes:
Enhancements:
Build:
Documentation:
Tests: