Repository navigation
fix(feature): position- and device-independent mesh curvature features - #68
alxndrkalinin wants to merge 20 commits into
Conversation
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
Reviewer's GuideAPIAdd device-context handling to the CUDA utilities and make same-device transfers target the GPU holding the reference array.
Run the public mesh-feature entry points on the GPU that owns their input.
ImplementationKeep ArrayMesh construction, scaling, and cached geometry calculations on the GPU holding its vertices.
Crop surface-feature and smoothed-mesh measurements to the object's bounding box, then restore the mesh to the original frame.
Recompute eligible marching-cubes edge vertices in float64 and scale them without discarding that precision.
Exclude low-curvedness vertices from the area-averaged shape index using a relative, area-weighted median cutoff.
Update the contour-length agreement note to reflect float64 level-set vertices.
Avoid repeated failed torch imports when checking whether an array is a tensor.
TestsAdd shared CPU/GPU checks that far-positioned objects match near-positioned measurements and meshes.
Cover position-independent surface features, precision-stable level sets, and the revised shape-index behavior.
Test CPU/GPU level-set equality, GPU ownership, and far-object feature agreement on GPU inputs.
Adjust unit-conversion expectations and the cropped-mask setup used by the open-volume check.
Test transfer to the reference GPU and the device context helper.
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
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
…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
There was a problem hiding this comment.
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
| try: | ||
| import torch | ||
| except ImportError: | ||
| torch = sys.modules.get("torch") |
There was a problem hiding this comment.
🟡 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) | ||
| ) |
There was a problem hiding this comment.
🟡 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.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
Stacked on #66.
Changes
Measure a mask over its object's bounding box (1ef9d29).
extract_surface_features, andmask2mesh(..., 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 valuesextract_featuresgives 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
ArrayMeshproperty ran on the current device. A newcubic.cuda.on_device_ofmakes the array's GPU current; the four entry points andArrayMesh's cached properties run under it.to_same_devicenow 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)
Review cleanups (no value changes)
_float64_verticesselects rows by mask instead of compacting them, and the step scaling no longer copiesstepto the GPU;on_device_ofchecks a CuPy array by its device id and_is_torch_tensorreadssys.modulesinstead of retrying a failedimport torch. On the GPU,extract_surface_featurestakes 0.89-0.92 of its previous time per nucleus._object_boxusesfind_objects; thecornerkeyword of_level_set_meshis gone; one curvedness helper serves Avg Curvedness and Avg Shape Index; float64 vertices are no longer copied to float64._FLAT_DEFECTto 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
tests/: 1019 passed, 238 skipped (at the cleanups);tests/feature+tests/test_cuda.pyat the head: 328 passedtests/feature+tests/test_cuda.py: 419 passed; CuPy 14.0.1: 425 passed; with torch installed,tests/test_cuda.py: 22 passedtests/feature+tests/test_cuda.py329 passed; GPU (CuPy 14.2.0) 420 passed; CuPy 14.0.1 426 passed🤖 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:
Bug Fixes:
Enhancements:
Documentation:
Tests: