Skip to content

feat(feature): mesh features on the GPU (CUDA marching cubes, ArrayMesh) - #63

Draft
alxndrkalinin wants to merge 42 commits into
feat/mesh-curvature-featuresfrom
feat/mesh-gpu
Draft

alxndrkalinin wants to merge 42 commits into
feat/mesh-curvature-featuresfrom
feat/mesh-gpu

Conversation

@alxndrkalinin

@alxndrkalinin alxndrkalinin commented Oct 30, 2026 •

Copy link
Copy Markdown
Owner

Stacked on #62 (base feat/mesh-curvature-features). Retarget once #61 and #62 merge.

Summary

Mesh features now follow cubic's device-agnostic API: a CuPy label image or mask is meshed and measured on the GPU, and the results match the CPU path.

  • CUDA marching cubes (cubic/feature/_marching_cubes_cuda.py). cuCIM has none, so this ports scikit-image's Lewiner implementation, running on scikit-image's own lookup tables and the same face and interior ambiguity tests. It works in three passes:

    1. Classify each cube, then mark the edges and cube centres it uses.
    2. Number them by prefix sum and compute the vertices.
    3. Write each cube's triangles.

    An edge vertex depends only on its edge's two corner values. So with float64 corner arithmetic in the reference's operation order, and --fmad=false, the vertices round to skimage's float32 values. The mesh is the same as skimage's up to vertex and face order. With allow_degenerate=False the port also merges every coincident vertex, where skimage merges only those of degenerate faces; the two meshes are equal once duplicates are merged on both sides. The call runs on the input volume's device, whichever device is current.

  • ArrayMesh (cubic/feature/_array_mesh.py). It provides the trimesh attributes the feature registry reads, computed with trimesh's formulas on NumPy or CuPy arrays: mass properties, Euler number, adjacency with dihedral angles and convexity, integral mean curvature, angle defects. It merges coincident vertices and drops unreferenced ones as trimesh's processing does. The convex hull and the bounding box, cylinder and sphere fall back to a host trimesh.Trimesh built on first use; a delegated method that would change the mesh in place raises TypeError.

  • GPU dispatch in mesh.py. extract_features, extract_surface_features and mask2mesh keep CuPy input on the GPU. mask2mesh returns an ArrayMesh for CuPy input and a trimesh.Trimesh for NumPy. On the GPU it accepts level, spacing and allow_degenerate among marching_cubes_kwargs; other keywords raise.

  • Fractal Dimension, re-estimated so it runs on both devices (commit 50cdcfd). The QEM-decimation estimator from feat(feature): ShapeTools shape measures on a smoothed mesh (total |K|, shape index, curvedness, fractal dimension) #62 returned 2.0001 ± 0.0001 on every nucleus: decimating a smooth (blurred) mesh barely changes its area. It also needed QEM on the host.

    • New estimator: 2 − the slope of log surface area against log blur scale, from the finest voxel spacing to curvature_sigma, with each area divided by the same area for the mask's smooth twin (its blur at curvature_sigma). The twin cancels the shrinking of curved surfaces under blur.
    • Smooth ellipsoids of nucleus size measure 2.000 ± 0.005, against 2.05–2.20 when using the blurred area alone. Band-limited roughness (0.4 µm) raises D monotonically.
    • Every step (blur, marching cubes, area) runs on the mask's device; a GPU test asserts it never builds a host trimesh, and CPU/GPU agree to rtol 1e-9. fast-simplification is no longer needed.
    • The mask is blurred at curvature_sigma once for both the smoothed mesh and D: 10 blurs and 11 marching-cubes calls per object, down from 12 and 12. The twin is blurred on the mask's own crop (commit 367ad00), which moved D by at most 3.95e-07 on the test masks.
    • The ladder's other blurs pad by one voxel (commits db2d1a0, 3064a43): the field on the mask's frame is bitwise the same, and D moved by at most 1.8e-8.
    • D needs the mask, so extract_mesh_features rejects it and leaves it out of its defaults.
  • Settable window, thin-object warning and an in-plane variant (commits 7da2d9d to 3064a43).

    • fractal_scales=(lowest, highest) sets the blur scales of the Fractal Dimension fit, in units of spacing. The default, the finest voxel spacing up to curvature_sigma, is unchanged.
    • On smooth synthetic shapes the 3D value is unbiased only while the top scale is at most a quarter of the object's Min Axis Length; above that it reads low. In that case the value is still returned, with one warning per label image.
    • Outline Fractal Dimension is a new optional feature, computed only when requested by name (mesh_feature_list(optional=True) lists it). It is the same estimator on the outline of the mask's projection along the first axis: 1 − slope of log contour length, about 1 for a smooth outline. Its window is outline_fractal_scales, by default 4 to 16 in-plane voxels. The contour length comes from marching cubes on a two-layer copy of the blurred footprint, so it runs on both devices with the same result. It is meant for flat objects imaged along the first axis and is the one feature defined on the image axes. It needs a footprint about 5 times the top scale across (0.99 on a smooth disc there, NaN below 3.2 times).
    • Why: in a scale-window sweep on three nucleus datasets, the outline form agreed between two segmenters of the same nuclei at Spearman rho 0.85 on astrocytes and fibroblasts, against 0.44 and 0.53 for the 3D default, and separated proliferating from serum-starved fibroblasts on held-out samples at AUROC 0.66, against 0.57.
    • Wrong-type windows raise TypeError, bad values ValueError, and warnings are attributed to the line that called the public function.
  • Shared SciPy-rounding Gaussian. image_utils.gaussian_filter_like_scipy replaces the private filter in aics_workflows. The curvature blur now uses it too, so the smoothed mesh is identical on both devices. cupyx alone differs from SciPy by up to 1.8e-7, which moved total |K| by 7e-4 relative. Complex input keeps its imaginary part on the GPU.

  • Shared kernel helpers. The CUDA compile and launch helpers moved from aics_workflows to cubic.cuda, where both kernel modules use them.

Evidence

