Skip to content

feat(segmentation): FBL and NPM1 nucleolar workflows on CPU or GPU - #64

Open
alxndrkalinin wants to merge 54 commits into
mainfrom
feat/aics-nucleolar-workflows
Open

alxndrkalinin wants to merge 54 commits into
mainfrom
feat/aics-nucleolar-workflows

Conversation

@alxndrkalinin

@alxndrkalinin alxndrkalinin commented Oct 31, 2026 •

Copy link
Copy Markdown
Owner

Summary

Ports two Allen Cell Structure Segmenter classic workflows to cubic.segmentation, alongside SEC61B and TOMM20:

  • workflow_fbl: aicssegmentation's Workflow_fbl, the fibrillarin / dense fibrillar component of the nucleolus.
  • workflow_npm1: Workflow_npm1, the nucleophosmin / granular component.

As with the existing workflows, NumPy input stays on the CPU, CuPy input stays on the GPU, and a 2D plane is segmented as a one-plane volume.

How parity is kept.

  • Scalar thresholds (triangle, median, global and per-object Otsu) are computed on the host. Their per-label histograms are binned on the device, exactly as np.histogram bins them.
  • The 2D spot filter is a CUDA kernel that replays SciPy's NI_Correlate1D summation order for symmetric kernels. cupyx sums tap by tap, which rounds near-zero second-derivative values differently.

