Skip to content

fix(feature): position- and device-independent mesh curvature features - #68

Open
alxndrkalinin wants to merge 20 commits into
fix/mesh-measurement-accuracyfrom
fix/mesh-device-and-position
Open

alxndrkalinin wants to merge 20 commits into
fix/mesh-measurement-accuracyfrom
fix/mesh-device-and-position

Conversation

@alxndrkalinin

@alxndrkalinin alxndrkalinin commented Nov 20, 2026 •

Copy link
Copy Markdown
Owner

Stacked on #66.

Changes

  • Measure a mask over its object's bounding box (1ef9d29). extract_surface_features, and mask2mesh(..., sigma=...), blurred and meshed the mask in its own frame. Marching cubes returns float32 vertices, which round coarser far from the frame's origin, so a nucleus 2,030 voxels from the origin of a full-frame mask moved Avg Shape Index by 6.6e-4 relative (up to 3.7e-2 at anisotropic spacing). Both now crop to the object's box first; the far and near copies give identical values, and a mask gives the values extract_features gives the same object as a label. Masks that are not cropped tight move slightly (4e-6 relative on a test ellipsoid).

  • Keep a mesh on the GPU of its mask (d77f892). Only marching cubes ran on the input's GPU; padding, face reversal, the vertex merge and every ArrayMesh property ran on the current device. A new cubic.cuda.on_device_of makes the array's GPU current; the four entry points and ArrayMesh's cached properties run under it. to_same_device now places the source on the reference's GPU instead of the current one.

  • Leave nearly planar vertices out of the shape index (e7c943a). The shape index is the angle of (k1, k2), undefined at a planar point (Koenderink and van Doorn, 1992), so at a nearly flat vertex rounding sets it, and the area average counted such vertices in full: NumPy and CuPy differed by up to 6.0e-7 on real nuclei. Avg Shape Index is now the area average over the vertices whose curvedness is at least 1% of the object's area-weighted median curvedness; the cut is relative, so it does not depend on scale. (82df452 first weighted every vertex by curvedness, which made the average follow curvature magnitude: Spearman with Total Absolute Gaussian Curvature -0.68 to -0.90; e7c943a replaces it.) Values stay close to fix(feature): deterministic bounding shapes, accurate dihedral angles, fixed-order GPU sums #66's (Spearman 0.977 / 0.997 / 0.9995 per dataset); the cut removes a median of 1.6% / 0.09% / 0% of the surface (up to 19% on a flat fibroblast nucleus).

  • Place blurred level-set vertices in float64 (52b8475). Marching cubes rounds vertices to float32 at a step that grows with the index, and the curvature estimates amplified it: Total Absolute Gaussian Curvature was up to 3.6e-2 (median 2e-5 to 1.8e-4) and Avg Curvedness up to 2.8e-3 off the float64-vertex value on real nuclei. Each float32 vertex strictly inside a grid edge is re-interpolated in float64 from the field (45 lines; vertices on grid points keep float32). The rule reads only the float32 vertex and the field, so CPU and GPU give the same float64 mesh.

Effect on real nuclei (2,392 nuclei, three datasets)

  • CPU vs GPU, 99 nuclei: all 990 level-set meshes bitwise equal; Avg Shape Index within 1.5e-10 (same vertices kept on both devices), curvedness 1.6e-11, TAGC 6.9e-15.
  • Classification vs fix(feature): deterministic bounding shapes, accurate dihedral angles, fixed-order GPU sums #66, paired per fold on the benchmark's primary splits: every comparison neutral. The 18 size/shape features are unchanged; with the four smoothed features added, fibroblast +0.0003 (logreg) / +0.0005 (gboost), astrocyte (3 folds) +0.001 / +0.001. Shape index alone: fibroblast 0.479 -> 0.486, astrocyte 0.480 -> 0.488, PC3 0.602 -> 0.604. Only Avg Shape Index differs from the curvedness-weighted tables.