check result
marching cubes, binary noise 40³ (all 14 Lewiner cases) identical to skimage: 99,337 vertices / 232,154 faces
marching cubes, continuous noise 64³ identical: 401,937 / 878,906; 88 ms on the GPU against 1.7 s for skimage
marching cubes, blurred noise, anisotropic balls, exact level hits (with and without degenerate removal) identical, including output dtype
marching cubes with the default level on a non-binary volume identical; a float64 midpoint moved 1,607 of 35,079 vertex coordinates by an ulp
marching cubes with the volume on GPU 1 and GPU 0 current (two-GPU node, float32 and float64 input) mesh on GPU 1, identical to skimage
ArrayMesh on NumPy against trimesh (ball, hollow ball, 58k-vertex VPA nucleus) ≤ 1.7e-16 relative on every feature
ArrayMesh against trimesh on a mesh with coincident and unreferenced vertices same vertex count, Euler number, area and angle defects
extract_features with CuPy against NumPy (three labels) rtol 1e-9 on every feature
Outline Fractal Dimension against contour lengths from find_contours on 60 real nuclei (three datasets) within 1.1e-8
default output of extract_surface_features before and after the fractal-dimension commits (8 masks, CPU) identical, except Fractal Dimension within 1.8e-8

Timings on two real VPA nuclei (about 330k voxels each), per nucleus:

features computed CPU GPU (A40) speedup max CPU–GPU difference
GPU-native (all but the hull, bounding-shape and fractal-dimension features) 1.15 s 0.03 s 39× 4e-11
+ hull and box features, on the host 1.25 s 0.36 s 3.5× 6e-11
everything, incl. the old QEM fractal dimension, on the host (before 50cdcfd) 1.88 s 0.93 s 2.0× 5e-11

The timings in commit 36f4e41's message were taken while another job held the GPU at 100%. They are superseded by the table above.

Fractal Dimension alone, per mask, on synthetic masks (median of 5 runs): 28–33 ms on an A40; 374–516 ms on the CPU for anisotropic masks of 58k–127k voxels, and 42–53 ms for isotropic masks of 3k–7k voxels. These were taken before the one-voxel padding of the ladder, which cut the CPU time on 8 test masks from 1,058 to 853 ms. Outline Fractal Dimension takes about 21 ms per mask on the CPU for a 151 × 151 footprint.

Notes

  • Compiling the CUDA kernels needs the CUDA headers. On this cluster that meant CUDA_PATH=/hpc/apps/cuda/12.8.0_570.86.10, with its lib64 on LD_LIBRARY_PATH for NVRTC's builtins. CuPy's [ctk] extra provided neither. The aics_workflows kernels need the same setup.
  • The lookup tables come from skimage.measure._marching_cubes_lewiner_luts, a private module. It is imported guardedly: a scikit-image release that moves it breaks only the GPU path, with an error naming the module, and the parity tests would catch any change to the tables.
  • On the GPU, Total Absolute Gaussian Curvature, Avg Shape Index and Avg Curvedness vary by up to 7e-14 between runs of the same code, because CuPy's weighted bincount accumulates with atomic adds. Every other feature and every mesh is bitwise repeatable.

Test plan

At head 3064a43:

  • full suite on CPU (uv run python -m pytest -q): 845 passed, 181 skipped
  • tests/feature tests/test_image_utils.py tests/segmentation with CuPy on an A40: 343 passed, 23 skipped (22 need cellpose or itk, 1 needs two GPUs)
  • tests/feature/test_mesh_gpu.py on a two-GPU node (2× L40S), at 7a5ebb5: 15 passed, none skipped (the marching-cubes device code has not changed since)
  • ruff check ., ruff format --check ., mypy --ignore-missing-imports cubic/
  • CI (the GPU tests skip there)

🤖 Generated with Claude Code

https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

Summary by Sourcery

Enable device-preserving GPU mesh extraction and feature measurement while aligning fractal-dimension and Gaussian-filter results across CPU and GPU paths.

New Features:

  • Add GPU-native mesh feature extraction for CuPy label images and masks, including CUDA Lewiner marching cubes and ArrayMesh measurements.
  • Support GPU-compatible fractal-dimension estimation based on multiscale blurred surface areas.
  • Provide a shared Gaussian filter whose GPU results match SciPy rounding.

Bug Fixes:

  • Correct fractal-dimension estimation so smooth surfaces measure near 2 and fine-scale roughness increases the result.
  • Keep GPU mesh generation on the input device and preserve CPU/GPU feature agreement.

Enhancements:

  • Delegate unsupported ArrayMesh operations such as convex hulls and bounding primitives to host trimesh while computing core geometry on the array device.
  • Update mesh feature APIs to distinguish mask-based fractal dimension from single-mesh features and enforce GPU marching-cubes argument limitations.

Build:

  • Remove the fast-simplification dependency from the mesh extras.

Documentation:

  • Document GPU mesh extraction, ArrayMesh support, curvature-scale measurements, and the revised fractal-dimension definition.

Tests:

  • Add CPU/GPU parity coverage for marching cubes, ArrayMesh measurements, mesh feature extraction, fractal dimension, device placement, and Gaussian filtering.

Chores:

  • Centralize CUDA kernel compilation and launch configuration for reuse across GPU modules.

alxndrkalinin and others added 5 commits October 30, 2026 08:32
aics_workflows kept a private Gaussian that runs each pass on a float64
copy on the GPU, so that cupyx rounds like SciPy, which accumulates
float32 input in float64. The mesh curvature blur needs the same
bitwise parity with a different mode and truncation, so the filter is
now image_utils.gaussian_filter_like_scipy(image, sigma, mode,
truncate), and _gaussian_nearest calls it with mode="nearest",
truncate=3. Measured bitwise equal to scipy.ndimage.gaussian_filter for
reflect/truncate=4 at sigmas (1.5,4,4), (2,7.39,7.39) and (2,2,2), where
plain cupyx differs by up to 1.8e-7.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
cuCIM has no marching cubes, so the GPU mesh path needs its own. This
ports scikit-image's Cython implementation to CUDA kernels that run on
scikit-image's own lookup tables and the same face and interior
ambiguity tests, in three passes: classify each cube and mark the edges
and cube centres it uses; number them by prefix sum and compute the
vertices; write each cube's triangles. An edge vertex depends only on
its edge's two corner values (the reference's interpolation sums the
same two terms in whichever cube creates it), so with float64 corner
arithmetic in the reference's operation order and --fmad=false the
vertices round to skimage's float32 values.

Measured identical to skimage up to vertex and face order, including
orientation and output dtype: binary noise 40^3 (all 14 Lewiner cases,
99,337 vertices / 232,154 faces), continuous noise 64^3 (401,937 /
878,906), blurred noise, anisotropic balls, and volumes with exact level
hits with and without degenerate-face removal. 64^3: 88 ms on an A40
shared with another job, against 1.7 s for skimage.

