Skip to content

Leave invalid SLAP2 samples out of the extraction frames - #52

Merged
KasparP merged 2 commits into
mainfrom
fit-artifact
Nov 22, 2026
Merged

KasparP merged 2 commits into
mainfrom
fit-artifact

Conversation

@KasparP

@KasparP KasparP commented Nov 22, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #53

Problem

Some SLAP2 sources at the edge of the field get fitted activity of 1e4–1e7 counts, on pixels whose movie is 5–20
counts. This happens in some frames or whole trials, and in those frames their F0 collapses and dF_ls goes hugely
negative. Seen in 803121_2025-10-29_11-19-29 and 804730_2025-07-25_14-08-35, Path 2 of both.

Cause

The extraction trial loader forms its frames as getImages does: rawFramesAt calls
slap2FrameSums(..., 'MaskInvalid', false). So samples that SLAP2 marks invalid (intmin('int16')) are averaged in as
data, each counting as about −32768 raw counts. These occur, for example, where the online correction moved a
superpixel off the DMD.

At the field's edge this gives samples of −10 to −600 photons. The loader's filter for aberrant negatives
(< -2*std) misses most of them, because they inflate the pixel's own std. The fill of missing samples then averages
them in.

extractSources' loss, (Z−T)²/(F·(T+1)), is lowest at T = −Z−2 for an observation Z < −1. So each strongly negative
sample pulls the fit far up.

Registration (slap2Frames) and getImage already skip invalid samples, and SILo localization uses the registered
movie.

Evidence, from an integration-capsule run of 803121 (300 s) that saved the extraction subproblems:

  • Path 2's source 55 blows up in trials 1 and 12–15: maximum dF 3×10⁵ to 3.5×10⁶, against ~10³ in the other trials.
  • Its subproblem has hundreds of samples below −5 photons (down to −598) in the field's last columns in trials 1 and 15.
    It has none (minimum 0) in trials 3, 9 and 11.
  • Main's extractSources on the saved subproblem reproduces the blow-up. It is there after the first S fit, so it is not
    the footprint fit or normalization.
  • The source's pixels are mostly measured throughout, so unmeasured frames are not the cause.

