Skip to content

Per-direction sampling floor, and split raw counts before resampling - #56

Merged
alxndrkalinin merged 16 commits into
mainfrom
frc-validity-floor-and-split-order
Sep 30, 2026
Merged

alxndrkalinin merged 16 commits into
mainfrom
frc-validity-floor-and-split-order

Conversation

@alxndrkalinin

@alxndrkalinin alxndrkalinin commented Sep 29, 2026 •

Copy link
Copy Markdown
Owner

Stacked on #55 — base is frc-split-validity-and-noise-model-warnings, not main. Merge #55 first.

Addresses the five findings left open at the end of #55.

1. The validity test was a normalised radius; it should be a length (findings 1, 2, 4)

_CHECKERBOARD_VALIDITY_RADIUS = 0.9 was wrong in three ways that share one cause — a radius cannot express a physical, per-direction criterion.

Too loose. Reported resolution is 2·d_px / (r·f(r)), so Rieger's d_min ≥ 4·d_px is already breached at r = 0.797 and Koho's 2√2·d_px at r = 0.883. At r = 0.9 the value is 2.56·d_px — inside both. Everything in [0.797, 0.9) broke the criterion the warning itself quoted:

r f(r) reported/d_px old r ≥ 0.9 new floor
0.850 0.709 3.317 silent silent
0.883 0.801 2.827 silent warn
0.900 0.868 2.560 warn warn

Wrong axis. The grid is normalised by one Nyquist for the whole volume, so on anisotropic data the same radius is a different physical resolution along XY and Z.

Never deduplicated. The message interpolated {point:.3f}, so every call had distinct text and Python's once-per-location filter never merged them. grid_crop_resolution reaches this once per slice per crop. 200 varying calls now collapse to 1 warning; suite-wide warning count dropped 194 → 19.

Replaced by _warn_if_below_split_floor, comparing against 2√2 × the pixel size for the direction measured. _fsc_extract_resolution takes the measured array's voxel sizes and judges XY and Z separately.

2. Split raw counts before resampling (finding 5)

resample_isotropic ran before the binomial split, so halves drawn from an interpolated volume share source samples. The old response was a warning telling you to turn resampling off. Now the split runs first and the same interpolation is applied to each half — a linear operator applied separately to independent inputs leaves them independent.

MEASURED against two genuinely independent Poisson acquisitions of one object:

XY error Z error
resample → split (old) −47.4% −0.3%
split → resample (new) +8.5% +0.5%

The old path also fed 44% non-integer values into a counts-mode split, since an interpolated volume is no longer counts.

This does not rescue every binomial case. On the Koho pollen stack the one-bit crossing is absent either way, with or without resampling — I initially attributed that nan to the ordering and that was wrong. It's a threshold problem, not an ordering one.

Testing

174 passed. ruff check and mypy clean across 45 files. The two validity tests poked the private correction helper with a hand-built dataset, which cannot see a normalisation bug; they now drive frc_resolution end to end, plus unit tests for deduplication and for one length judged against two pixel sizes.

🤖 Generated with Claude Code

https://claude.ai/code/session_01RMWszUe53TCdX1XJ8rfWBj

Summary by Sourcery

Make single-image FRC/FSC validity checks physically directional and perform binomial splitting before resampling to avoid biased resolution estimates.

Bug Fixes:

  • Correct checkerboard validity warnings by evaluating reported physical resolution against direction-specific pixel-size floors, including anisotropic XY and axial measurements.
  • Preserve binomial split independence by splitting raw counts before applying isotropic resampling, including repeated estimates.

Enhancements:

  • Deduplicate sampling-limit warnings by using stable message text and update FSC resolution extraction to carry measured pixel sizes.

Tests:

  • Expand end-to-end coverage for physical sampling floors, warning deduplication, per-direction limits, split ordering, and repeated resampled binomial estimates.

Chores:

  • Refresh executed notebook outputs and comparison examples to reflect the revised FSC behavior and warnings.