allow_degenerate=False merges coincident vertices by a lexicographic
sort; cp.unique(axis=0) took hours on a few thousand vertices.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
The mesh feature registry reads trimesh attributes. ArrayMesh provides
the ones it uses (face areas and normals, mass properties and inertia,
Euler number, face adjacency with dihedral angles and convexity,
integral mean curvature, face angles and angle defects), computed with
trimesh's own formulas on NumPy or CuPy arrays, so the features run on
whichever device holds the mesh. Anything else (convex hull, bounding
box, cylinder and sphere, QEM decimation) goes to a trimesh.Trimesh
built on the host on first use. A mesh with negative enclosed volume is
flipped, as trimesh.repair.fix_normals does for consistent winding.

On NumPy arrays every feature matches trimesh to 1.7e-16 relative or
better on a ball, a hollow ball and a 58k-vertex VPA nucleus.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
extract_features, extract_surface_features and mask2mesh now keep a
CuPy label image or mask on the GPU, following cubic's device-agnostic
API: each label's crop is meshed with the CUDA marching cubes and
measured as an ArrayMesh, while labels and bounding boxes come from a
host copy. The curvature blur uses gaussian_filter_like_scipy, so the
smoothed mesh is identical on both devices. mask2mesh returns an
ArrayMesh for CuPy input (a trimesh.Trimesh for NumPy), and accepts
only spacing among marching_cubes_kwargs on the GPU.

Features agree with the CPU path to rtol 1e-9 on a three-label image.
On VPA nuclei (2 nuclei, ~330k voxels each, A40 shared with another
job): the GPU-native features take 0.16 s/nucleus against 2.47 s on
CPU (15x); with the hull and box features, computed by trimesh on the
host, 0.63 s against 4.26 s (6.7x); with the QEM fractal dimension, also
on the host, 1.90 s against 4.14 s (2.2x).

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
@sourcery-ai

sourcery-ai Bot commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Reviewer's Guide

Data structures

Add ArrayMesh, the NumPy/CuPy-backed mesh structure that merges vertices and supplies trimesh-compatible geometric properties.

  • cubic/feature/_array_mesh.py L1-339

API

Expose GPU-capable mesh extraction and distinguish default, optional, and mask-based feature interfaces.

  • cubic/feature/mesh.py L54-77, L83-119, L251-285 (+13 small edits)

Uses of the API

Reuse the shared Gaussian filter and CUDA helpers in the AICS segmentation workflow.

  • cubic/segmentation/aics_workflows.py L34-42 (+4 small edits)

Implementation

Port Lewiner marching cubes to CUDA and construct meshes and vertices on the input array's device.

  • cubic/feature/_marching_cubes_cuda.py L1-625

Implement device-aware mesh dispatch, multiscale fractal measurements, and mask-to-mesh construction behind the public mesh APIs.

  • cubic/feature/mesh.py L287-422, L435-540, L793-935 (+10 small edits)

Provide a SciPy-rounding Gaussian filter for CPU and GPU arrays.

  • cubic/image_utils.py L989-1018

Centralize reusable CUDA kernel compilation and launch helpers.

  • cubic/cuda.py L6, L237-259

Configuration

Remove fast-simplification from the mesh extra now that fractal dimension no longer depends on QEM decimation.

  • pyproject.toml L48 (removed lines)

Documentation

Document the GPU mesh path, ArrayMesh, and the updated mesh-feature behavior.

  • AGENTS.md L71-73

Tests

Cover revised mesh features, fractal scales, and outline measurements on the CPU path.

  • tests/feature/test_mesh.py L130-184, L521-1107, L1144-1156 (+6 small edits)

Test CUDA marching-cubes parity, ArrayMesh compatibility, GPU dispatch, and CPU/GPU feature agreement.

  • tests/feature/test_mesh_gpu.py L1-376

Check that the shared Gaussian filter preserves complex GPU input.

  • tests/test_image_utils.py L36, L716-731

Lock files and vendored code

Update the dependency lockfile for the mesh-extra dependency change.

  • uv.lock L2-1040 (5 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

Unresolved correctness issues can cause cross-device CUDA launch failures, inconsistent mesh state, inflated curvature metrics, and loss of imaginary data during GPU filtering.

4 open issues
What changed in this PR

Extends cubic’s mesh feature extraction to GPU inputs, building on the earlier mesh and curvature work while preserving the CPU path.

Changes:

  • Adds CUDA Lewiner marching cubes and device-native ArrayMesh measurements, with host fallbacks for selected operations.
  • Routes CuPy masks through GPU meshing and shares SciPy-compatible Gaussian filtering across curvature and segmentation workflows.
  • Adds CPU/GPU parity tests and updates project documentation.
File Description
tests/​feature/​test_mesh_gpu.py Tests marching-cubes and mesh-feature parity across devices.
cubic/​segmentation/​aics_workflows.py Reuses the shared Gaussian helper.
cubic/​image_utils.py Adds Gaussian filtering with SciPy-compatible GPU rounding.
cubic/​feature/​mesh.py Dispatches CuPy inputs to GPU meshing and measurements.
cubic/​feature/​_marching_cubes_cuda.py Implements CUDA Lewiner marching cubes.
cubic/​feature/​_array_mesh.py Provides device-native mesh properties and host fallbacks.
AGENTS.md Documents GPU mesh support and the new modules.

Review effort: Balanced

Comment thread cubic/feature/_array_mesh.py Resolved
Comment thread cubic/feature/_array_mesh.py Resolved
Comment thread cubic/feature/_marching_cubes_cuda.py Resolved
Comment thread cubic/image_utils.py Resolved
alxndrkalinin and others added 20 commits November 7, 2026 09:10
The decimation estimator returned 2.0001 +- 0.0001 on every nucleus:
QEM decimation of a smooth (blurred) mesh preserves its area, so the
slope was zero. It also ran QEM on the host for GPU input.

Fractal Dimension is now 2 - slope of log surface area against log
blur scale, from the finest voxel spacing to curvature_sigma, divided
by the same areas for the mask's smooth twin (its blur at
curvature_sigma). The twin shares the coarse shape and voxel grid, so
the shrinking of curved surfaces under blur cancels: smooth ellipsoids
of nucleus size measure 2.000 +- 0.005, against 2.05-2.20 for the area
of the blurred mask alone, and band-limited roughness raises D
monotonically. It describes the detail finer than the scale the
curvature features use.

Blur, marching cubes and area all run on the mask's device, so the
feature no longer builds a host trimesh (guarded by a GPU test), and
fast-simplification is dropped from the mesh extra. The feature needs
the mask, so extract_mesh_features rejects it and leaves it out of
its defaults.

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

