Skip to content

viewer: auto-scale initial gain to recording amplitude - #203

Merged
neuromechanist merged 4 commits into
mainfrom
feature/issue-109-viewer-autoscale
Jul 29, 2026
Merged

neuromechanist merged 4 commits into
mainfrom
feature/issue-109-viewer-autoscale

Conversation

@neuromechanist

Copy link
Copy Markdown
Contributor

Closes #109.

Estimator

Auto-scale computes a robust per-recording amplitude from the first
loaded window (the same data the first paint renders):

  1. estimateSignalAmplitude (src/lib/eeg-viewer/dsp.ts) takes, per
    channel, the 95th percentile of |sample| (non-finite samples
    skipped), then takes the median across channels of those
    per-channel values. Median (not mean or max) is what makes this
    robust to a single dead/railed channel: it becomes one entry among
    many rather than a value that drags a mean or dominates a max.
  2. autoscaleGain converts that amplitude into a gain that puts it at
    70% of a channel slot's half-height (the issue's "60-80%" target,
    using the midpoint), falling back to 1 (unchanged/default) for
    any zero, negative, or non-finite input so a silent/all-bad
    recording can never produce a divide-by-zero or Infinity gain.

In viewer.ts, the estimate is built from win.channels of the
first successful readFrame result (line/band channels, DC-removed
the same way the render path removes DC), so no extra network read is
added beyond what first paint already does.

Edge cases covered (unit tests in dsp.test.ts)

  • Normal multi-channel signal (deterministic ramp inputs, exact
    expected percentile/median)
  • All-zero channel and constant non-zero channel (no divide-by-zero,
    no throw)
  • NaNs mixed into a channel (skipped, not treated as 0)
  • An all-NaN channel (excluded entirely, does not drag the estimate
    toward 0)
  • One dead channel among several healthy ones (median ignores it)
  • Single-channel recording
  • No channels at all
  • autoscaleGain fallback to 1 for zero/negative/NaN amplitude and
    non-positive physPerDivSI, and never returns Infinity/NaN for a
    vanishingly small amplitude

Manual override + group switch

Scale +/- (buttons and +/- keys) set gainManuallySet = true.
Auto-scale only fires once per mount, and re-arms on a channel-group
switch to estimate the new group's own amplitude/modality -- but the
gainManuallySet guard means it never overwrites a gain the user
already touched.

Before/after scale-bar values (measured in the browser)

Recording Before (fixed default) After (auto-scaled)
on003800 (sub-001, AuditoryGammaEntrainment, ~1.6 uV std) 75 uV/div (traces flat/invisible) 4.7 uV/div
on003810 (sub-02, run-1, EDF, unit n/a, ~tens-of-units amplitude) 75 "uV"/div-equivalent (traces clip solid, see below) 25 V/div