Review cleanups (no value changes)

  • _float64_vertices selects rows by mask instead of compacting them, and the step scaling no longer copies step to the GPU; on_device_of checks a CuPy array by its device id and _is_torch_tensor reads sys.modules instead of retrying a failed import torch. On the GPU, extract_surface_features takes 0.89-0.92 of its previous time per nucleus.
  • _object_box uses find_objects; the corner keyword of _level_set_mesh is gone; one curvedness helper serves Avg Curvedness and Avg Shape Index; float64 vertices are no longer copied to float64.
  • All 2,178 feature values of 99 nuclei, and the 990 level-set meshes, are bitwise equal before and after, on CPU and GPU.
  • A new check confirms that the angle-defect floor does not decide the curvature: moving _FLAT_DEFECT to 1e-15 or 1e-13 moves Avg Shape Index and Avg Curvedness by at most 4.9e-9 relative on a blurred flat ellipsoid.

Test plan

  • CPU tests/: 1019 passed, 238 skipped (at the cleanups); tests/feature + tests/test_cuda.py at the head: 328 passed
  • GPU (CuPy 14.2.0) tests/feature + tests/test_cuda.py: 419 passed; CuPy 14.0.1: 425 passed; with torch installed, tests/test_cuda.py: 22 passed
  • two-GPU job at the head (258ccd1): 71 passed (6 torch skips); end-to-end check exits 4 at fix(feature): deterministic bounding shapes, accurate dihedral angles, fixed-order GPU sums #66's head (30.6 MB allocated on GPU 0 for a mask on GPU 1) and 0 here
  • shape-index change and its review fixes, at 655680a: CPU tests/feature + tests/test_cuda.py 329 passed; GPU (CuPy 14.2.0) 420 passed; CuPy 14.0.1 426 passed
  • CI at 655680a

🤖 Generated with Claude Code

https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

Summary by Sourcery

Make mesh curvature features numerically stable and device-independent across object positions, GPU placement, and nearly planar surfaces.

New Features:

  • Make curvature and surface-feature measurements independent of an object's position by operating on its bounding box.
  • Keep mesh construction, feature computation, and cached mesh properties on the GPU that owns the input.
  • Improve blurred level-set curvature accuracy with position-independent float64 vertices.
  • Exclude nearly planar vertices from average shape-index calculations.

Bug Fixes:

  • Prevent numerical rounding and GPU-device placement from changing mesh curvature features across image positions, devices, or coordinate scales.

Enhancements:

  • Add device-aware array movement and execution contexts for multi-GPU workflows.
  • Refine shape-index and curvedness handling for planar and near-planar surface regions.

Documentation:

  • Update mesh-feature documentation to describe bounding-box measurement and the treatment of nearly planar vertices.

Tests:

  • Add CPU, GPU, and multi-GPU coverage for position-independent meshes, device locality, float64 level-set consistency, and robust shape-index behavior.

alxndrkalinin and others added 2 commits November 20, 2026 10:35
extract_surface_features meshed and blurred the mask in its own frame.
Marching cubes returns float32 vertices, which round coarser far from
the frame's origin, so a nucleus 2,030 voxels from the origin of a
full-frame mask moved Avg Shape Index by 6.6e-4 relative, Total Absolute
Gaussian Curvature by 5.7e-4 and Avg Curvedness by 3.0e-4, and by up to
3.7e-2 at spacing (0.29, 0.1, 0.13). extract_features crops each label
to its bounding box and did not move.

extract_surface_features now crops the mask to the bounding box of its
nonzero voxels before any mesh or blur, which pad it as they need, so
the far copy gets the near copy's values exactly and a mask gets the
values extract_features gives the same object as a label.
mask2mesh(..., sigma=...) had the same shift in its blurred mesh (1.2e-4
in vertex position); it now blurs and meshes the crop too and moves the
vertices back to the caller's frame in float64. The module docstring
again states that the features do not depend on the object's position.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
Given a CuPy mask on GPU 1 while GPU 0 was current, mask2mesh returned
its mesh on GPU 0 with the right values. CuPy allocates new arrays and
runs kernels on the current device, and only marching cubes itself was
run on the input's device: the pad before it, the reversed faces, the
shifted vertices, ArrayMesh's vertex merge and lazily computed arrays,
and the blurs and crops of the feature functions ran with GPU 0 current.

cubic.cuda.on_device_of makes the GPU that holds an array current.
mask2mesh, extract_surface_features, extract_features and
extract_mesh_features run under the device of their first argument, and
ArrayMesh computes its merge and every cached property under the device
of its vertices. to_same_device ignored the reference's GPU and placed
the source on the current one; it now places it on the reference's
GPU, copying a CuPy source from another GPU, and returns a source
already there as it is. ArrayMesh.scaled keeps its device context,
through on_device_of: its new vertices are computed before any
to_same_device call. The two-GPU tests skip on one GPU.

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