A sheet a few planes thick survives the blur at curvature_sigma, but its
thinner smooth twin vanishes when blurred again, and Fractal Dimension
returned NaN silently while every other NaN path warns. One of 781 PC3
nuclei on the CPSAM v2 masks (a 4-plane, 1.3 um sheet) hit it.

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

Marching cubes with degenerate faces removed leaves coincident and
unreferenced vertices after an exact level hit. The CPU path's
trimesh.Trimesh (process=True) merges them, but ArrayMesh kept them, so
each unreferenced vertex added a 2 pi angle defect (0.5 to total |K|)
and each duplicate split defects and edges at a seam: on a level-hit
test mesh total |K| was 480.9 against trimesh's 496.1.

ArrayMesh now drops unreferenced vertices and merges those equal to
trimesh's 8-decimal key (vertices * 1e8, rounded, as merge_vertices
does) with a lexsort on the mesh's device; cupy.unique(axis=0) took
seconds for a few thousand rows. Meshes without such vertices are left
untouched. The fractal-dimension areas use a new face_areas helper,
which needs no merging.

Reported by Copilot on #63.

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

ArrayMesh forwards attributes it does not compute to a host
trimesh.Trimesh copy, including in-place mutators. So
mask2mesh(cupy_mask).apply_scale(2) scaled only the host copy: the
device vertices and the cached volume and area stayed as they were,
while delegated bounding primitives described the scaled mesh.

Delegated methods now run under a check of trimesh's data hash (which
covers vertices and faces, not caches). A call that changes it raises
TypeError and drops the host copy, which is rebuilt from the device
arrays on next use; read-only methods such as copy() work as before.
A hash check covers every mutator without a list to keep in sync with
trimesh.

Reported by Copilot on #63.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
The kernels and lookup tables are compiled per device (_kernels(id)),
but the contiguous-float32 copy, the scratch arrays and the launches
ran on whichever device was current. With the volume on GPU 1 and GPU 0
current, a float64 volume was copied to GPU 0 and meshed there (the
mesh came back on GPU 0); a contiguous float32 volume would launch GPU
1's kernels with GPU 0's scratch arrays.

marching_cubes now enters the input array's device for the whole call.
Tested on a two-GPU node for float32 and float64 input; the unfixed
body returned the float64 mesh on device 0.

Reported by Copilot on #63.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
The GPU branch cast each pass to float64, which drops the imaginary
part of a complex image, while SciPy on the CPU filters both parts. It
now works in np.result_type(image.dtype, float64): float64 for real
input as before, complex128 for complex input. Real-valued results are
unchanged.

Reported by Copilot on #63.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
_edge_groups, face_adjacency and face_adjacency_unshared looked up the
array module for calls that NumPy already dispatches to CuPy:
ones_like, flatnonzero, stack, diff with append=, and take_along_axis
in place of arange fancy indexing. Each was checked on CuPy input to
return a CuPy array with NumPy's dtype and bytes. mesh.py moves its
host vertex offsets with cubic.cuda.to_same_device instead of
get_array_module(verts).asarray; the offsets stay float64.

On 16 masks and spacings, every feature and mask2mesh mesh is
bitwise unchanged on the CPU and the GPU, apart from the GPU's
run-to-run noise (below 5e-14) in the three curvature features that
CuPy's weighted bincount sums with atomic adds.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5
_edge_groups stored the sorted edges in self._edges_sorted, face_adjacency
assigned self.face_adjacency_edges as a side effect, and the
face_adjacency_edges property read it back out of __dict__, so each
property depended on another one having run first. _edge_groups now
returns the edges with their grouping, and one cached _face_adjacency
returns (pairs, shared edges), which face_adjacency and
face_adjacency_edges index.

Features and meshes are bitwise unchanged on the CPU and the GPU (the
GPU's three weighted-bincount curvature features aside, which vary
below 5e-14 between runs).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5
_merge_vertices, ArrayMesh._edge_groups and the CUDA marching cubes'
_remove_degenerate_faces each sorted rows and marked the first row of
each run of equal rows. _group_rows(keys) -> (order, is_new) in
_array_mesh.py now does it with np. calls for all three. The two
modules gave different figures for why unique(axis=0) is avoided; the
helper keeps the measured one: cupy.unique(axis=0) took about 7 s per
1,000 rows, against 1.5 ms per 300,000 rows for the lexsort.

_edge_groups now lexsorts the (vertex, vertex) rows instead of
argsorting a combined scalar key. Equal edges still form the same runs
and the pairs are sorted per row afterwards, so the adjacency is
unchanged; on a 48,716-face mesh the grouping takes 0.60 ms instead of
0.45 ms on the GPU. Marching-cubes faces stay int32.

Features and meshes are bitwise unchanged on the CPU and the GPU (the
GPU's three weighted-bincount curvature features aside, which vary
below 5e-14 between runs).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5
_marching_cubes_on_device raises for any volume with an axis shorter
than 2, so by the time it counts vertices and faces there are at least
8 grid points and one cube, and the cumulative sums it reads the last
element of are never empty. The "if n", "if ncubes" fallbacks could not
be taken; an all-background volume still raises "No surface found".

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5
The CUDA marching cubes compiled its kernels and sized its grids with
copies of _cuda_functions and _launch_config from aics_workflows.py:
the same RawModule(..., options=("--fmad=false",)) per device and the
same grid-stride formula. Both helpers now live in cubic/cuda.py under
the same names, and aics_workflows.py imports them, so its kernels
resolve them as before. _launch_config keeps the marching-cubes
version's floor of one block, which only changes a zero-size launch.
_kernels still caches each device's lookup-table upload. cubic/cuda.py
imports nothing from cubic, so there is no import cycle.

Mesh features and meshes are bitwise unchanged on the CPU and the GPU
(the GPU's three weighted-bincount curvature features aside, which
vary below 5e-14 between runs); the aics workflow GPU tests pass.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5
mask2mesh had its own device branch: on the GPU it checked the
keywords and rebuilt skimage's default level from the volume's range,
on the CPU it called skimage directly, around _marching_cubes, which
exists to own that choice. _marching_cubes now takes skimage's call
shape (level=None for the midpoint, keyword-only spacing and
allow_degenerate, any other keyword passed to skimage on the CPU and
refused with the same ValueError on the GPU), the CUDA marching_cubes
accepts level=None and takes the midpoint from the min and max it
already reads for its range check, and mask2mesh calls the seam once.

A NumPy bool mask still goes to skimage unchanged. On the GPU,
marching_cubes_kwargs now also accept level and allow_degenerate,
which the port supports; step_size and the rest still raise.

