Skip to content

feat(feature): ShapeTools shape measures on a smoothed mesh (total |K|, shape index, curvedness, fractal dimension) - #62

Merged
alxndrkalinin merged 41 commits into
mainfrom
feat/mesh-curvature-features
Nov 20, 2026
Merged

alxndrkalinin merged 41 commits into
mainfrom
feat/mesh-curvature-features

Conversation

@alxndrkalinin

@alxndrkalinin alxndrkalinin commented Oct 30, 2026 •

Copy link
Copy Markdown
Owner

Based on main: #61 is merged, and this branch includes main from 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-simplification again. 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.

  • Total Absolute Gaussian Curvature: ∫|K| dA / 4π, unitless. It is 1 for every convex body and grows with every saddle region (grooves, waists, the necks of lobes). An average of Gaussian curvature can't carry shape: Gauss–Bonnet fixes it at 2πχ/A. That holds for the area-weighted mean, the ShapeTools vertex mean and the 2021 ball measure alike, so the shape information is in where K is negative.
  • Avg Shape Index (Koenderink: −1 cup, 0 saddle, 1 cap) and Avg Curvedness √((k1² + k2²)/2). Both come from per-vertex principal curvatures computed as in ShapeTools: the Meyer et al. angle defect, and the edge-based mean curvature over the mixed Voronoi area. Both are averaged by area, not by vertex, so they don't depend on how the mesher places vertices.
  • Fractal Dimension: 2 + 2 × the slope of log area against log face count, under QEM decimation from 1/16 of the faces up to all of them (the LONI GSA module's parameterization). It needs fast-simplification, which is now in the mesh extra (>=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 of extract_features / extract_surface_features (sigma on mask2mesh).

  • It defaults to 2 × the coarsest voxel spacing, applied isotropically in physical units.
  • Nothing is blurred unless one of the four features is requested.
  • An object too small to survive the blur gets NaN for those four, with a warning; its other features are still computed.
  • A mesh that survives the blur with fewer than 64 faces gets NaN for Fractal Dimension (commit 1b2422b). Before, the decimation raised and one small object failed extract_features with 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 without marching_cubes_kwargs, so the two can no longer be combined (commit 2b99c10). Before, a spacing passed 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.

feature AUC folded AUC lobulated AUC wrinkled rotation CV
any average of K (area, ShapeTools vertex mean, 2021 ball) 0.53–0.64 0.53–0.57 0.54–0.63 ≤ 0.004
total |K|/4π, σ = 2 1.00 0.82 0.77 0.000
shape index, area-weighted 0.97 0.76 0.76 0.003
curvedness × R_eq, area-weighted 1.00 0.76 0.74 0.001
fractal dimension (QEM) 0.65 0.61 0.66 0.000

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:

  • Ball: total |K| = 1.000, shape index 0.92 (per-vertex principal curvatures are noisy), curvedness 1.08/R (the blur shrinks a convex body by about σ²/R), fractal dimension 2.005.
  • Torus: total |K| = 2.04 (exact value 2).
  • Unit change: curvedness scales by exactly 10; the other three don't change.

Real data

The test data are nuclear masks only, from three published cell-state comparisons:

  • Fibroblasts, proliferating vs serum-starved (PROLIF vs SS): 999 nuclei on 11 slides (Kalinin et al. 2018).
  • PC3 cells, epithelial vs EMT (EPI vs EMT): 561 nuclei on 6 slides (same paper).
  • Astrocytes, untreated vs valproic acid (NHA vs VPA): 832 nuclei in 216 tiles, imaged on days 3, 5 and 7 (Kalinin et al. 2021).

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:

  • one slide per class for the 2018 sets, over every pair;
  • tiles, or a whole day, for VPA.

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.

comparison held out folds baseline AUC Δ, + all four new Δ, + Fractal Dimension only
fibroblast PROLIF vs SS 1 slide per class 28 0.784 / 0.766 +0.001 / −0.005 +0.008 / −0.004
astrocyte NHA vs VPA tiles 25 0.741 / 0.753 +0.016 / +0.003 +0.017 / +0.005
astrocyte NHA vs VPA one day 3 0.653 / 0.657 +0.023 / −0.023 +0.027 / −0.005
PC3 EPI vs EMT 1 slide per class 8 0.368 / 0.494 +0.127 / +0.049 +0.009 / +0.011
  • 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:

    • VPA: +0.018 / +0.008 on tiles and +0.036 / +0.024 on days, against +0.016 / +0.003 and +0.023 / −0.023 at 2×;
    • fibroblasts: worse at 1× (−0.004 / −0.009);
    • 3× is within noise of 2× on both.

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

feature cubic (default blur) raw marching cubes
the 18 features from #61 ≥ 0.93 / ≥ 0.86 / ≥ 0.73 same (no blur)
Total Absolute Gaussian Curvature 0.76 / 0.82 / 0.78 0.24 / 0.45 / −0.02
Avg Shape Index 0.88 / 0.85 / 0.79 0.82 / 0.37 / 0.83
Avg Curvedness 0.96 / 0.94 / 0.94 −0.11 / 0.85 / 0.34
Fractal Dimension 0.62 / 0.37 / 0.40 0.12 / −0.49 / −0.16
  • The blur is what makes curvature comparable to Mask2Mesh. Without it, the curvature measures mostly measure the voxel staircase.
  • Neither surface separates the sampled classes better. On 15 vs 15 nuclei, per-feature AUCs differ by at most 0.12 in either direction, which is about one standard error.
  • Cost. Mask2Mesh takes a median of 113–823 s per downsampled nucleus, on a shared node. cubic takes 0.26–0.47 s per full-resolution nucleus for the four smoothed features on one A40 (median over the blur sweep).

Known limits, not changed here

  • extract_mesh_features(mesh) without smooth_mesh measures 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.
  • The blurred mask is meshed on the native grid. On a strongly anisotropic stack the triangles are slivers: at spacing (4, 1, 1), 44% of the faces of the test ellipsoid are obtuse. The effect on the curvature features was not measured beyond the Mask2Mesh comparison above, whose data have a z to xy ratio of about 2.4 to 2.7.
  • Avg Shape Index averages over all vertices, including nearly flat ones, where the shape index is not defined.

Test plan

  • tests/feature/test_mesh.py at 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-simplification
  • at head 1b2422b, with the locked versions: tests/feature/test_mesh.py 47 passed; full suite 785 passed, 166 skipped
  • ruff check ., ruff format --check ., mypy --ignore-missing-imports cubic/
  • CI at head 1b2422b
  • real-data validation (above)

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

  • Add total absolute Gaussian curvature, area-weighted average shape index, average curvedness, and fractal dimension mesh features.

Bug Fixes:

  • Return NaN for curvature features when an object disappears under smoothing and for fractal dimension when meshes are too small for decimation, while preserving other feature extraction.

Enhancements:

  • Support configurable physical-scale Gaussian smoothing for curvature-based features, defaulting to twice the coarsest voxel spacing.
  • Allow smoothed surfaces to be supplied separately when extracting curvature-based features and validate blurred mesh generation options.

Build:

  • Add fast-simplification as an optional mesh dependency for fractal-dimension estimation.

Documentation:

  • Document the new shape measures, smoothing behavior, units, and feature requirements.

Tests:

  • Add coverage for curvature measures, smoothing scale and units, orientation stability, fractal-dimension edge cases, dependency errors, and mesh-generation validation.

alxndrkalinin and others added 29 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
@sourcery-ai

sourcery-ai Bot commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Reviewer's Guide

API

Expose curvature smoothing through per-label extraction and document its physical-scale behavior.

  • cubic/feature/mesh.py L121, L140-142

Expose smoothing and optional smoothed-mesh input through the surface and mesh APIs, documenting their behavior.

  • cubic/feature/mesh.py L192-211, L296-307, L366-369 (+2 small edits)

Implementation

Define the new shape measures and their smoothed-mesh interpretation in the mesh feature documentation and registry.

  • cubic/feature/mesh.py L81-92, L578-583 (+2 small edits)

Build and select a blurred mesh only for requested shape measures, preserving other features and returning NaNs when the mask vanishes.

  • cubic/feature/mesh.py L177, L214-231, L395-403

Add physical-unit blur validation and Gaussian-smoothed mask meshing, including explicit handling of ignored marching-cubes options.

  • cubic/feature/mesh.py L232-270, L309-320

Implement mixed-area principal-curvature estimates, area-weighted shape statistics, and QEM fractal dimension.

  • cubic/feature/mesh.py L445-551

Configuration

Add the optional fast-simplification dependency required to calculate fractal dimension.

  • pyproject.toml L48-50

Tests

Add and update mesh tests for smoothed shape measures, scale and orientation behavior, fractal dimension, invalid inputs, and vanished masks.

  • tests/feature/test_mesh.py L318-326, L362-386, L427-601 (+5 small edits)

Lock files and vendored code

Update the dependency lockfile to record the optional mesh dependency change.

  • uv.lock L1043-1078 (+3 small edits)

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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

Comment thread cubic/feature/mesh.py Resolved
alxndrkalinin and others added 7 commits November 17, 2026 15:32
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
@alxndrkalinin
alxndrkalinin changed the base branch from fix/mesh-features to main November 18, 2026 01:43
alxndrkalinin and others added 5 commits November 17, 2026 19:47
_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
@alxndrkalinin

Copy link
Copy Markdown
Owner Author

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 main after #61 merged (reviewed under #61)

  • Addressed in 4ae2e33: test docstrings no longer quote timings of removed code
  • Addressed in b926c34: the meshing stub in the tests drops a default it could never use
  • Addressed in 2068dea: the lint job installs the mesh extra, so mypy checks against trimesh's annotations
  • Fixed in 69c5ae6: a trimesh older than 4.6.12 raises ImportError when cubic.feature.mesh is imported
  • Fixed in b2e0de2: a one-shot iterable as the feature list keeps its names

From the local review of this PR

  • Addressed in 20765ea: _mixed_area builds the opposite-edge lengths in one indexed step, bitwise the same
  • Addressed in 2d5fc4e: the duplicate spacing-unit test is folded into the existing one; the torus mask is one helper
  • Addressed in f41aa0f: a test pins the default blur to twice the coarsest spacing on an anisotropic stack
  • Fixed in 2b99c10: mask2mesh refuses marching_cubes_kwargs together with sigma, and a bad sigma is named as such

alxndrkalinin added a commit that referenced this pull request Nov 18, 2026
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
@alxndrkalinin
alxndrkalinin marked this pull request as ready for review November 18, 2026 06:34

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread cubic/feature/mesh.py Resolved
Comment thread cubic/feature/mesh.py Resolved
Comment thread cubic/feature/mesh.py Resolved
Comment thread cubic/feature/mesh.py Resolved
Comment thread cubic/feature/mesh.py Resolved
Comment thread tests/feature/test_mesh.py Resolved
Comment thread tests/feature/test_mesh.py Resolved
Comment thread tests/feature/test_mesh.py Resolved
@alxndrkalinin
alxndrkalinin merged commit 308c89c into main Nov 20, 2026
9 checks passed
@alxndrkalinin
alxndrkalinin deleted the feat/mesh-curvature-features branch November 20, 2026 20:15
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