sourcery-ai Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Reviewer's Guide

API

Add device-context handling to the CUDA utilities and make same-device transfers target the GPU holding the reference array.

  • cubic/cuda.py L5, L12, L336-375

Run the public mesh-feature entry points on the GPU that owns their input.

  • cubic/feature/mesh.py L60-67, L108-126 (+4 small edits)

Implementation

Keep ArrayMesh construction, scaling, and cached geometry calculations on the GPU holding its vertices.

  • cubic/feature/_array_mesh.py L37-51, L227-243, L361-369 (+16 small edits)

Crop surface-feature and smoothed-mesh measurements to the object's bounding box, then restore the mesh to the original frame.

  • cubic/feature/mesh.py L403-411, L663-689, L695-699 (+2 small edits)

Recompute eligible marching-cubes edge vertices in float64 and scale them without discarding that precision.

  • cubic/feature/mesh.py L870-924, L932

Exclude low-curvedness vertices from the area-averaged shape index using a relative, area-weighted median cutoff.

  • cubic/feature/mesh.py L166-171, L1915-1918, L1941-1994 (+1 small edits)

Update the contour-length agreement note to reflect float64 level-set vertices.

  • cubic/feature/mesh.py L2115-2116

Avoid repeated failed torch imports when checking whether an array is a tensor.

  • cubic/cuda.py L85-91, L452

Tests

Add shared CPU/GPU checks that far-positioned objects match near-positioned measurements and meshes.

  • tests/feature/conftest.py L3-4, L123-180

Cover position-independent surface features, precision-stable level sets, and the revised shape-index behavior.

  • tests/feature/test_mesh.py L532-541, L737-759, L911-966 (+13 small edits)

Test CPU/GPU level-set equality, GPU ownership, and far-object feature agreement on GPU inputs.

  • tests/feature/test_mesh_gpu.py L105-135, L380-430, L1054-1064 (+1 small edits)

Adjust unit-conversion expectations and the cropped-mask setup used by the open-volume check.

  • tests/feature/test_mesh_units.py L26-30, L265-267, L278-281

Test transfer to the reference GPU and the device context helper.

  • tests/test_cuda.py L17, L74-115

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

alxndrkalinin and others added 2 commits November 20, 2026 14:10
Avg Shape Index averaged (2 / pi) atan2(k1 + k2, k2 - k1) by area over
the vertices with k1 or k2 nonzero. The shape index is the angle of
(k1, k2), so rounding sets it at a nearly flat vertex, and the area
average counted that vertex in full. Bending the faces of a subdivided
cube by up to 1e-9 moved the average from 0.509 to 0.310. On the 999
fibroblast nuclei, NumPy and CuPy differed by up to 6.0e-7 relative (121
nuclei above 1e-9). The cause was the flat-topped vertices, where the
two devices' arccos angle defects differ by an ulp.

Each vertex now counts by its area times its curvedness,
sqrt((k1^2 + k2^2) / 2), which is the length of (k1, k2). A vertex's term
goes to 0 continuously as the vertex flattens, and planar vertices drop
out without a separate test. The bent cube now moves by 1.5e-8, and NumPy
and CuPy agree to 4.4e-11 on all 2,392 nuclei of the three datasets.

A float64-vertex prototype of the level-set mesh, without the
bounding-box crop, shows the same on nuclei. A 1-voxel frame shift moved
the area average by up to 7.2e-8 (63 of 999 fibroblast nuclei above
1e-9), and multiplying the blur by 1 + 1e-15 u moved it by up to 4e-4.
Weighted by curvedness, those changes are at most 3.4e-11 and 6.6e-12.

Surfaces of constant shape index read as before: sphere 1, cylinder 0.5,
saddle 0. Elsewhere the values move. A blurred ball goes from 0.916 to
0.904, and the median nucleus from 0.35-0.46 to 0.49-0.54, with a
Spearman correlation of 0.84 to 0.96 against the old values.

The flat-angle and flat-defect floors stay. Without them a raw mesh's
shape index varies by 1.2e-10 relative over scale and orientation, and
curvedness and mean curvature still use them.