Features and meshes are bitwise unchanged on the CPU and the GPU (the
GPU's three weighted-bincount curvature features aside, which vary
below 5e-14 between runs).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5
extract_surface_features blurred the mask at sigma in
_smooth_mask2mesh, _fractal_dimension blurred it again to make the
smooth twin and a third time as its last scale (geomspace returns sigma
itself as the last scale), and marching cubes ran twice on that same
volume. With features=["Fractal Dimension"] the smoothed mesh was built
only to check that the mask survives the blur.

extract_surface_features now blurs at sigma and takes its 0.5 level set
once. The smoothed mesh is built from that level set only when a
smoothed curvature feature is requested; _fractal_dimension thresholds
the same blur for the twin and takes the mask's area at the last scale
from the same (verts, faces), computed as before. _level_set folds the
"max <= 0.5, else marching cubes at 0.5" that _smooth_mask2mesh and
_level_set_area each repeated. The raw mesh and its validation, the
vanishing warning and NaN result, and mask2mesh(mask, sigma=...) are
unchanged.

Per extract_surface_features call (measured by patching counters, the
raw mesh included): all features or Fractal Dimension alone, 12 blurs
and 12 marching cubes before, 10 and 11 after; the curvature features
alone, 1 and 2 before and after.

Features, warnings and meshes are bitwise unchanged on the CPU and the
GPU (the GPU's three weighted-bincount curvature features aside, which
vary below 5e-14 between runs). The smoothing test patched
_smooth_mask2mesh, which extract_surface_features no longer calls, so
it now patches the blur itself; a new test checks that Fractal
Dimension alone builds no smoothed mesh, and fails when the mesh is
always built.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5
The smooth twin, the mask's blur at curvature_sigma thresholded at 0.5,
kept that blur's padding and was padded again at every scale; on the
test masks below, its five blurred volumes held 2.1-2.4x the voxels
they hold cropped (3.1-3.5x for the smallest balls). Outside the mask's
frame every mask voxel lies to one side along some axis, so the blur
there is at most the kernel's weight beyond its centre, below 0.5: the
twin fits in the mask's own frame. _smooth_twin now crops it there
before the per-scale blurs. A new test checks that a box and a ball
touching their frame on every face lose no twin voxels to the crop,
and that the box's twin reaches every face.

The twin's vertices move by whole voxels, so float32 rounding moves
its areas slightly: over 12 finite cases (6 masks, at isotropic and
(0.29, 0.108, 0.108) spacing) Fractal Dimension changes by at most
3.95e-7 on the CPU and on the GPU. Every other feature is unchanged.

Fractal Dimension alone, per mask, median of 5 runs after a warm-up:
- CPU, (0.29, 0.108, 0.108), 58k-127k voxels: 482-772 -> 374-516 ms
- CPU, isotropic, 3k-7k voxels: 56-73 -> 42-53 ms
- GPU, all of them: 31-45 -> 28-33 ms

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5
test_gpu_marching_cubes_runs_on_the_input_device repeated the
canonicalize-and-compare block of test_gpu_marching_cubes_matches_skimage;
both now call _assert_same_mesh. test_array_mesh_matches_trimesh built
mesh_feature_list() minus "Fractal Dimension" by hand, which is what
extract_mesh_features computes by default, so it passes no list.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5
skimage takes level=None as 0.5 * (volume.min() + volume.max()) on
float32 scalars, so the sum rounds to float32 before it is halved. The
CUDA port added the extremes as Python floats, which moves the level
whenever that sum is not a float32: on a 20^3 uniform volume in
[0.1, 3.0], 1,607 of 35,079 vertex coordinates came out an ulp away
from skimage's. The sum is now rounded to float32 first, and the new
test meshes that volume with level=None on both devices and compares
the meshes bit for bit; it fails without the change. A mask's level
(0.5) is unchanged.

Features and meshes are bitwise unchanged on the CPU and the GPU (the
GPU's three weighted-bincount curvature features aside, which vary
below 1e-13 between runs).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5
skimage raises ValueError("`spacing` must consist of three floats.")
for any other length. The CUDA port multiplied the vertices by it, so
spacing=(0.5,) silently scaled every axis and a two-value spacing
failed with a broadcast error after the whole mesh was computed. The
port now raises skimage's error before any GPU work, and a new test
checks both lengths on the direct call and through mask2mesh against
skimage's own message; it fails without the change.

Features and meshes are bitwise unchanged on the CPU and the GPU (the
GPU's three weighted-bincount curvature features aside, which vary
below 1e-13 between runs).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5
…mesh

ArrayMesh.__getattr__ delegated every public name to the host trimesh.
Python also calls __getattr__ when one of ArrayMesh's own properties
raises AttributeError, so such a failure was answered by trimesh on the
host, silently and off the device. A name defined on the class now
raises AttributeError saying the ArrayMesh attribute itself failed;
only names ArrayMesh does not define are delegated.

Features and meshes are bitwise unchanged on the CPU and the GPU (the
GPU's three weighted-bincount curvature features aside, which vary
below 1e-13 between runs).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5
_fractal_dimension returned NaN only for curvature_sigma at or below
the finest voxel spacing. Just above it, the five scales span a small
log range and the slope fit rests on small area differences. It now
warns, and still returns the value, when curvature_sigma is less than
twice the finest spacing: 2 is the default range on isotropic data and
the smallest one validated. The default never warns, on isotropic data
or at (0.29, 0.108, 0.108); a new test checks both and that a ratio of
1.5 warns. The curvature_sigma docstring of extract_surface_features
gives the range.

Fractal Dimension of 12 smooth ellipsoids (semi-axes 7-17 voxels,
random orientations, isotropic spacing, CPU) by curvature_sigma /
spacing:

  ratio   mean     SD      min      max
  1.05    1.9998   0.0007  1.9990   2.0014
  1.1     2.0000   0.0007  1.9991   2.0016
  1.25    1.9997   0.0007  1.9984   2.0009
  1.5     1.9986   0.0007  1.9977   1.9995
  2       1.9947   0.0012  1.9930   1.9969
  3       1.9741   0.0061  1.9652   1.9846

On these smooth bodies the spread below a ratio of 2 is no larger than
at 2, so the threshold rests on 2 being the smallest validated range,
not on a measured rise in spread.