alxndrkalinin and others added 11 commits September 29, 2026 13:53
…rence

The 0.59 / 3.91 um pair the pollen comparison was checked against appears
neither in Koho et al. (2019) nor in the reference implementation. Fig. 4b
prints PSF_WFHM = 0.6 x 3.9 um, which is the rounding of what miplib's own
notebook "One Image Sectioned FSC and 3D Wiener filtering" prints for this
stack: FWHM (Z: 3.8875587137876315 um, XY: 0.5986743538754852 um). 3.91 was
the outermost radial tick of the polar plot, and 0.5987 rounds to 0.60.

Cite the notebook output instead. It is still Koho's own SFSC result rather
than an independent measurement of the sample, so it cannot arbitrate
between the two axial corrections, but unlike a figure label it is
reproducible.

Record what reproducing it takes: at the notebook's resample_order=0,
bin_delta=10, one-bit threshold and 'spline' curve fit, cubic gives
Z 3.872 um / XY 0.578 um, within 0.4% and 3.5%. The gap previously
attributed to the axial formula is bin width and curve-fit type, not the
correction. Cropping to the notebook's 500^3 cube is deliberately not
adopted: it moves Z to 4.16 um (+7.1%).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RMWszUe53TCdX1XJ8rfWBj
…sumptions

Two cases where the single-image paths silently return a number that does
not mean what a caller will read it as.

Checkerboard past its validity range: _apply_cutoff_correction now warns
when the crossing lands at normalized radius >= 0.9. The split halves sample
a lattice twice as coarse per axis, so their Nyquist is half the original,
and a crossing that far out reflects the halves' own sampling limit rather
than a resolution the data support. Rieger et al. (2024) require
d_min >= 4 * pixel size and Koho et al. (2019) require 2*sqrt(2) * pixel
size; both are violated there, and the empirical calibration is clamped
inert, so the value can be optimistic by up to 2x.

Binomial split after interpolation: fsc_resolution warns when
split_type='binomial' is combined with resample_isotropic=True. Rieger et
al. are explicit that splitting the output of a reconstruction is incorrect
because the reconstruction introduces correlations; interpolating 181 -> 582
Z planes makes neighbouring planes near-copies and the axial correlation
never decays, measured as 0.745 um axial on the Koho pollen stack.

Also expand the _calibration_factor docstring to record why the min(f, 1.0)
clamp is there and where it departs from the published curve: past
r ~ 0.925 the paper's factor exceeds 1 and would report a resolution finer
than the source image's own Nyquist limit (measured 0.3228 um against a
0.3250 um limit at r = 0.944, and 0.1783 um at r = 1.0). miplib divides
unbounded and so reports those impossible values.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RMWszUe53TCdX1XJ8rfWBj
…sumptions

binomial_split assumes independent per-pixel Poisson noise. Neither
condition can be established from the array, so add three checks that are
veto-only by construction: they can show data is not counts, never that it
is. Nothing here selects a split type, and checkerboard remains the default.

  - band-limited axis: the per-axis fraction of Nyquist enclosing 99% of the
    spectral power, reported by axis index. Independent noise reaches
    Nyquist, so an untouched axis reads ~0.85-1.0 while an axis upsampled by
    m reads ~1/m. The Koho pollen stack gives 0.86/0.84/0.85 as acquired and
    0.20/0.77/0.79 after an order-1 resample in Z. This is the check that
    catches volumes resampled before cubic ever sees them, which the
    existing resample_isotropic flag check cannot.
  - variance that does not track intensity: normalized slope of a robust
    per-bin noise variance against local mean. Poisson gives ~1, additive
    Gaussian gives 0.00.
  - poisson_thinning on integer counts: thinning draws two variates from a
    shared rate, leaving a high-frequency correlation floor (~0.33 measured
    on simulated counts) that can stop the curve crossing 1/7 at all, so the
    resolution comes back nan with no explanation.

All three warn rather than raise: a violated assumption makes the number
unreliable, not uncomputable, and the caller may be doing this deliberately.