The ellipsoid test now compares with the curvedness-weighted analytic
average, which the mesh matches within 4.6e-5; the area average is
9.5e-4 away. A new test bends the faces of a cube by 1e-9.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
Both marching cubes compute each edge vertex in float64 and round it to
float32 at a step that grows with the index, so a level set's vertices
depended on where its object lay in the array, and the curvature
estimates amplified the rounding: Total Absolute Gaussian Curvature was
up to 3.6e-2 and Avg Curvedness up to 4e-3 off its float64-vertex value
on real nuclei.

_level_set now meshes at unit spacing and recomputes, in float64, every
vertex that float32 leaves strictly inside a grid edge: a float32 vertex
with exactly one non-integer coordinate lies on the edge from its floor
along that axis, and the interpolation is redone there when that edge
straddles the level and the result rounds back to the float32 vertex.
Vertices that float32 put on a grid point, and cube-centre vertices,
keep their float32 position. The rule reads only the float32 vertex and
the field, so it runs unchanged on the GPU's output, which is skimage's
up to order, and both devices give the same float64 mesh; vertices
coincide in float64 exactly when they do in float32, so the merge of
degenerate faces is unchanged. The vertices are then scaled by the step
in float64.

The flat-residue test no longer asserts that no angle defect lies in
(1e-14, 1e-13]: with float64 vertices real defects reach down to
2.5e-14, and what the defect floor zeroes is still at most four ulps
of 2 pi.

New tests: a blurred ball's level set placed at index 1 and at 1500
agrees to 1.1e-13 after the shift (6.0e-5 in float32), and CPU and GPU
give the same float64 level set bit for bit on a field with a third of
its near-level values set to 0.5 or a float32 neighbour of it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
@alxndrkalinin alxndrkalinin changed the title fix(feature): position- and device-independent mesh features fix(feature): position- and device-independent mesh curvature features Nov 20, 2026
alxndrkalinin and others added 11 commits November 20, 2026 15:24
…g them

_float64_vertices picked the rows to recompute with flatnonzero and a boolean
index, and _level_set copied the step to the GPU to scale the vertices; each
of these makes the host wait for the device. Every row is now computed and
the rows that qualify are chosen with where. A row with several non-integer
coordinates reads the field at its floor, inside the volume, and is
discarded. Each vertex column is multiplied by its step as a Python float,
and not at all for a step of 1, which leaves every double as it is, so the
products are those of verts * step. Same-dtype astype calls no longer copy.

On 33 nuclei of each of three datasets, the level sets that
extract_surface_features meshes (990 of them, 47.8e6 vertices) are bit for
bit those of the previous code on both devices, with identical faces. On the
GPU, for a tight nucleus crop, the level-set stage takes 0.74 to 0.78 of the
previous time and extract_surface_features 0.94 to 0.96 (median of 72
alternating runs, three nuclei).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
on_device_of tried to import torch twice for a CuPy array, once in
get_device and once for the index; a failed import costs about 41 us when
torch is not installed. A CuPy array is now recognised by the id of its
device and no torch check runs for it; any other array runs the check once.
The context returned is the same for a host array, a CuPy array, a CUDA or
CPU torch tensor, and an object with a device id, with torch installed and
without it.

to_same_device no longer tests whether CuPy is installed after to_device(...,
"GPU"), which has already raised if it is not.

With torch not installed, a call on a CuPy array takes 0.4 us instead of 83 us
and to_same_device 89 us instead of 199 us (median of 6 processes).

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

_object_box looped over the axes with a reduction and a host copy each;
it is now the device-agnostic find_objects on the mask as uint8, which
gives the same box on both devices, including None for an empty mask. On
the GPU it takes 0.17 ms instead of 0.35 ms on a 20 x 120 x 100 crop and
3.5 ms instead of 2.2 ms on a 60 x 1024 x 1024 frame (median of 30).

_level_set_mesh took a corner keyword that only _smooth_mask2mesh used,
to shift by (pad - corner) * step instead of pad * step. The caller now
passes pad - corner, so the keyword goes, and _smooth_mask2mesh returns
None as soon as the mask has no box instead of blurring an empty mask.

_curvedness and _shape_index wrote the per-vertex curvedness twice; one
helper now serves both. _shape_index still sets the non-finite weights to
0 before _area_average: passing the weight as it is would differ for a
+inf weight, a curvature above 1e154, which _area_average would turn into
NaN.

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