Changes

  • rawFramesAt (processAllTrials_Async.m) skips invalid samples. Each channel's value is the mean of its valid
    samples. A frame with no valid sample at a pixel is missing (NaN), and the loader fills it in like any other missing
    sample. The weight is the first channel's, as in slap2Frames. Recordings without invalid samples are formed exactly
    as before.
  • slap2FrameSums formed the weights of pixels with invalid samples by subtracting the invalid samples' weights
    from the summed weights. That leaves roundoff of about eps times the summed weight: where every sample at a pixel was
    invalid, ±1e-16, so Num./Den was a signed zero instead of NaN; and where the only valid samples are far in the
    kernel's tail (weight exp(-dtRead/dt), when linesPerCycle is large relative to dt), the roundoff can exceed
    their weight. At pixels with invalid samples it now sums the valid samples' weights directly, as Num sums their
    values: exactly 0 where none is valid (as in getImage), and exact otherwise. Other pixels are formed as before.
    This also reaches registration's slap2Frames at pixels with invalid samples: those with no valid sample change
    from ~0 (weight ~1e-16) to NaN (weight 0), the others only by roundoff.
  • Tests:
    • TestCompensatedExtraction/testInvalidSamplesLeftOut writes a fake recording with a block of invalid samples and
      checks the samples handed to extraction. They must stay positive, be filled in where no valid sample is left, and
      otherwise be as steady as without invalid samples. On main the minimum sample is −24633 and samples deviate by 135
      spatial SDs.
    • TestSlap2Frames/testPixelsWithOnlyInvalidSamples checks the NaN value and zero weight of such pixels.
    • TestSlap2Frames/testOnlyValidSampleInKernelTail checks a pixel whose only valid sample is dtRead away
      (linesPerCycle 6, dt 0.25 and 0.1: weights exp(-24) and exp(-60)), also for a pixel subset. With a relative
      cutoff on the subtracted weights (this PR's first version) its image was Inf.
    • The fake slap2.Slap2DataFile gains invalidLines/invalidCols options.

Validation

  • Unit tests: the full tests/unit suite passes locally at 8e00248 (164/164), including the three new tests.
  • Integration capsule, 803121, 300 s, the same parameters as the run above (compensateOnline, peakMethod wmf,
    wmfPeakth 3), at 3296b05 (this PR's first commit) and at 8e00248. Both PASS, as did the run at main plus the debug
    dumps (ed0e47e), with the same 2 warnings (one trial each path fails alignment, in all three runs). All find 94
    sources in Path 1 and 113 in Path 2. The runs at 3296b05 and 8e00248 give bit-identical sources (profiles, F0,
    dF_ls, dF_denoised) and the same metrics apart from runtime. The comparison with main below holds for both.
    • Path 1: bit-identical to main (profiles, F0, dF_ls, dF_denoised).
    • Path 2, source 55: no blow-up left. Its maximum dF is 960–1670 in every trial (main: 3.5×10⁶ in trial 1,
      3×10⁵–1.4×10⁶ in trials 12–15). In trials 12–15 its median F0 (585–646) and dF_ls (76–88) are now in line with
      its other trials (548–834 and 66–108); on main they were 508–533 and −16 to 0. Trial 1 stays lower than the
      others (F0 360, dF_ls 43; main 254 and −7). No source in either path has a trial where the 99th percentile of dF
      exceeds 20× F0 (main: source 55 in trials 1 and 12–15).
    • Path 2, source 3, the neighbour of source 55 at the edge, was pulled down in the same trials on main. Its
      median F0 in trials 1 and 12–15 goes from 518–654 to 742–789 and its dF_ls from 59–79 to 96–104, in line with its
      other trials (753–957 and 73–136). Its profile changes by up to 13% of its peak, as does source 55's.
    • Other Path 2 sources change little. Sources 27, 57, 65 and 111 change in 8–62 frames of trial 14 or 15
      (dF_denoised correlates ≥ 0.9994 with main's). F0 and dF_ls of 57, 82 and 103 change by up to 0.4 SD, and their
      profiles by ≤ 0.3% of the peak. Depending on the trace, 84–87 of the 113 sources change by less than 1e-4 SD.
    • Source extraction took 5218 s (3296b05) and 5263 s (8e00248) against 5836 s on main, and its peak memory was 195
      and 199 GB against 202 GB. These are single runs, so the differences may be noise.

Not changed here

  • The loss's behaviour for Z < −1 would amplify any other source of strongly negative samples. Clamping Z at −1 in the
    fits would guard against that, but it changes every fit slightly.
  • The aberrant-negative filter could be made robust (median/MAD).

🤖 Generated with Claude Code

SLAP2 records intmin('int16') for samples it did not take, for example
where the online motion correction moved a superpixel off the DMD. The
trial loader formed its frames as getImages does (slap2FrameSums with
MaskInvalid false), so each such sample counted as -32768 raw counts.
At the edge of the field this gave samples of tens to hundreds of
negative photons, which the -2*std filter for aberrant negatives misses
(they inflate the pixel's own std) and which the fill of missing samples
spreads. Source extraction's loss, (Z-T)^2/(F*(T+1)), is lowest at
T = -Z-2 for an observation Z < -1, so these samples pulled the activity
of edge sources to 1e4-1e7 counts in exactly the frames or trials whose
lines were affected (803121 path 2, 804730 path 2).

rawFramesAt now skips invalid samples, as getImage and slap2Frames do:
each channel's value is the mean of its valid samples, and a frame with
none at a pixel is missing (NaN, filled in by the loader). Recordings
without invalid samples are formed exactly as before.

slap2FrameSums subtracted the weights of invalid samples from the summed
weights, which left about +-1e-16 where every sample was invalid, so
Num./Den gave a signed zero instead of NaN. Such weights are now exactly
0, as in getImage.

Tests: TestCompensatedExtraction/testInvalidSamplesLeftOut writes a fake
recording with a block of invalid samples (new invalidLines/invalidCols
options of the fake Slap2DataFile) and checks that the samples handed to
extraction stay positive, are filled in where no valid sample is left,
and are otherwise as steady as without invalid samples (on main: a
minimum sample of -24633 and deviations of 135 spatial SDs).
TestSlap2Frames/testPixelsWithOnlyInvalidSamples checks the NaN and zero
weight of pixels with only invalid samples.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Copilot AI 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.

🟡 Changes recommended

The weight cutoff can discard genuine valid contributions when linesPerCycle is large relative to dt, leaving a zero denominator with a positive numerator and causing slap2Frames to return Inf.

1 open issue
What changed in this PR

This PR excludes invalid SLAP2 samples from extraction frames to prevent strongly negative observations from inflating fitted source activity.

Changes:

  • Average valid samples per channel and treat pixels without valid samples as missing.
  • Add denominator cleanup intended to give fully invalid pixels exactly zero weight.
  • Extend fake recordings and regression tests to cover mixed-validity and fully invalid samples.
File Description
tests/​unit/​fakes/​+slap2/​Slap2DataFile.m Adds configurable invalid sample blocks.
tests/​unit/​dependencies/​extraction/​TestCompensatedExtraction.m Tests invalid-sample exclusion and missing-sample filling.
tests/​unit/​dependencies/​alignment/​slap2/​TestSlap2Frames.m Tests NaN values and zero weights for fully invalid pixels.
dependencies/​extraction/​processAllTrials_Async.m Enables invalid-sample masking and per-channel normalization.
dependencies/​alignment/​slap2/​slap2FrameSums.m Adds cleanup of residual weights after invalid-sample subtraction.

Review effort: Balanced

slap2FrameSums formed the weight of a pixel with invalid samples by
subtracting their weights from the summed weights, and zeroed results
below 1e-9 of the sum to remove roundoff. A pixel whose only valid
sample is far in the kernel's tail (weight exp(-dtRead/dt), when
linesPerCycle is large relative to dt) then lost that weight while Num
kept the sample, so its image was Inf; and such weights can be below
the roundoff of the subtraction altogether.

At pixels with invalid samples, the weight is now the sum of the valid
samples' weights, formed as Num sums their values: exactly 0 where none
is valid, exact otherwise. Other pixels are formed as before.

TestSlap2Frames/testOnlyValidSampleInKernelTail covers linesPerCycle 6
with dt 0.25 and 0.1 (tail weights exp(-24), exp(-60)), the exclusive
boundary and a pixel subset. It gave Inf before this change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Copilot AI 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.

🟢 Approval recommended

No active review issues remain for the changes that exclude invalid SLAP2 samples from extraction frames.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

@KasparP
KasparP merged commit 472f0e5 into main Nov 22, 2026
2 checks passed
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.

Extraction averages invalid SLAP2 samples into its frames, so sources at the field's edge get activity of 1e4–1e7 counts

2 participants