Both blind spots are pinned by tests rather than left to be found later.
Richardson-Lucy is undetectable (25 iterations reads 1.00/0.98/0.98, i.e.
fuller-band than the raw stack) and nearest-neighbour upsampling evades the
bandwidth check because replication reintroduces spectral replicas instead
of emptying the top of the band.

The slope fit is capped at 2M subsampled line-samples: unbounded it took
174 s on a 315 MB volume, and this runs per split. Since every repeat splits
the same image, check_noise_model threads from binomial_split through
preprocess_images to _calculate_frc_single_pass so the n_repeats loop pays
the cost on the first repeat only.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RMWszUe53TCdX1XJ8rfWBj
…fired

The spectral-bandwidth and variance-vs-mean checks both warned on valid
high-SNR Poisson data, which is exactly the input a binomial split is for.

Bandwidth: smooth structure holds nearly all the spectral power, so the band
looks narrow even though shot noise is independent and full-band. Measured
0.54/0.38/0.36 of Nyquist at 20k photons against 0.20 for a genuinely
resampled axis -- too thin a margin to threshold. Residual-based and
band-emptiness variants each lost a real detection instead.

Slope: finite differences pick up the signal gradient, which grows like the
dose while shot noise grows like its square root, so the slope collapses to
0.04 at 20k photons. Second differences annihilate locally-linear signal and
rescue the smoothest cases only (0.93 at sigma=8, still 0.05 at sigma=1).

Real stacks passed both (pollen 1.09, astrocyte 1.54), which is why this was
missed; synthetic fields resembling plausible microscopy did not. Inferring
"these are Poisson counts" from one structured image is not reliable enough
to warn on, so keep only the value-domain test: poisson_thinning handed
non-negative integer data. That has no false positives by construction.

Interpolation cubic itself performs is still caught exactly by the flag check
in fsc_resolution. check_noise_model existed solely to keep the expensive
checks out of the n_repeats loops and is removed with them, so the 2D and 3D
repeat loops go back to plain iteration.

Also guard a singleton final axis: the removed slope fit differenced along
the last axis, so binomial_split raised IndexError on shape (N, 1).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RMWszUe53TCdX1XJ8rfWBj
…ell output

Three corrections to the pollen reference material.

Koho et al. print "PSF_WFHM" in the Fig. 4a and 4b labels while their body
text uses FWHM correctly; the quotes here are verbatim, so annotate them
[sic] rather than silently correcting the source and rather than leaving
readers to assume the typo is ours.

The comparison cell in the 3D notebook still carried a stored output reading
"Koho et al. 0.5900 3.9100 6.6" from a run predating the reference fix, so
the rendered result contradicted the executable cell. Clear that cell's
output instead of hand-writing replacement numbers; it repopulates on the
next run.

The README and the frc.py comment quoted different numbers for the same
claim (XY 0.553 / Z 3.818 against XY 0.578 / Z 3.872) because one was taken
at cubic's default smooth-spline fit and the other at the notebook's spline
fit. State the notebook-matched configuration explicitly and use its numbers
in both places.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RMWszUe53TCdX1XJ8rfWBj
…ole array

Both integer tests in binomial_split flattened the full image before
subsampling. reshape(-1) on a non-contiguous array copies, so a cropped view
-- which is how the benchmark and notebook code passes volumes -- was copied
in its entirety before the sample cap could apply: 114 ms and 108 MB for a
300x300x300 crop, to look at 2M values.

Stride the leading axis first, then flatten the slice. The cropped view and
the contiguous array now cost the same (27 ms each) because neither is
copied whole.

Fold the pre-existing counts-mode integer check onto the same sampler. It
asked the same question with its own full-array pass and a separate
formulation, so the two could drift; now they read one subsample and each
compute their own statistic from it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RMWszUe53TCdX1XJ8rfWBj
_FLOAT_NON_INTEGER_FRAC_THRESHOLD is documented as a per-pixel tolerance and
the counts-mode check uses it that way, comparing each pixel's distance to
the nearest integer and averaging the result. The thinning check instead
compared a *mean* deviation against the same constant -- a different
statistic borrowing a knob calibrated for another purpose, free to drift
away from its sibling.