The crop comment and the _smooth_mask2mesh docstring justified the crop
by float32 vertices, which _level_set no longer returns. The reason now
is that a vertex rounded to a grid point or a cube centre in float32
keeps that float32 position, which depends on where the object lies, and
the crop makes the frame the object's own.

_principal_curvatures gave the nearly flat vertices of a blurred mesh as
the reason for _FLAT_DEFECT, which curvedness weighting made obsolete.
The reason now is the raw voxel meshes, where thousands of flat vertices
carry a rounding-residue defect of at most 1e-14 radians that would
otherwise read as Gaussian curvature.

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

The nearly-flat shape-index test rebuilt the subdivided cube that
_turned_cube builds; _turned_cube takes a bump that moves each face-interior
vertex along its normal before the turn, and the test uses it. The
curvedness-weighting test no longer recomputes the implementation's
weighted average; its bounds and the zero weight of flat vertices remain.

Test docstrings and comments keep what each test asserts: the figures
that no assertion checks and the account of what the code did before are
removed, and the lines over 100 characters are reflowed.

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

_level_set now returns float64 vertices, so the ribbon's area matches
skimage's find_contours to rounding rather than to float32: on ten
blurred ellipses the largest relative difference is 2.2e-16.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
Float64 level-set vertices leave 48 angle defects between 1e-14 and
1e-13 on the blurred flat ellipsoid (the smallest is 2.49e-14), so
test_flat_residues_leave_real_curvature_as_it_is can no longer assert
that none lies there.

It now measures Avg Shape Index and Avg Curvedness, the features that
read _FLAT_DEFECT, at the default floor and at 1e-15 and 1e-13, which
keep and zero those defects, and requires them to agree to 5e-8,
relative. They differ by at most 4.9e-9, at 1e-13; a floor of 1e-11
moves Avg Shape Index by 8e-8 and fails the check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
_level_set returns float64 vertices, so astype(np.float64) in
_level_set_area and in ArrayMesh.__init__ copied the array to the dtype
it already had. Both now pass copy=False; a float32 array is still
converted.

Nothing writes into the result. face_areas indexes the vertices by the
faces, which copies them, and ArrayMesh never changes its vertices in
place. The vertices that mask2mesh hands to ArrayMesh are a fresh array
(the level set minus the padding offset), never the cached level set.
When there is nothing to merge, ArrayMesh.vertices is now the array it
was given, as it already is with merge=False.

extract_surface_features of three lumpy nuclei, with and without
curvature_sigma, gives bitwise-equal values before and after on the CPU
and on the GPU (138 values on each device).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
Python does not cache a failed import, so with torch not installed every
call of _is_torch_tensor tried to import it again: 27.7 to 28.6 us per
call (best of 5 runs of 20000 calls, in each of 6 processes), and 28.6
to 29.3 us for get_device of a NumPy array.

_is_torch_tensor now reads sys.modules. A tensor cannot exist unless
torch has been imported, so with torch not in sys.modules the answer is
False. A call takes 0.08 us, and get_device of a NumPy array 0.20 us.
It also no longer imports torch when torch is installed but nothing has
imported it yet.

The answer is unchanged for a NumPy array, a CuPy array, and a CPU, a
CUDA and a Parameter torch tensor.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
The warning said that all vertices are planar (k1 = k2 = 0), but
_shape_index returns NaN, and warns, whenever no vertex has a finite,
positive area times curvedness. A planar mesh is one such case, not the
only one. The message and the docstring now state that condition.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
tests/feature/conftest.py also serves the voxel and texture tests, which
must run without trimesh. cubic.feature loads mesh lazily; importing it
at the top of conftest would load trimesh for them too, and warn when
it is missing. A comment now says so, so that the import is not moved to
the top.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
@alxndrkalinin
alxndrkalinin marked this pull request as ready for review November 21, 2026 01:04

@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 3 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="cubic/cuda.py" line_range="90" />
<code_context>
-    try:
-        import torch
-    except ImportError:
+    torch = sys.modules.get("torch")
+    if torch is None:
         return False
</code_context>
<issue_to_address>
**Concurrent torch startup breaks array checks**