Tunable parameters. Every workflow constant is a keyword-only argument: normalization bounds, smoothing, spot sigma and cutoff (None skips the step), size limits, NPM1's hole filter and dilation, and a factor on each object's local Otsu level for both workflows (local_otsu_factor; FBL's defaults to None, the reference behaviour). The defaults are the reference's values, so parity holds at the defaults. The classic workflows are meant to be re-tuned per dataset. On the 2018 confocal tiles (immunostained fibrillarin and EtBr):

  • FBL's default spot cutoff marks noise speckle throughout every nucleus.
  • FBL's low-level objects are whole cells, so the per-object Otsu level separates nucleus from cytoplasm rather than nucleoli from nucleoplasm, and the mask covers about half of each nucleus. Scaling that level fixes it.

Settings that outline nucleoli on those tiles, judged on renderings across several physical samples:

  • fibroblasts: FBL smoothing_sigma=2, dot_cutoff=None, local_otsu_factor=2.0; NPM1 the same with factor 2.5;
  • PC3: FBL factor 1.5; NPM1 factor 1.75.

Evidence

Bitwise parity on real data. These are 3D confocal tiles from Kalinin et al. 2018, cast from uint16 to float32. The measurement script lives outside the repo.

tiles voxels differing: CPU vs aicssegmentation voxels differing: GPU vs CPU
24 fibroblast (31–38 × 1024²): 12 anti-fibrillarin through FBL, 12 EtBr through NPM1 0 on 24/24 0 on 24/24
10 PC3 (52–71 × 1024²), FBL and NPM1 0 on 10/10 0 on 10/10

Speed. The GPU takes 0.2–5.8 s per tile (A40), against 22–570 s for the CPU reference.

Two GPU bugs, found on PC3 and fixed. Both are now covered by regression tests.

  • Past 30 labels, cupyx's labeled minimum/maximum switches to a sort that treats label 0 as background. The first object's histogram came out empty, so its threshold was 0 (41b9235). On one tile this flipped 375,291 voxels; with the fix it flips 0.
  • The spot-filter summation order differed from SciPy's, flipping 1 voxel on one tile (b899881).

Test plan

  • tests/segmentation/test_aics_workflows.py: 70 passed and 0 skipped, in the GPU environment with aicssegmentation and itk
  • Full suite on CPU: 797 passed, 180 skipped (GPU and cellpose tests). It ran during the parameter commit, so CI is the check for the final state.
  • ruff and mypy, run per commit by the implementing agent
  • CI

Notes

  • The weights for the spot-filter kernel come from SciPy's private scipy.ndimage._filters._gaussian_kernel1d, which guarantees the same taps as SciPy. A future SciPy may move it; the import would then fail loudly, not silently drift.
  • The scikit-image min_size semantics follow size_filter_inclusive, as in the existing workflows.

🤖 Generated with Claude Code

https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT

Summary by Sourcery

Add bitwise-compatible FBL and NPM1 nucleolar segmentation workflows for NumPy and CuPy inputs.

New Features:

  • Add CPU- and GPU-compatible FBL and NPM1 nucleolar segmentation workflows with configurable normalization, filtering, spot detection, local thresholding, and morphology parameters.
  • Export the new workflows through the segmentation package API and support consistent 2D-plane processing.

Bug Fixes:

  • Ensure per-label histogram thresholds and GPU spot filtering match NumPy, SciPy, and aicssegmentation results across label counts and numerical edge cases.
  • Fix CPU/GPU workflow discrepancies in labeled reductions and dot-filter accumulation order.

Enhancements:

  • Extend shared segmentation utilities with device-aware histogram thresholding, local Otsu masking, median calculation, and parity-preserving Gaussian spot filtering.
  • Update existing workflows to use unified 2D-plane handling.

Documentation:

  • Document the new nucleolar workflows and their CPU/GPU parity characteristics.

Tests:

  • Add comprehensive CPU/GPU, parameterization, 2D-plane, edge-case, regression, and aicssegmentation parity tests for all workflows.

alxndrkalinin and others added 30 commits October 29, 2026 15:03
extract_mesh_features computed all 20 features whatever was asked for.
Mean curvature alone took 15.4 s of a 15.8 s per-label total on a
13k-vertex nucleus, so extract_features(img, ["Volume"]) paid for it on
every label. Each feature is now a registry entry evaluated only when
requested; trimesh caches the shared convex hull and bounding
primitives, so features that share them still compute them once.
Default output is bitwise identical to before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
The test job synced only the dev extra, so trimesh was missing and
tests/feature/test_mesh.py skipped at import on every run: all of its
tests had never executed in CI.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
Min/Med/Max Axis Length were the sorted extents of the axis-aligned
bounding box, so they measured how an object sat in the image rather
than its shape: turning an ellipsoid with axes (12, 16, 48) by 45
degrees about z gave (12, 36, 36). Extent divided by the same box and
fell from 0.52 to 0.31.

The axis lengths are now the full axes of the ellipsoid with the same
principal moments of inertia, regionprops' axis_major_length
convention: (12.02, 15.96, 47.70) at 0 degrees, (12.12, 16.01, 47.66)
at 45. Extent divides by the oriented bounding box volume (0.50-0.55
across 0/30/45 degrees, against pi/6 = 0.524 for an ideal ellipsoid).

Scale (the axis-aligned box diagonal) and Bounding Box Volume are
dropped: both are defined on the image axes, and the oriented box
volume and the axis lengths already carry what they measured.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
Both curvature features were vertex averages of trimesh's curvature
measures integrated over balls of radius 1 in the units of spacing. The
radius did not follow the unit or the resolution: the same voxels with
spacing 0.1 instead of 1 changed them 78x and 11x rather than 100x and
10x, and sampling the same physical sphere twice as finely changed the
Gaussian one 0.46x. The mean curvature measure also looped over
vertices in Python and took 15.4 s of a 15.8 s per-label total for a
13k-vertex nucleus.

They are now surface averages. The mean curvature integrates as half
the sum of edge length times signed dihedral angle (Cohen-Steiner and
Morvan), giving 1/R within 2.2% on voxelized spheres of radius 4-24 and
converging under finer sampling. The Gaussian curvature integrates to
the angle-defect sum, 2 pi times the Euler characteristic exactly, so
it is 4 pi / area for objects without handles or cavities. Both are
vectorized: the full default feature set now takes 0.29 s for the
13k-vertex nucleus and 0.83 s for a 51k-vertex one (was 208 s).

Neither needs mesh.face_adjacency_tree, so rtree leaves the mesh extra
and the per-function dependency guard goes back to a trimesh check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
The formula is Wadell's sphericity for any body, nothing specific to
ellipsoids, and the name suggested otherwise. No caller outside mesh.py
used the old name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
An unknown name raised a bare KeyError only after every feature of the
first label had been computed, and an image without labels accepted it
silently. Names are now checked up front in extract_features and
extract_mesh_features, and the ValueError lists the available ones.

features=[] now yields an (n_labels, 0) matrix instead of silently
falling back to the full default set.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
voxel.extract_features returns (labels, values, column_names) while the
mesh variant returned only (labels, values), so the two could not be
swapped and callers had to rebuild the names themselves. The mesh
variant now returns the same triple.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
cubic.feature did not export the mesh module, so cubic.feature.mesh
raised AttributeError unless the submodule had been imported
explicitly. A module-level __getattr__ now imports it on first access,
the pattern cubic.scipy already uses, so the 0.75-3 s trimesh import
still stays off the import path of the voxel and texture features.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
The inline literal was split across two docstring lines, which breaks
its rendering.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
_avg_mean_curvature rebuilt Trimesh.integral_mean_curvature, a cached
trimesh property that gives the same value (equal to the last bit on a
voxelized ball). trimesh signed the dihedral angles only from 4.6.12 on;
4.6.11 returns 71.8 instead of 2 pi^2 R = 59.2 on a torus. The mesh
extra therefore now requires trimesh>=4.6.12. The mesh tests pass on
both 4.6.12 and the locked 4.11.2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
_TRIMESH_AVAILABLE restated whether the import had bound trimesh, and
was set in three places to stay in sync with it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
trimesh annotates volume, area and mass as numpy float64, which the
numpy 2.0 stubs do not treat as float. With trimesh installed, mypy
rejected the registry's Callable[..., float] values and the sphericity
call. CI's lint job runs without trimesh, so it did not see this. The
registry now returns SupportsFloat, which extract_mesh_features already
converts, and sphericity receives plain floats.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
extract_features and extract_mesh_features each repeated the same
default-then-validate block. _resolve_features now returns the
resolved list, so the default and the error message live in one place.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
_equivalent_ellipsoid_axes described the bounding-box extents it
replaced, with the numbers of one example. That history is in the tests
and the commit log; the docstring now states only what the code does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
Three tests each defined the same extract_surface_features stub, so
adding the features parameter meant three identical edits. A
surface_calls fixture now records each call's mask and spacing. The
ball, ellipsoid and torus builders share _centred_grid instead of three
spellings of a centred meshgrid, one of them with a hardcoded centre.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
The subprocess imported trimesh only to check the last assertion,
3.9 s of the file's 7.6 s. It now checks only that importing
cubic.feature skips trimesh. The in-process call to the package
__getattr__ covers the access path. The test takes 0.11 s.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
With "mesh" in __all__, `from cubic.feature import *` resolved it
through __getattr__ and loaded trimesh, undoing the lazy import, and
warned on hosts without trimesh. Attribute access still loads it on
demand.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
tests/test_plot_utils.py skipped at import in CI for want of
matplotlib, the same gap the mesh extra had. The plot extra is as light,
so the test job installs it too. cellpose stays out because it pulls in
torch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
mesh_feature_list and AGENTS.md called every feature orientation-
invariant. None is defined on the image axes any more, but voxelization
moves all of them a little, and trimesh's oriented box and bounding
cylinder come from approximate minimum searches: Extent spans 0.50-0.55
for one ellipsoid at 0, 30 and 45 degrees. The docs now say so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
mypy types every unknown attribute of a module that defines __getattr__
with that function's return type, so cubic.feature.regionprop type-
checked as a module and failed only at run time. __getattr__ is now
defined only outside type checking, and mypy learns about mesh from a
TYPE_CHECKING import. The typo is now reported ("Module has no
attribute 'regionprop'; maybe 'regionprops'?").

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
The subprocess had no timeout, so an import that hangs in the child,
such as CUDA probing on a node with a broken driver, would stall the
whole pytest run without output.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
extract_features(img, "Volume") iterated the string and reported
Unknown mesh features ['V', 'o', 'l', 'u', 'm', 'e']. A string now
raises a TypeError that names it.

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

As a surface average, the Gaussian curvature is exactly
2 pi * euler_number / area by Gauss-Bonnet, so the column was 4 pi /
Area for every label without holes and carried nothing beyond Area and
one integer. That integer is now its own column: twice the separate
pieces plus cavities, minus twice the handles (2 for a ball, 4 for a
hollow ball or two balls, 0 for a torus). It is free to compute and
does not depend on the spacing unit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
A hollow ball's shells must keep their orientation relative to the
material: the cavity faces inward and counts as concave, so the hollow
ball integrates to the outer ball minus the inner one (82.1), not their
sum (244.2). mask2mesh already does this, because fix_normals runs
without multibody, but nothing tested it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
extract_surface_features built the mesh before the names reached a
check, and extract_mesh_features validated the mesh geometry first. An
unknown name with an open mesh therefore surfaced as "Mesh volume must
be finite and positive" instead of the unknown-feature error, and a
valid mask was meshed for nothing. Both entry points now resolve the
names first, as extract_features already did.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
extract_features(img, []) still meshed and validated every label just
to return an (n_labels, 0) matrix, and could raise a geometry error
instead. It now returns that matrix straight away.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
Adds Total Absolute Gaussian Curvature, Avg Shape Index and Avg
Curvedness, the ShapeTools shape measures, chosen by how well they
separate shape states rather than by parity:

- Any average of Gaussian curvature is fixed by Gauss-Bonnet, so the
  shape signal is in where K is negative. The integral of |K| over 4 pi
  is 1 for every convex body and grows with saddle regions (grooves,
  waists, the necks of lobes); unitless.
- Shape index (Koenderink) and curvedness come from per-vertex principal
  curvatures computed as in LONI ShapeTools (Meyer et al. angle defect
  and edge-based mean curvature over the mixed Voronoi area), averaged
  over the surface by area rather than by vertex, so the result does
  not depend on how the mesher distributes vertices.

Per-vertex curvature on a voxel staircase measures the staircase, so
these are computed on a mesh of the mask blurred at curvature_sigma
(default twice the coarsest spacing, isotropic in physical units), a new
option of extract_features, extract_surface_features and mask2mesh
(sigma). Nothing is blurred unless one of them is requested, and an
object too small to survive the blur gets NaN for them with a warning.

On synthetic nuclei with random size, axes, rotation, sub-voxel position
and boundary noise (3 seeds x 2 noise levels, 30 per class), total |K|
separated folded from smooth ellipsoids with AUC 1.00 and lobulated with
0.82 at rotation CV 0.000, against 0.53-0.64 for every average of K
(including the 2021 ball measure and the ShapeTools vertex mean), and
shape index and curvedness added 0.02-0.06 cross-validated AUC on top of
Solidity, Sphericity and mean curvature. On analytic shapes: ball total
|K| 1.000, torus 2.04 (exact 2), unit change rescales curvedness by 10
and leaves the rest unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
Completes the ShapeTools shape list with the LONI GSA fractal dimension,
whose module sampled the mesh at triangle counts between a minimum and a
maximum: the smoothed mesh is simplified by quadric error metrics to six
face counts from a sixteenth of its own up to all of it, and
D = 2 + 2 * slope of log area against log face count (about 2 for a
smooth surface; 2.005 on a voxelized ball).

On the synthetic nuclei it is weak on its own (AUC 0.59-0.66) and adds
signal only in some settings (+0.05 cross-validated AUC for folded
nuclei at high boundary noise, -0.03 for lobulated at low noise); box
counting on the mask boundary added nothing and was not kept.

Decimation needs fast-simplification, now in the mesh extra (>=0.1.9:
0.1.7 does not import under NumPy 2). Without it the feature raises a
RuntimeError naming the package.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
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
alxndrkalinin and others added 10 commits October 30, 2026 08:33
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
…r workflows

Shared primitives for the aicssegmentation FBL and NPM1 ports, running on
NumPy or CuPy input with reference-identical rounding:

- _label_histograms bins each label as np.histogram(values, 256) does
  (NumPy's float32 linspace edges, its float32 bin estimate and the
  one-bin edge correction), voxel-wise on the device; Otsu (through
  skimage's hist= path) and the triangle threshold (skimage's code after
  its histogram call) then run on the host per label.
- _median reproduces np.percentile(x, 50) from the middle order
  statistics of a device sort.
- _greater and _local_threshold_mask compare against host scalars with
  NumPy's promotion, so float64 thresholds compare in float64 on GPU too.
- dot_slice_by_slice ports seg_dot.dot_slice_by_slice: per-plane
  gaussian_laplace as 1D passes, float64 on GPU, stored in float32 after
  each pass as SciPy does.
- _low_level_mask: the (triangle + median) / 2 threshold with the
  700-voxel size filter.

Host extremes use ufunc.at; SciPy's labeled minimum/maximum argsorts the
whole image and took 70 s of 138 s on a 31x1024x1024 tile.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
workflow_fbl and workflow_npm1 port aicssegmentation's Workflow_fbl and
Workflow_npm1 with their fixed parameters (rescale_ratio=-1), returning a
boolean mask on the input's device; a 2D plane is segmented as a
one-plane volume. FBL thresholds each low-level object at its own Otsu
level and merges 2D spot detections; NPM1 dilates the low level by
ball(2), keeps objects whose Otsu level beats 0.333 x the global Otsu,
adds bright spots inside the low level and cuts dark spots as holes.

On 24 fibroblast tiles (31-38 x 1024 x 1024, slides 157-160; 12
anti-fibrillarin tiles through FBL, 12 EtBr through NPM1) the CPU masks
differed from aicssegmentation's by 0 voxels and the GPU masks from the
CPU's by 0 voxels. Per tile: reference 23-97 s, CPU 22-125 s, GPU
0.23-1.70 s (single-CPU host, A40 shared with another process).

The tests add synthetic nucleoli that reach every branch, and extend the
GPU-vs-CPU, aicssegmentation, plane-mode and dimensionality tests.

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

_group_extremes passed 0-based groups to cupyx's labeled minimum and
maximum. Past 30 labels cupyx switches from a per-label loop to a lexsort
that reads extremes at the starts of labels 1..max, so label 0's
minimum and maximum stayed at 0. The first object then had an empty
histogram and a threshold of 0, so every voxel in it passed FBL's local
Otsu step. On a 34-object PC3 tile (171 c1_g004, 52x1024x1024) the GPU
mask differed from the CPU mask in 375291 voxels; with 1-based labels it
differs in 0, and every intermediate matches.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
dot_slice_by_slice ran cupyx's gaussian_filter1d on a float64 copy.
That accumulates in float64 like SciPy but tap by tap, while SciPy's
NI_Correlate1D sums a symmetric kernel as centre * w0 plus
(left + right) * w_k from the outermost pair inwards. Where a
second-derivative pass cancels to near zero, the two orders round to
different float32 values: 3 and 6 voxels in the two order-2 passes of a
52x1024x1024 PC3 tile, and 1 voxel of the final response.

A CUDA kernel now replays SciPy's loop with SciPy's own reversed
weights, for float32 and float64 input, in reflect mode. The response
on that tile and on 16x256x256 uniform noise (seed 0, sigma 2; 1 voxel
differed before) is bitwise SciPy's.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
The Allen Cell Segmenter workflows are meant to be re-tuned per dataset,
and on the 2018 fibroblast/PC3 confocal tiles the defaults mark noise
speckle (FBL) and EtBr-bright cytoplasm (NPM1). workflow_fbl and
workflow_npm1 now take keyword-only parameters for their constants:
normalization bounds, Gaussian sigma, spot-filter sigma(s) and cutoff
(None skips the step), low-level and final minimum sizes, and for NPM1
the hole sigmas and cutoff, dilation radius (0 skips it), local-cutoff
factor and local Otsu factor. The defaults are the reference's values
and its expressions, so the aicssegmentation parity tests are unchanged.

Tests check that disabling or loosening each step changes the mask in
the documented direction, and that GPU equals CPU at non-default values.

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 31, 2026 •

Copy link
Copy Markdown
Contributor

Reviewer's Guide

API

Export the new FBL and NPM1 workflows as public segmentation entry points alongside the existing workflows.

  • cubic/segmentation/__init__.py L13-18, L35-36

Add configurable FBL and NPM1 workflow interfaces, including two-dimensional plane handling and device-preserving boolean masks.

  • cubic/segmentation/aics_workflows.py L1226-1407

Implementation

Implement the shared label histogram, threshold promotion, median, and local-threshold primitives that underpin CPU/GPU parity.

  • cubic/segmentation/aics_workflows.py L728-1117, L1132-1139

Adapt existing SEC61B and TOMM20 workflows to add a plane axis in place and restore the original plane shape on return.

  • cubic/segmentation/aics_workflows.py L1220-1225 (+3 small edits)

Import the histogram, morphology, Gaussian-kernel, and device helpers required by the new workflow implementation.

  • cubic/segmentation/aics_workflows.py L38-44, L50

Documentation

Document the nucleolar workflow primitives, CPU/GPU parity evidence, and the updated plane-handling behavior.

  • AGENTS.md L51
  • cubic/segmentation/aics_workflows.py L3-21

Tests

Add primitive-level coverage for histograms, thresholds, median behavior, CUDA LoG parity, and edge cases.

  • tests/segmentation/test_aics_workflows.py L381-559

Extend workflow tests to cover CPU/GPU parity, plane behavior, parameter effects, degenerate labels, reference parity, and dimensionality validation.

  • tests/segmentation/test_aics_workflows.py L677-709, L725-842, L849-876 (+5 small edits)

Add synthetic nucleolar image helpers and shared test setup for exercising workflow branches and references.

  • tests/segmentation/test_aics_workflows.py L9-38, L73-123

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 October 31, 2026 14:30
On the 2018 confocal tiles FBL's low-level objects span whole cells, so
each object's Otsu level separates nucleus from cytoplasm rather than
nucleoli from nucleoplasm, and the mask covers ~50% of every nucleus
even without the spot step. local_otsu_factor scales each object's Otsu
level, as NPM1's 0.98 factor does; None (default) keeps the reference.
With sigma 2, no spots and a factor of 2 (fibroblast) or 1.5 (PC3) the
mask outlines the nucleolar clusters.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
main holds #61-#63, #66 and #68 squashed. This branch carried an older
feat/mesh-gpu, so every file outside its own four takes main's version,
and its own changes to AGENTS.md, cubic/segmentation/__init__.py,
aics_workflows.py and their tests are applied on top. In
aics_workflows.py, main moved _cuda_functions and _launch_config to
cubic.cuda; the import keeps main's list and adds to_same_device, which
this branch uses.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
@alxndrkalinin
alxndrkalinin changed the base branch from feat/mesh-gpu to main November 25, 2026 06:29
@alxndrkalinin
alxndrkalinin marked this pull request as ready for review November 26, 2026 07:13
@sourcery-ai

sourcery-ai Bot commented Nov 26, 2026

Copy link
Copy Markdown
Contributor

Sorry @alxndrkalinin, you've used your own review budget of 250,000 diff characters for the last 7 days.

You can request another review in 17 hours and 3 minutes by commenting @sourcery-ai review. Upgrade to get a review now.

alxndrkalinin and others added 9 commits November 25, 2026 23:55
Multiplying by 1.0 is exact, so the None sentinel only added a branch
and a union type; NPM1 already takes a plain float.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
The 2D branch of each workflow re-forwarded every keyword, so a new
parameter missed there would silently fall back to its default.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
Drops the None accumulator and the unused truncate parameter of the
GPU 1D Gaussian (always 4.0). The addition order is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
The triangle and global Otsu thresholds were each computed from their
own, identical whole-image histogram.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
The float64 copy of the volume was redundant: comparing with the
float64 table promotes exactly.

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

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

@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.

Sourcery assessment

Approved.

alxndrkalinin and others added 3 commits November 26, 2026 00:07
With no labeled voxels, or only constant labels, the cupyx labeled
min/max and cupy.bincount raised on empty input, so FBL and NPM1
crashed on GPU where the CPU path returned a mask. Return the empty
extremes and zero histograms before reducing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011hEQ1TZJUbmhYKcC14RYHT
np.partition returned a finite middle value for an image holding NaN,
while the CPU np.percentile returns NaN, so the two devices thresholded
differently.

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