Extract _non_integer_fraction and have both call it, so the tolerance keeps
one meaning. The two thresholds are now complements of each other: counts
mode warns above _FLOAT_NON_INTEGER_WARN_FRACTION, thinning treats the data
as counts at or below it.

Also drop the restated calibration derivation from the clamp test's
docstring. It repeated the 1.813 plateau, the 0.925 crossing and Rieger's
4*d_px from the _calibration_factor docstring, so those numbers had to be
corrected in two places; point at the source instead.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RMWszUe53TCdX1XJ8rfWBj
…integers

Two defects in the sampler and the thinning test, both found by review.

_sample_values strided only the leading axis, so whenever a single plane held
more than the cap the slice collapsed to plane 0 and the verdict depended on
whatever that plane contained: a (4, 2048, 2048) stack was judged from its
first plane, and it returned 4.19M values against a 2M cap. A (1, 3000, 3000)
input escaped the cap entirely at 9M. Stride every axis by the same factor
instead, then trim any remainder. Basic slices stay views, so the cropped-view
copy this function exists to avoid is still avoided.

The thinning check treated data as counts when the *average* pixel was close
to an integer. Sparse float images -- deconvolved or background-subtracted,
which is exactly what thinning is the fallback for -- are mostly exact zeros,
so the average reads as integral and the warning fired on them. Require every
sampled value to be integral.

Restore the "# image operations assume ZYX channel order" comment, which an
earlier edit in this branch removed by accident.

The no-false-positive tests ran in counts mode, where the check returns on its
first line, so they could not have caught either problem; they now exercise
poisson_thinning. Adds regressions for the sampler spread and cap, and for
sparse float input.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RMWszUe53TCdX1XJ8rfWBj
fsc_resolution takes xy_curve_fit_type and z_curve_fit_type; the README and
the axial-correction comment both named a curve_fit_type argument it does not
accept, so copying the documented reproduction settings raises TypeError.

The band-edge warning claimed "the empirical calibration is also clamped
inert here" from r = 0.9, but _calibration_factor only reaches its 1.0 clamp
near r = 0.93 -- it returns 0.868 at 0.9 and 0.993 at 0.924, so the value is
still being coarsened by up to 15% where the message says nothing is applied.

Also rewrap two comments this branch left malformed: one 126-character line
and one that broke mid-sentence.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RMWszUe53TCdX1XJ8rfWBj
…n length

The validity test was a fixed normalized radius of 0.9 inside the calibration
helper. It was wrong in three ways that share one cause: a radius cannot
express a physical, per-direction criterion.

Too loose. The reported value is 2 * d_px / (r * f(r)), so Rieger's
d_min >= 4 * d_px is already breached at r = 0.797 and Koho's
d_min >= 2*sqrt(2) * d_px at r = 0.883. At r = 0.9 the value is 2.56 * d_px,
inside both. Every crossing in [0.797, 0.9) broke the criterion the warning
itself quoted, silently.

Wrong axis. The frequency grid is normalized by one Nyquist for the whole
volume, so on anisotropic data the same radius is a different physical
resolution along XY and Z: the warning fired for one direction while missing
the other.

Never deduplicated. The message interpolated the crossing radius, giving
every call distinct text, so Python's once-per-location filter never merged
them; grid_crop_resolution reaches this once per slice per crop.

Replace it with _warn_if_below_split_floor, comparing the resolution against
2*sqrt(2) times the pixel size *for the direction measured* -- Koho's own
bound, so every value that breaks it is reported without firing on merely
marginal ones. _fsc_extract_resolution now takes the measured array's voxel
sizes and judges XY and Z separately; calculate_frc judges the 2D result
against the spacing its frequency axis was normalized by. The message text is
constant, so repeats collapse to one.

_apply_cutoff_correction goes back to applying only the calibration.