Features, warnings and meshes are bitwise unchanged on the CPU and the
GPU (the GPU's three weighted-bincount curvature features aside, which
vary below 1e-13 between runs).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5
_marching_cubes_cuda.py imported skimage.measure._marching_cubes_lewiner_luts
and _marching_cubes_lewiner._to_array at module top, and mesh.py imports
that module unconditionally, so a scikit-image release that moved either
private name would break import cubic.feature.mesh for CPU users too.
The imports stay at the top but fall back to None, and marching_cubes
raises an ImportError naming the missing module before any CuPy call.
A new test patches both names to None and checks that the CPU path of
mask2mesh still meshes and that the GPU entry point raises that error;
it runs without a GPU.

Features and meshes are bitwise unchanged on the CPU and the GPU (the
GPU's three weighted-bincount curvature features aside, which vary
below 1e-13 between runs).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5
alxndrkalinin and others added 4 commits November 10, 2026 17:46
…scupy

_kernels copied the lookup tables to the device with cp.asarray inside
`with cp.cuda.Device(device_id)`. ascupy is cp.asarray, so the tables
still land on the device entered there, now through the cubic.cuda
helper that AGENTS.md asks for.

The isinstance(volume, cp.ndarray) device choice in marching_cubes
stays: get_device also returns "GPU" for a CUDA torch tensor, whose
.device is a torch.device rather than a CuPy device to enter.