When one thread is performing the first torch import while another calls an array helper that reaches `_is_torch_tensor`, `_is_torch_tensor` can observe the partially initialized module before `torch.Tensor` is available, so accessing `torch.Tensor` raises `AttributeError`; concurrent callers checking even ordinary NumPy arrays then fail during startup.

Handle a module without `Tensor` yet (or synchronize with torch initialization) before calling `isinstance`.
</issue_to_address>

### Comment 2
<location path="cubic/feature/_array_mesh.py" line_range="148" />
<code_context>
         )


</code_context>
<issue_to_address>
**Cached mesh geometry becomes stale**

When a caller retains the float64 vertex array, the mesh has no vertices to merge or drop, and the caller mutates that array after a mesh property has been cached, `_merge_vertices` returns the input vertex array unchanged when it finds no merges, so a caller updating its retained array changes the mesh without invalidating cached properties such as `area_faces` and `face_normals`; later feature calculations then combine stale caches with the new vertices.

Copy the vertices before storing them, or otherwise ensure mutations to the caller's array invalidate all mesh and host caches.
</issue_to_address>

### Comment 3
<location path="tests/feature/test_mesh.py" line_range="906" />
<code_context>
     name = "Avg Shape Index"
     value = mesh.extract_mesh_features(cube, [name])[name]

+    assert (weight[flat] == 0).all()
     assert 0.5 <= value <= 1
-    expected = (shape_index * area)[curved].sum() / area[curved].sum()
</code_context>
<issue_to_address>
**Cube accepts area-only averaging**

When `_shape_index` uses area-only averaging for the cube, when `_shape_index` reverts to area-only averaging, `test_shape_index_weights_vertices_by_curvedness` still passes: the cube’s old value of about 0.509 satisfies the bounds, and this assertion checks a separately computed `weight`, not the weight used to produce `value`.

Assert that the returned value matches an independently calculated curvedness-weighted average.
</issue_to_address>

Sourcery assessment

Approval pending. 3 findings to address first.

Blocking findings: cubic/cuda.py:90, cubic/feature/_array_mesh.py:148, tests/feature/test_mesh.py:906


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

Comment thread cubic/cuda.py
try:
import torch
except ImportError:
torch = sys.modules.get("torch")

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.

🟡 Medium · Concurrent torch startup breaks array checks

When one thread is performing the first torch import while another calls an array helper that reaches _is_torch_tensor, _is_torch_tensor can observe the partially initialized module before torch.Tensor is available, so accessing torch.Tensor raises AttributeError; concurrent callers checking even ordinary NumPy arrays then fail during startup.

Handle a module without Tensor yet (or synchronize with torch initialization) before calling isinstance.

Prompt for AI agents
In `cubic/cuda.py` at line 90:

**Concurrent torch startup breaks array checks**

When one thread is performing the first torch import while another calls an array helper that reaches `_is_torch_tensor`, `_is_torch_tensor` can observe the partially initialized module before `torch.Tensor` is available, so accessing `torch.Tensor` raises `AttributeError`; concurrent callers checking even ordinary NumPy arrays then fail during startup.

Handle a module without `Tensor` yet (or synchronize with torch initialization) before calling `isinstance`.

with on_device_of(vertices):
vertices, faces = _merge_vertices(
vertices.astype(np.float64, copy=False), faces.astype(np.int64)
)

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.

🟡 Medium · Cached mesh geometry becomes stale

When a caller retains the float64 vertex array, the mesh has no vertices to merge or drop, and the caller mutates that array after a mesh property has been cached, _merge_vertices returns the input vertex array unchanged when it finds no merges, so a caller updating its retained array changes the mesh without invalidating cached properties such as area_faces and face_normals; later feature calculations then combine stale caches with the new vertices.

Copy the vertices before storing them, or otherwise ensure mutations to the caller's array invalidate all mesh and host caches.

Prompt for AI agents
In `cubic/feature/_array_mesh.py` at line 148:

**Cached mesh geometry becomes stale**

When a caller retains the float64 vertex array, the mesh has no vertices to merge or drop, and the caller mutates that array after a mesh property has been cached, `_merge_vertices` returns the input vertex array unchanged when it finds no merges, so a caller updating its retained array changes the mesh without invalidating cached properties such as `area_faces` and `face_normals`; later feature calculations then combine stale caches with the new vertices.