The two tests for this poked the private correction helper with a hand-built
dataset, which cannot see a normalization bug; they now drive frc_resolution
end to end, plus unit tests for the deduplication and for one length judged
against two pixel sizes.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RMWszUe53TCdX1XJ8rfWBj
…about it

resample_isotropic ran before the binomial split, so the halves were drawn
from an interpolated volume: neighbouring voxels share source samples, the
halves are correlated, and the estimate is biased fine. The response was a
warning telling the caller to turn resampling off or switch to checkerboard,
which leaves the combination unusable.

Do it in the right order instead. Split the raw counts, then apply the same
interpolation to each half. A linear operator applied separately to
independent inputs leaves them independent, so the FSC premise survives and
the eq. (5) axial correction still applies.

MEASURED against two genuinely independent Poisson acquisitions of one
object, resampled the same way: splitting after resampling reports XY 47.4%
too fine, splitting before it +8.5% (axial -0.3% and +0.5%, which the
ordering barely touches because the split decimates in XY). The old path also
fed 44% non-integer values to a counts-mode split, since an interpolated
volume is no longer counts.

Note this does not rescue every binomial case: on the Koho pollen stack the
one-bit crossing is absent either way, with or without resampling, so that
nan is about the threshold and not the ordering.

Drops the warning and the test that pinned it.

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

sourcery-ai Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Reviewer's Guide

The PR makes checkerboard validity warnings physically meaningful and direction-specific, with stable warning deduplication, and corrects binomial FSC processing by splitting raw counts before independently resampling the halves. Tests now exercise the public resolution paths, anisotropic pixel sizes, warning behavior, and the resampling/splitting order.

Sequence diagram for raw-count splitting before FSC resampling

sequenceDiagram
    participant Caller
    participant fsc_resolution
    participant binomial_split
    participant resample_isotropic
    participant FSC

    Caller->>fsc_resolution: fsc_resolution(..., resample_isotropic=True, use_binomial=True)
    fsc_resolution->>binomial_split: binomial_split(image1, ...)
    binomial_split-->>fsc_resolution: independent image1 and image2
    fsc_resolution->>resample_isotropic: resample image1
    resample_isotropic-->>fsc_resolution: resampled image1
    fsc_resolution->>resample_isotropic: resample image2
    resample_isotropic-->>fsc_resolution: resampled image2
    fsc_resolution->>FSC: calculate FSC from independent halves
    FSC-->>Caller: resolution result
Loading

Flow diagram for direction-specific checkerboard validity warnings

flowchart LR
    A[Checkerboard FSC result] --> B{Single-image checkerboard?}
    B -- No --> C[Return corrected resolution]
    B -- Yes --> D[Measure resolution in physical units]
    D --> E{Resolution below split floor?}
    E -- No --> C
    E -- Yes --> F[_warn_if_below_split_floor]
    F --> G[Constant direction-specific RuntimeWarning]
    G --> C
    H[XY resolution] --> I[XY pixel size]
    J[Axial resolution] --> K[Z pixel size]
    I --> E
    K --> E
Loading

File-Level Changes

Change Details Files
Replace normalized-radius validity checks with per-direction physical-resolution floors.
  • Add a 2√2 pixel-size sampling floor for checkerboard results.
  • Pass measured Z and XY pixel sizes through FSC extraction and warn independently for each direction.
  • Move warning emission after resolution conversion and keep message text constant for warning deduplication.
  • Update end-to-end tests for physical thresholds, anisotropy, and deduplicated warnings.
cubic/metrics/spectral/frc.py
tests/metrics/spectral/test_frc.py
Split raw count data before isotropic resampling for binomial FSC.
  • Perform the binomial split before interpolation when both binomial splitting and resampling are enabled.
  • Resample each independently split half using the existing interpolation path.
  • Remove the obsolete warning that instructed callers to disable resampling.
  • Add regression tests comparing against independent acquisitions and verifying no ordering warning remains.