Features and meshes are bitwise unchanged on the CPU and the GPU (the
GPU's three weighted-bincount curvature features aside, which vary
below 1e-13 between runs).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5
ArrayMesh.to_trimesh imported trimesh inside the method, so a missing
trimesh surfaced as a bare ModuleNotFoundError on first delegation.
The module now imports it at the top under the same guard as mesh.py,
without a second warning, and to_trimesh raises mesh.py's
RuntimeError ("trimesh is required for mesh operations. Install with
'cubic[mesh]'") when it is missing.

Features and meshes are bitwise unchanged on the CPU and the GPU (the
GPU's three weighted-bincount curvature features aside, which vary
below 1e-13 between runs).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5
- mesh_feature_list said its features are extracted from a trimesh
  object; Fractal Dimension is measured on the mask. It now describes
  the surface features of a label that extract_features and
  extract_surface_features return.
- The CUDA marching_cubes and its module said the mesh matches
  skimage's up to vertex and face order. With allow_degenerate=False
  it merges every coincident vertex, where skimage merges only those of
  degenerate faces, and keeps vertices used only by the dropped faces,
  which ArrayMesh drops. Both docstrings now say so; behaviour is
  unchanged.
- test_mask2mesh_on_gpu said only spacing is accepted on the GPU;
  level and allow_degenerate are too since mask2mesh goes through
  _marching_cubes.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5
e1d3e69 warned when curvature_sigma was under twice the finest voxel
spacing, on the argument that a fit over a short log range is
ill-conditioned. The measurement made for that commit does not show it:
over 12 smooth ellipsoids (semi-axes 7-17 voxels, isotropic spacing) the
SD of Fractal Dimension is 0.0007 at ratios 1.05, 1.1, 1.25 and 1.5,
against 0.0012 at 2 and 0.0061 at 3. The area ratio to the smooth twin
carries too little jitter for the short range to amplify, so the warning
would flag a valid setting without evidence of a problem. The NaN and
warning for a curvature_sigma at or below the finest spacing stay, and
the curvature_sigma docstring keeps that rule.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5
@alxndrkalinin

alxndrkalinin commented Nov 11, 2026 •

Copy link
Copy Markdown
Owner Author

Changes since Copilot's review of bc8a991, each with the commit it was addressed in. Copilot has not re-reviewed them: a re-request through the API did not register. They were reviewed locally (a quality pass and a correctness pass), and CI passes at 7a5ebb5.

Fractal Dimension re-estimated on CPU and GPU

  • Addressed in 50cdcfd: fractal dimension from multi-scale area, on CPU or GPU
  • Addressed in 49d9b33: warn when fractal dimension is NaN for a sheet thinner than the blur

Fixes for the four Copilot threads (replied to and resolved there)

  • Fixed in 6016dec: merge equal and unreferenced vertices in ArrayMesh like trimesh
  • Fixed in 3fdbfa8: ArrayMesh raises for delegated methods that change the mesh
  • Fixed in af4ff1c: run CUDA marching cubes on the input volume's device
  • Fixed in 68279ab: keep the imaginary part in gaussian_filter_like_scipy on the GPU

Cleanups; feature values unchanged except where noted

  • Addressed in b8ab999: call np. in ArrayMesh adjacency, not get_array_module
  • Addressed in c64d405: return ArrayMesh adjacency edges, not stash them
  • Addressed in b62da1c: share one lexsort row-grouping helper for meshes
  • Addressed in 994e4d4: drop empty-volume guards in CUDA marching cubes
  • Addressed in 382d730: share the CUDA compile and launch helpers in cubic.cuda
  • Addressed in f8e6d0a: mesh mask2mesh through the _marching_cubes seam
  • Addressed in bfdb146: blur the mask at curvature_sigma once per object
  • Addressed in 367ad00: crop the fractal-dimension twin to the mask's frame (moves Fractal Dimension by at most 3.95e-07)
  • Addressed in 44923ee: share the GPU mesh comparison in the tests and use default features

Correctness fixes from the local review

  • Fixed in e68cc85: round the GPU default level like skimage's
  • Fixed in f3b4321: reject a spacing of other than three values on the GPU
  • Fixed in a74c2a4: keep ArrayMesh's own attribute errors from reaching trimesh
  • Fixed in 9910844: import skimage's private marching-cubes tables guardedly
  • Addressed in 9e7c9ec: upload the marching-cubes tables with cubic.cuda.ascupy
  • Addressed in 0490c85: import trimesh at the top of _array_mesh.py
  • Addressed in 369835d: describe mesh feature sources and GPU degenerate faces in the docstrings
  • Addressed in e1d3e69: warn when Fractal Dimension spans under a factor of 2. Removed again, addressed in 7a5ebb5: the spread over 12 smooth ellipsoids is 0.0007 at range ratios 1.05–1.5 against 0.0012 at the default 2, so the warning had no evidence behind it.

alxndrkalinin and others added 13 commits November 11, 2026 17:04
…ales

extract_features and extract_surface_features take fractal_scales, the
(lowest, highest) blur scale of the fit in units of spacing. The smooth
twin is the mask blurred at the highest scale, and the fit keeps 5
geometric levels. In a sweep over three nucleus datasets, the 3D
estimate was unbiased only while the top scale stayed below half the
object's smallest half-extent, and the useful window started a few
voxels above the resolved edge rather than at one voxel, so the window
needs to be set apart from curvature_sigma.

None keeps the window from the finest voxel spacing to curvature_sigma
and reuses the curvature blur. On 8 test masks (ellipsoids, rough
ellipsoids, slabs, hollow balls; isotropic and (0.29, 0.108, 0.108)
spacing) every default feature is bitwise unchanged on the CPU and on the
GPU, apart from the three curvature-distribution features, which vary by
up to 1.1e-8 between GPU runs of the unchanged code on a flat slab. A
window that is not two finite numbers with 0 < lowest < highest raises
ValueError before any meshing.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5
In a sweep over three nucleus datasets, the 3D fractal dimension was
unbiased on smooth shapes only while the top blur scale stayed at most
half the object's smallest half-extent; above that it reads low, which
makes it unreliable for flat nuclei. extract_surface_features now warns
when the top scale (curvature_sigma, or the highest of fractal_scales)
exceeds a quarter of Min Axis Length, the shortest axis of the
same-inertia ellipsoid of the raw mesh, and still returns the value.

The text is the same for every object, so Python's default filter shows
it once for a label image of many thin objects: three slabs of different
size (Min Axis Length 1.93, 2.31, 2.32 um at a 0.6 um top scale) give
one warning. The axes are computed only when Fractal Dimension is
requested and finite. Default features of the 8 baseline masks are
bitwise unchanged on the CPU, and on the GPU apart from the
run-to-run noise of the three curvature-distribution features.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5
Outline Fractal Dimension runs the Fractal Dimension construction on the
outline of the mask's projection along the first axis: 1 - slope of log
contour length of the blurred footprint, relative to its smooth twin,
against log blur scale. In a sweep over three nucleus datasets, this
form was unbiased at any top scale, reproduced across segmenters as well
as volume, and separated cell states better than the 3D estimate, which
reads low for flat nuclei. Its default window is 4 to 16 times the
coarser in-plane spacing; fractal_scales sets it as for the 3D feature.

The contour length comes from the existing marching cubes, so the
feature runs on the mask's device: the blurred footprint stacked twice
one unit apart meshes to a ribbon whose area is the contour length. On
5 shapes, 3 spacings and 3 blur scales the ribbon matched skimage's
find_contours to 6.2e-8 relative, and an analytic disc to its 2 pi R up
to the polygon's own deficit. On CuPy input it matches the CPU to 1e-9.

Smooth elliptical footprints measure 0.992-0.999, and 4% and 8% outline
noise raise a 0.997 disc to 1.008 and 1.054. A quarter turn about the
first axis changes it by 1e-8, a 45 degree turn by 1.8e-4. It is the one
feature defined on the image axes, which mesh_feature_list now says.
The thin-object warning of Fractal Dimension points to it.

On 20 cpdino-v2 nuclei from each of mboc2021_astr_vpa,
scirep2018_fibroblast and scirep2018_pc3, fractal_scales=(0.4, 1.6)
reproduces the sweep's find_contours values to at most 1.06e-8.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5
At its default 4-to-16-voxel window the outline feature is NaN, with a
warning, for every footprint under about 51 voxels across: a smooth disc
of radius 25 voxels gives NaN, one of 25.5 voxels -0.15, and the value
reaches 0.95 at a radius of 32 voxels and 0.99 at 40. Computed by
default, it would warn for every small object, and it would put a
feature defined on the image axes into a default set that is otherwise
orientation-invariant.

mesh_feature_list() again returns the 22 default names of 7a5ebb5,
ending in Fractal Dimension; mesh_feature_list(optional=True) appends
Outline Fractal Dimension. features=None computes the defaults, an
explicit list may name either kind, and the unknown-name error lists
both. On the 8 baseline masks, extract_surface_features at default
arguments returns exactly the 7a5ebb5 keys and values (bitwise on the
CPU; on the GPU within 1.1e-8 for the three curvature-distribution
features, their run-to-run spread on a flat slab), and extract_features
returns 22 columns.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5
fractal_scales set the window of both fractal features, but their
windows differ in kind: on a flat object a window that suits the outline
(say 0.8-1.6 um) puts the 3D estimate above a quarter of the object's
thickness, where it reads low and warns. fractal_scales now applies to
Fractal Dimension only, and a new keyword, outline_fractal_scales, on
extract_features and extract_surface_features, sets the window of
Outline Fractal Dimension, with the same form and validation; each
error names its keyword. The outline default stays 4 to 16 times the
coarser in-plane spacing.

Changing either window leaves the other feature bitwise unchanged
(tested on a rough cylinder). Default features of the 8 baseline masks
are unchanged: bitwise on the CPU, and on the GPU within the run-to-run
spread of the three curvature-distribution features.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5
_fractal_dimension and _outline_fractal_dimension repeated one estimator:
the smooth twin, the geometric ladder of blur scales, the reuse of the
top scale, the ratio list, the vanishing warning and the fit. Both now
call _blur_ladder_dimension, which takes the N-dimensional mask, its
step, the window, a measure of the 0.5 level (surface area, or contour
length of the stacked ribbon) and the already computed top blur and top
measure, and returns mask.ndim - 1 - slope.

extract_surface_features resolves each feature's (lowest, highest) once,
instead of in three branches for the 3D window and inside the outline
estimator, and reuses the blur and level set at curvature_sigma whenever
the 3D top scale equals it, also for an explicit window. The thin-object
ratio is one constant, used by the condition and the warning text.

Default features of the 8 baseline masks are bitwise unchanged on the
CPU, and on the GPU within the run-to-run spread of the three
curvature-distribution features; Outline Fractal Dimension and Fractal
Dimension over custom windows are bitwise unchanged on 7 flat masks at
three spacings.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5
_padded_blur pads by ceil(3 sigma) + 1 voxels and blurs in reflect
mode, so at the outline's default 16-pixel top scale a 151 x 151
footprint became 249 x 249 for each of its 10 blurs. With tight=True it
pads by one pixel and blurs with zeros beyond it (constant mode). On the
mask's frame and that ring the field is bitwise the same as the wide
blur's (checked on CPU and GPU for a rough disc, a box and a disc that
touch their crop on all four sides, and noise blobs, on (0.108, 0.108),
(0.2, 0.1) and (1, 1) planes at every ladder scale), and the ring stays
below 0.5 (at most 0.4814), so every contour closes inside the array.
Only Outline Fractal Dimension uses it; the 3D blurs keep their padding.

