Skip to content

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

Draft
alxndrkalinin wants to merge 2 commits into
fix/mesh-featuresfrom
feat/mesh-curvature-features
Draft

alxndrkalinin wants to merge 2 commits into
fix/mesh-featuresfrom
feat/mesh-curvature-features

Conversation

@alxndrkalinin

@alxndrkalinin alxndrkalinin commented Oct 30, 2026 •

Copy link
Copy Markdown
Owner

Stacked on #61 (base fix/mesh-features); retarget to main once #61 merges.

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.

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.

  • 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).

Test plan

  • tests/feature/test_mesh.py: 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
  • ruff check ., ruff format --check ., mypy --ignore-missing-imports cubic/
  • full suite and CI
  • real-data validation (above)

🤖 Generated with Claude Code

https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

Summary by Sourcery

Add ShapeTools-inspired curvature and fractal-dimension measures to mesh feature extraction with scale-aware smoothing.

New Features:

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

Enhancements:

  • Measure curvature-based features on an optionally smoothed mask mesh with configurable physical blur scale and graceful handling of objects that vanish under smoothing.
  • Expose smoothed mesh support through surface extraction and mask-to-mesh APIs while preserving raw-mesh measurements for existing features.

Build:

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

Documentation:

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

Tests:

  • Add coverage for curvature measures, fractal dimension, scale and rotation behavior, smoothing failures, dependency errors, and selective smoothing.

alxndrkalinin and others added 2 commits October 29, 2026 21:44
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

The PR adds four optional ShapeTools-inspired mesh descriptors, computes curvature-based measures on a physically scaled Gaussian-smoothed mask, estimates fractal dimension through QEM decimation, and covers the new behavior with extensive feature and validation tests.

Sequence diagram for smoothed mesh feature extraction

sequenceDiagram
    participant Caller
    participant Extract as extract_surface_features
    participant Smooth as _smooth_mask2mesh
    participant Features as extract_mesh_features
    participant Mesh as trimesh

    Caller->>Extract: extract_surface_features(mask, spacing, features, curvature_sigma)
    Extract->>Extract: _curvature_sigma(spacing, curvature_sigma)
    Extract->>Smooth: _smooth_mask2mesh(mask, spacing, sigma)
    Smooth-->>Extract: smooth_mesh
    Extract->>Features: extract_mesh_features(mesh, features, smooth_mesh)
    Features->>Mesh: compute curvature features on smooth_mesh
    Features->>Mesh: compute other features on mesh
    Features-->>Caller: feature values
Loading

Flow diagram for optional smoothed curvature features

flowchart TD
    A["extract_surface_features"] --> B{"Any smoothed feature requested?"}
    B -->|No| C["Extract all requested features from raw mesh"]
    B -->|Yes| D["Resolve curvature_sigma"]
    D --> E["Blur mask in physical units"]
    E --> F{"Mask reaches 0.5 level?"}
    F -->|No| G["Warn and return NaN for four smoothed features"]
    G --> H["Compute remaining features on raw mesh"]
    F -->|Yes| I["Generate smoothed mesh"]
    I --> J["Compute curvature features on smoothed mesh"]
    J --> K["Compute other features on raw mesh"]
Loading

File-Level Changes

Change Details Files
Adds four ShapeTools-inspired shape measures and centralizes their registration and computation.
  • Registers total absolute Gaussian curvature, area-weighted shape index, area-weighted curvedness, and QEM-based fractal dimension.
  • Computes per-vertex principal curvatures using mixed Voronoi areas, angle defects, and signed edge dihedral curvature.
  • Estimates fractal dimension from the log area versus face-count slope across six QEM decimation levels.
cubic/feature/mesh.py
Introduces scale-aware smoothing for curvature-dependent measurements while preserving raw-mesh measurements for other features.
  • Adds optional curvature_sigma to per-label and single-mask extraction, defaulting to twice the coarsest voxel spacing.
  • Blurs masks isotropically in physical units with padding before marching cubes, and returns NaN plus a warning when the object vanishes.
  • Extends mask2mesh with sigma and allows extract_mesh_features to use a separate smooth_mesh for selected features.
cubic/feature/mesh.py
Adds the fractal-dimension dependency to the mesh extra and updates the locked environment.
  • Requires fast-simplification>=0.1.9 for QEM decimation.
  • Updates the uv lockfile with the new dependency resolution.
pyproject.toml
uv.lock
Expands mesh feature coverage with analytic-shape, scaling, orientation, dependency, smoothing, and validation tests.
  • Tests curvature behavior on balls, tori, peanut shapes, rotated ellipsoids, and unit rescaling.
  • Tests fractal dimension, missing-dependency messaging, blur failure handling, selective smoothing, mesh equivalence, and sigma validation.
  • Adjusts existing pipeline stubs and tests for smoothing and the optional simplification dependency.
tests/feature/test_mesh.py

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
raise RuntimeError(
"Fractal Dimension needs fast-simplification. Install with 'cubic[mesh]'"
)
n_faces = len(mesh.faces)

This branch has not been deployed

No deployments
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