cubic/metrics/spectral/frc.py
tests/metrics/spectral/test_frc.py

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 1 issue

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

## Individual Comments

### Comment 1
<location path="cubic/metrics/spectral/frc.py" line_range="1500" />
<code_context>
+    # raw counts first, then apply the *same* interpolation to each half: a
+    # linear operator applied separately to independent inputs leaves them
+    # independent, so the premise survives and eq. (5) still applies.
+    presplit_binomial = use_binomial and resample_isotropic
+    if presplit_binomial:
+        image1, image2 = binomial_split(
</code_context>
<issue_to_address>
**issue (bug_risk):** When `split_type='binomial'`, `resample_isotropic=True`, and `n_repeats > 1`, the code performs one binomial split before resampling, sets `use_binomial` to false, and therefore skips the later repeated-split branch. The requested repeats are silently ignored without the existing warning, so the result lacks the independent-repeat averaging and standard deviations promised by `n_repeats`.

**Triggers:** When callers request multiple binomial repeats together with isotropic resampling.

**Suggested fix:** Preserve the repeat path by splitting and resampling independently for every repeat, or reject/explicitly warn that `n_repeats` is unsupported for presplit resampling.
</issue_to_address>

Sourcery assessment

Approval pending. 1 finding to address first.

Blocking findings: cubic/metrics/spectral/frc.py:1500


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

Comment thread cubic/metrics/spectral/frc.py Resolved
Hoisting the pre-split out of the loop also cleared the binomial flag, so
`if use_binomial and n_repeats > 1` was false and the multi-repeat path was
skipped entirely. n_repeats was silently ignored and xy_std/z_std dropped out
of the returned dict -- a change in the result's shape rather than a visible
failure.

Every repeat needs its own draw, so the interpolation cannot be shared: move
both into _binomial_halves_resampled and call it per repeat. Only the
resampled spacing and anisotropy are needed up front, and those depend on the
Z extent and the input spacing alone, so take them from a thin proxy slice
rather than paying for a full resample whose voxels are then discarded.

Cost on the Koho pollen stack (181x512x512 -> 582x512x512, A40): 8.20 s for
one repeat, 23.66 s for three, 38.57 s for five -- linear at ~7.9 s per
repeat, of which the added resample is 1.85 s. The remaining ~6 s is the FSC
over the upsampled volume, which the old ordering also paid on every repeat,
so splitting first costs about 23% per repeat rather than doubling anything.

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

Copy link
Copy Markdown
Owner Author

Follow-up: the per-repeat cost I flagged turned out to hide a regression, now fixed in d9065b4.

Hoisting the pre-split out of the repeat loop also cleared the binomial flag, so if use_binomial and n_repeats > 1 was false and the multi-repeat path was skipped entirely — n_repeats was silently ignored and xy_std/z_std disappeared from the returned dict. That is a change in the result's shape, not a visible failure, so a regression test now pins it.

Measured cost on the pollen stack (181×512×512 → 582×512×512, A40):

config total per repeat
checkerboard, n=1 1.99 s 1.99 s
binomial, n=1 8.20 s 8.20 s
binomial, n=3 23.66 s 7.89 s
binomial, n=5 38.57 s 7.71 s

Linear at ~7.9 s/repeat, of which the added resample is 1.85 s. The other ~6 s is the FSC over the upsampled volume, which the old ordering also paid on every repeat — so splitting first costs about 23% per repeat, not a doubling. The dominant cost is resampling to isotropic at all (3.2× the voxels), which is independent of split order.

175 tests pass.

@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 2 commits September 29, 2026 22:56
All seven run clean on an A40 with no errors. Source cells are byte-identical
-- only outputs and execution counts change -- so the nbconvert-generated
scripts are unaffected.

This refreshes results that the FRC/FSC work had made stale or removed:

- resolution_estimation_3d's comparison table had its output cleared when the
  pollen reference was corrected, because the stored table still read
  "Koho et al. 0.5900 3.9100". It now regenerates with 0.5987 / 3.8876 from
  miplib's own SFSC notebook, consistent with the code and the README.
- The two deconvolution notebooks now surface the new per-direction sampling
  floor on the astrocyte stack, whose crossing sits at the halves' own
  sampling limit. That warning is the point of the check, not a regression.
- split_comparison_frc_fsc surfaces the poisson_thinning-on-integer-counts
  warning. That notebook deliberately runs both counts and thinning on the
  same data to compare them, so the warning is the check firing correctly on
  a mode the notebook is demonstrating.

Runtimes: deconvolution_iterations_3d 520 s, split_comparison_frc_fsc 415 s,
feature_extraction_3d 176 s, resolution_estimation_3d 99 s,
segmentation_3d_monolayer 96 s, resolution_estimation_2d 76 s,
deconvolution_wb_backprojector_3d 44 s.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RMWszUe53TCdX1XJ8rfWBj
…n is expected

The notebook runs counts and poisson_thinning on the same tubulin image to
compare them, so cubic's "poisson_thinning on non-negative integer data"
warning now appears in the committed output. Without a note a reader takes it
as a mistake in the example rather than the check doing its job on a mode the
notebook exists to demonstrate.

Markdown only; no code cell changed, so the executed outputs stay valid.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RMWszUe53TCdX1XJ8rfWBj
@alxndrkalinin
alxndrkalinin changed the base branch from frc-split-validity-and-noise-model-warnings to main September 30, 2026 19:16
alxndrkalinin and others added 2 commits September 30, 2026 12:16
Merging main resurrected two blocks this branch had deleted. Their
replacements landed here first, then #55 was squashed onto main, so the
three-way merge saw both as new on the main side and re-added them
alongside the code that replaced them.

The radius check referenced _CHECKERBOARD_VALIDITY_RADIUS, which this
branch removed with the check itself, so the merged file raised NameError
on every checkerboard crossing. Its replacement, _warn_if_below_split_floor,
judges the same limit per direction and in length units.

The binomial + resample_isotropic warning is obsolete for the same reason:
this branch splits raw counts before resampling, so there is no longer an
interpolated-input case to warn about.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RMWszUe53TCdX1XJ8rfWBj
@alxndrkalinin
alxndrkalinin merged commit 17568f4 into main Sep 30, 2026
9 checks passed
@alxndrkalinin
alxndrkalinin requested a balanced review from Copilot September 30, 2026 19:28

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.

Copilot review overview

🟡 Changes recommended

The mask backend skips binomial resampling and no longer emits checkerboard validity warnings.

Review effort: Balanced
Findings: 1 High severity · 1 Medium severity

Open (2)
What changed in this PR

Updates FSC/FRC sampling validation and preserves binomial-half independence during isotropic resampling.

Changes:

  • Adds direction-specific checkerboard sampling-floor warnings.
  • Splits binomial counts before independently resampling each half.
  • Expands regression tests and refreshes example outputs.
File Description
cubic/​metrics/​spectral/​frc.py Implements sampling warnings and split-before-resample flow.
tests/​metrics/​spectral/​test_frc.py Adds warning, ordering, and repeat tests.
examples/​scripts/​split_comparison_frc_fsc.py Documents expected thinning warning.
examples/​notebooks/​split_comparison_frc_fsc.ipynb Refreshes comparison results.
examples/​notebooks/​segmentation_3d_monolayer.ipynb Refreshes execution outputs.
examples/​notebooks/​resolution_estimation_3d.ipynb Refreshes resolution outputs.
examples/​notebooks/​resolution_estimation_2d.ipynb Refreshes execution outputs.
examples/​notebooks/​feature_extraction_3d.ipynb Refreshes benchmark outputs.
examples/​notebooks/​deconvolution_wb_backprojector_3d.ipynb Refreshes warnings and outputs.
examples/​notebooks/​deconvolution_iterations_3d.ipynb Refreshes iterative results.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread cubic/metrics/spectral/frc.py Resolved
Comment thread cubic/metrics/spectral/frc.py Resolved
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