The outline estimator takes 20.9 ms instead of 34.6 ms on that
footprint (median of 7, CPU). Values move by at most 1.7e-8 relative on
7 flat masks, because the float32 contour vertices sit at a different
offset in the array; CPU and GPU agree to 3.7e-16 relative. On 20
cpdino-v2 nuclei per dataset the outline matches the fd_sweep
find_contours values to at most 5.2e-9 (mboc2021_astr_vpa), 9.8e-9
(scirep2018_fibroblast) and 1.1e-8 (scirep2018_pc3). Default features of
the 8 baseline masks are unchanged.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5
mesh_feature_list now derives the default names from _MASK_FEATURES and
_OPTIONAL_FEATURES instead of a third tuple, and _fractal_window checks
0 < lowest < highest < inf in one comparison, which is also false for
NaN and either infinity (the validation test covers NaN in both places,
+inf, -inf, reversed, equal and zero windows).

Each default window is stated once, in the keyword that sets it, and
mesh_feature_list and curvature_sigma point to it; mesh_feature_list
says once that the fractal features are measured on the mask, and its
reflowed paragraph on the axis lengths is joined again. Default features
of the 8 baseline masks are unchanged.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5
…ases

The default count of 22 is now pinned only in the test of the optional
list; the background-label and default-output tests use
len(mesh_feature_list()). The thin-object test checks that its one
warning points to Outline Fractal Dimension, which replaces a separate
test that repeated its slab call to match the text. The rotation test
measures the upright ellipsoid once, outside the loop, and the
default-output test is the one place that checks the outline stays out
of the defaults.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5
extract_features and extract_surface_features are wrapped by
_require_trimesh, which adds a frame, so with stacklevel=2 every warning
raised under them was attributed to that wrapper in cubic/feature/mesh.py
instead of to the code that called the public function. The thin-object
warning, both "vanishes" warnings, the warning for curvature_sigma not
above the finest spacing and the blur-ladder warning now use one
stacklevel constant, plus the frames of the helpers that raise them, so
a direct call to extract_surface_features attributes each to the
caller's line. Against the previous code, the new test fails for all
five warnings and passes with this change.

Through extract_features the caller is its per-label loop, one line
for every label, so the constant thin-object text is still shown once
per label image under the default filter; the docstring says why.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5
extract_surface_features bound the blur, padding and level set at
curvature_sigma inside one branch and read them later under another
(Fractal Dimension's top scale equal to curvature_sigma), correct only
through an invariant held elsewhere in the function. A per-call memo of
the mask's blur, padding and level set at a scale, each computed at
most once, now serves the curvature features at curvature_sigma and
Fractal Dimension's top scale, so the reuse when the two are equal
follows from the memo.

An empty default window (curvature_sigma not above the finest spacing)
is now decided before any blur: it returns NaN with its own warning,
without blurring, and is no longer listed as vanishing when the mask
vanishes at curvature_sigma. The default output and warning texts of
the 8 baseline masks are unchanged, as is the bitwise equality of the
explicit (finest spacing, curvature_sigma) window with the default.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5
_fractal_window accepted b"12" as the window (49.0, 50.0) and a dict
through its keys, and raised ValueError for a scalar or a string, where
_resolve_features raises TypeError for a string. It now raises
TypeError, naming the keyword, unless the window is a sequence or 1D
array of real numbers (so for a scalar, str, bytes, a mapping or
non-numeric elements), and ValueError when the sequence has other than
two values or they are not finite with 0 < lowest < highest. Default
features of the 8 baseline masks are unchanged.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5
The 3D ladder's nine extra blurs and marching-cubes runs per label (4
mask scales, 5 twin scales) padded by ceil(3 sigma / step) + 1 voxels a
side, about 1.9 times the voxels of a 40 x 100 x 100 crop at nucleus
spacing. _blur_ladder_dimension now uses the one-voxel tight padding
for every ladder blur, of both fractal features, so its tight flag is
gone; the top-scale blur, shared with the curvature mesh, keeps the
wide padding.

In 3D the field on the mask's frame and the one-voxel ring is bitwise
the same as the wide blur's, and the ring stays below 0.5 (at most
0.4307), on CPU and GPU, at every ladder scale of the mask and its twin,
for a rough ellipsoid, a box filling its crop, a slab filling the first
axis and a hollow ball, at (0.29, 0.108, 0.108), (0.3, 0.13, 0.13) and
isotropic spacing. Only the float32 vertex offsets change: Fractal
Dimension of the 8 baseline masks moves by at most 1.8e-8 on CPU and
GPU, every other feature is unchanged, and CPU and GPU agree to 2.3e-16
relative. Fractal Dimension of the 8 masks takes 853 ms instead of
1058 ms on the CPU (min of 5 per mask); on the shared GPU 841 and 356 ms
instead of 986 and 567 ms in two runs.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01R9GLau7FwMYTDwZz9aQxb5
@alxndrkalinin

Copy link
Copy Markdown
Owner Author

Changes since 7a5ebb5, each with the commit it was addressed in. Copilot has not reviewed them: a re-request through the API again did not register (2026-11-12). They were reviewed locally (a quality pass and a correctness pass on these commits).

Fractal dimension: settable window, thin-object warning, in-plane variant

  • Addressed in 7da2d9d: fractal_scales sets the (lowest, highest) blur scale of Fractal Dimension; the default is unchanged
  • Addressed in 55ad195: warn, and still return the value, when the top scale exceeds a quarter of the object's Min Axis Length
  • Addressed in 743450a: new feature Outline Fractal Dimension, the same estimator on the outline of the projection along the first axis
  • Addressed in adf00f8: the outline feature is optional, computed only when requested by name; mesh_feature_list(optional=True) lists it
  • Addressed in 4992e77: the outline feature has its own window, outline_fractal_scales

Cleanups; default output unchanged except where noted

  • Addressed in 717a90f: one blur-ladder estimator for both fractal features
  • Addressed in db2d1a0: the outline's 2D blurs pad by one pixel (outline value moves by at most 1.7e-8)
  • Addressed in 988db7e: default feature list derived from the optional tuple; simpler window check; default windows stated once
  • Addressed in 35355ec: tests pin the default feature count once and fold repeated cases

Correctness fixes from the local review

  • Fixed in 03a778b: warnings are attributed to the line that called the public function, not to the decorator's wrapper
  • Addressed in 41a48de: the mask's blur is memoized per scale; an empty default window returns NaN before any blur
  • Fixed in e8741f7: a window that is not a sequence of numbers raises TypeError (bytes and dicts were accepted)
  • Addressed in 3064a43: the 3D ladder's blurs pad by one voxel (Fractal Dimension moves by at most 1.8e-8)

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