on003810's store unit is n/a so the absolute label ("V" instead of
"uV") is a pre-existing, out-of-scope quirk (per the issue: "do not go
hunting for a conversion bug") -- the estimator works on the same
numeric scale as physPerDiv, so the fit is correct regardless of the
label.

What I verified in the browser

Ran bun run dev, opened both datasets' detail pages, expanded the
BIDS tree to a signal file (sub-001/eeg/..._eeg.set for on003800,
sub-02/eeg/..._run-1_eeg.edf for on003810), and confirmed:

  • Traces are legible at first paint without touching Scale, for both
    recordings.
  • Scale bar text captured directly from the canvas draw calls (patched
    CanvasRenderingContext2D.fillText to avoid any OCR/screenshot
    ambiguity) reads 4.7 µV (on003800) and 25 V (on003810) at first
    paint.
  • Manual Scale + and Scale - still work from the auto-scaled baseline:
    on003800 4.7 -> 3.1 uV (Scale+) -> 7.0 uV (Scale- x2); on003810 25 ->
    38 V (Scale-).
  • Reproduced the pre-fix "before" look for on003810 by dialing gain
    back toward 1 (~34 Scale+ presses) -- traces clip into solid blocks,
    confirming this is the exact problem viewer: auto-scale initial gain to each recording's amplitude #109 describes.
  • Screenshots taken via a Chrome MCP tab for both datasets showing
    clean, legible traces at first paint.

Two independent browser sessions were used for this (a shared
Puppeteer tab kept getting hijacked mid-session by another agent's
concurrent navigation in this same workspace -- visible as the tab
jumping to an unrelated dataset page), so the on003800 result was
reproduced twice from a clean state before trusting it.

Scope note

Re-autoscale-on-group-switch is implemented (not skipped) per the
issue's optional suggestion, guarded by the same gainManuallySet
check. No "fit" hotkey/button was added -- out of scope for this issue
(auto-scale is about the initial value, not a manual re-fit control).

Coordination

Issue #199 (full-screen modal for the viewer) is in flight in
parallel and touches src/pages/dataset/[id].astro and the mount
path. This PR only touches src/lib/eeg-viewer/dsp.ts,
src/lib/eeg-viewer/dsp.test.ts, and src/lib/eeg-viewer/viewer.ts.

Compute a robust amplitude estimate (median across channels of each
channel's 95th percentile |signal|, DC-removed) from the first loaded
window and use it to set the initial gain so a typical trace fills
~70% of its channel slot. Manual Scale +/- still overrides, and
group switches re-arm the estimate without stomping a manual change.

Falls back to the modality DEFAULT_SCALINGS (gain=1) when there is no
usable estimate (silent/all-bad channels), so a divide-by-zero or
Infinity gain is never produced.
@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Jul 29, 2026 •

Copy link
Copy Markdown

Deploying nemar-website with  Cloudflare Pages  Cloudflare Pages

Latest commit: f794855
Status: ✅  Deploy successful!
Preview URL: https://169ff9fd.nemar-website.pages.dev
Branch Preview URL: https://feature-issue-109-viewer-aut.nemar-website.pages.dev

View logs

@neuromechanist

Copy link
Copy Markdown
Contributor Author

Test gap fixed, pushed.

You were right that the existing case proved nothing: 1e-15 divides to a perfectly finite ~5.25e10 and never reaches the overflow branch it claimed to cover. I confirmed the same way you did — deleted Number.isFinite(gain) && gain > 0 ? gain : 1 and the whole file stayed green.

Split it into two tests:

  • the original 1e-15 case, renamed to say what it actually covers (a large-but-finite gain on the ordinary small-signal path)
  • a new case driving 5e-320 and Number.MIN_VALUE past the ~2.9e-313 threshold, asserting the result is finite and exactly 1

Re-ran the same mutation against the new test: falls back to 1 when the quotient overflows to Infinity fails as it should. Mutation reverted, git diff clean, 41/41 passing, lint clean.

The comment records the threshold and why the denormal input is load-bearing, so nobody "simplifies" it back to a friendlier-looking number later.

On your other two observations

  • DC-removal race — agreed it is narrow and acceptable. Autoscale fires once on the first window read, so the only divergence is a user opening the gear popover and unchecking DC before that read resolves. Not worth code in this PR.
  • on003810's looser reconciliation — agreed your reading is the right one. ±45 µV is a whole-recording dynamic-range figure while autoscale samples a windowed median-of-p95, so the smaller implied value is expected rather than contradictory. The on003800 reconciliation (implied ~3.29 µV vs ~3.14 µV predicted from 1.6 µV std) is the one that actually validates the math, and it lands within ~5%.

Thanks for mutation-testing this rather than reading it — that is what turned up the one real gap.

@neuromechanist
neuromechanist merged commit 0fadf7a into main Jul 29, 2026
5 checks passed
@neuromechanist
neuromechanist deleted the feature/issue-109-viewer-autoscale branch September 30, 2026 19:25
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.

viewer: auto-scale initial gain to each recording's amplitude

1 participant