Copy the vertices before storing them, or otherwise ensure mutations to the caller's array invalidate all mesh and host caches.

Comment thread tests/feature/test_mesh.py Resolved
alxndrkalinin and others added 5 commits November 21, 2026 14:38
Koenderink and van Doorn (1992) define the shape index and the
curvedness as the angle and radius of (k1, k2): independent
coordinates, with the shape index undefined at a planar point.
Weighting each vertex by its curvedness made Avg Shape Index follow
curvature magnitude as well as shape.

Avg Shape Index is now the area-weighted mean of the shape index over
the vertices with a finite, positive area and a curvedness of at least
1e-2 times the area-weighted median curvedness of the vertices with
positive curvedness. The cut is relative to the object, so it does not
depend on scale. Rounding sets the shape index of a nearly flat vertex;
with a cut of 1e-3, rounding still moved the value of blurred nuclei
by more than 1e-9 between devices and frames. The value is NaN, with a
warning, when no vertex is kept. On a surface that is mostly nearly
flat, the median is that of the nearly flat vertices, so they are kept.

On 2,392 real nuclei of three datasets, the values return to the level
of #66: Spearman 0.977, 0.997 and 0.9995 with the #66 values per
dataset, and every within-fold AUROC comparison with #66 is neutral.
Only Avg Shape Index changes in the feature tables. Against the
curvedness weight, the univariate AUROC of the shape index rises on the
PC3 EMT split (0.501 to 0.604) and falls on the fibroblast split (0.542
to 0.486); with the four smoothed features added to the 18 mesh
features, the VPA day split falls by 0.034 with logistic regression
and rises by 0.012 with gradient boosting. On a 99-nucleus sample, CPU
and GPU agree to 1.5e-10 relative and keep the same vertices.

Tests: the cube test now checks that the face-interior vertices are
left out and that the value is the area average over the rest. The
test with every face bent by 1e-9 is replaced by two: half of one face
bent by 1e-9 falls below the cut (without the cut the value moves by
0.069), and faces moved by 1e-14 stay flat under the floors and leave
the value unchanged. The ellipsoid test compares with the analytic area
average.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
_area_median read the median as values[order][index], which builds a
full sorted copy of the values to take one element. The expression
values[order[index]] reads the same element from the original array.

The value is unchanged: on 120 random arrays of 1 to 100,001 elements,
on NumPy and on CuPy, the new and the old expression returned equal
values every time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
The _shape_index docstring said twice that the cut is relative to the
object: "planar relative to the object, so the cut does not depend on
its scale" and "the cut is relative to the object's own median
curvedness, so on a surface that is mostly nearly flat ...". It now
says it once and keeps both consequences: the same vertices are kept at
any scale, and on a mostly nearly flat surface the median is that of
the nearly flat vertices, so the cut is low and they are kept.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
Two docstrings quoted spreads of Avg Shape Index measured before the
average left out the vertices below the relative cut.

test_raw_shape_index_does_not_depend_on_scale_or_orientation: with
_FLAT_ANGLE at 1e-14 and at 3e-14 the spread over scales and
orientations is now 7.0e-16 and 1.7e-16, the size of rounding next to
the 1.3e-16 of the shipped floor, so those two figures are dropped. With
the cut set to 0 they reproduce the old 9.5e-3 and 6.4e-4. With
trimesh's arccos angles the spread is 5.1e-10, measured on centred
copies; it replaces 3.0e-3, measured before the copies were centred.

test_gpu_shape_index_of_a_raw_mesh_matches_numpy: with _FLAT_ANGLE and
_FLAT_DEFECT both at 0, NumPy and CuPy now differ by 1.4e-17 in Avg
Shape Index, so the figure "about 1e-3" is dropped. The test asserts
the same agreement to 1e-12 as before.

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

Avg Shape Index now averages by area over vertices down to 1% of the
median curvedness, where the angle of (k1, k2) moves most with
rounding. Through a unit conversion of the blurred anisotropic mesh it
now differs by up to 6.9e-13 relative on the CPU and on CuPy 14.2.0 and
14.0.1, against 5.6e-14 before; every other feature stays within
5.3e-14. _RTOL goes from 1e-12, 1.45 times the new figure, to 1e-11.
A wrong unit power changes a feature by orders of magnitude, so the
checks still catch it.

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

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.

1 participant