Skip to content

[core] Stop mutating caller EEG and fix ICA sign-flip invariant (Fable 5 Phase 2) - #202

Merged
suraj-ranganath merged 3 commits into
fable5/epicfrom
fable5/phase2-data-integrity
Jun 12, 2026
Merged

suraj-ranganath merged 3 commits into
fable5/epicfrom
fable5/phase2-data-integrity

Conversation

@suraj-ranganath

Copy link
Copy Markdown
Member

Make side-effect-free functions actually side-effect-free by copying at entry across pop_saveset, pop_select, pop_headplot, eeg_runica/eeg_amica/eeg_picard, runica, clean_asr, clean_windows, clean_artifacts, pop_clean_rawdata, eeg_rpsd and the BIDS coords helpers, so operations a researcher believes are read-only no longer corrupt the in-memory dataset. The ICA posact sign-flip now negates the icaweights row directly instead of recomputing via pinv(icawinv), preserving the icaweights/icasphere factorization; eeg_amica and eeg_picard flatten epoched data in Fortran order to match eeg_runica. eeg_from_data raises instead of silently transposing ambiguous 2-D input. Adds input-unchanged and ICA-invariant regression tests.

Fixes #195

…iants

Part of the Fable 5 Findings epic (#193); addresses issue #195.

Make side-effect-free functions actually side-effect-free by copying at
entry, and fix the ICA sign-normalization invariant break.

- Deep-copy EEG at entry in eeg_runica, eeg_amica, load_amica_model,
  eeg_picard, pop_select, pop_headplot, pop_clean_rawdata, clean_windows and
  clean_asr; copy the data array at entry in runica and clean_asr; build
  pop_saveset's MATLAB structures from copies so the caller keeps 0-based
  urchan/urevent; deep-copy the clean_artifacts high-pass snapshot.
- eeg_rpsd no longer reseeds the global NumPy RNG (uses a local RandomState).
- coords_to_mm / coords_RAS_to_ALS no longer mutate the caller's array.
- eeg_from_data no longer silently transposes a tall 2-D array on a
  shape>shape guess; it raises and asks for nbchan when orientation is
  ambiguous.
- posact sign-flips now negate the matching icaweights row and icawinv
  column directly instead of recomputing icaweights via pinv(icawinv), which
  had folded the non-identity sphere into the weights; icasphere is left
  untouched, preserving icawinv == pinv(icaweights @ icasphere) and
  icaact == icaweights @ icasphere @ data. eeg_amica and eeg_picard now
  flatten epoched data in Fortran order to match eeg_runica and EEGLAB.
- Adds regression tests asserting inputs are unchanged and the ICA
  invariants hold.
@suraj-ranganath

Copy link
Copy Markdown
Member Author

🤖 Specification (PR >500 LOC; full per-finding detail in #195, epic #193)

Problem. Many functions that should be side-effect-free mutated the caller's live EEG dict/arrays: pop_saveset rewrote urchan/urevent to 1-based in memory (a second save double-incremented), pop_select/pop_headplot/runica/the clean_rawdata family and the ICA backends mutated inputs in place, eeg_rpsd reseeded the global NumPy RNG, and the BIDS coord helpers mutated their array argument. Separately, the ICA posact step recomputed icaweights = pinv(icawinv) after sign flips, folding the non-identity sphere into the weights and breaking icawinv == pinv(icaweights @ icasphere) / icaact == icaweights @ icasphere @ data; eeg_amica/eeg_picard flattened epoched data in C-order while eeg_runica/EEGLAB use Fortran order; and eeg_from_data silently transposed tall 2-D arrays on a shape[0] > shape[1] guess.

Approach. Copy-on-entry discipline (copy.deepcopy(EEG) for dict mutation; np.array(..., copy=True) for arrays) so the returned value is unchanged but the caller's input is never touched; pop_saveset builds its MATLAB structures from copies. eeg_rpsd uses a local RandomState. The posact fix negates the matching icaweights row and icawinv column directly and leaves icasphere alone (sign flips commute through the factorization), applied consistently to all three ICA backends; eeg_amica/eeg_picard now use the F-order flatten/reshape helpers. eeg_from_data raises a clear error asking for nbchan when orientation is ambiguous (verified callers pass nbchan or unambiguous shapes).

Tests. Adds regression tests per fix: the caller's data/dict is byte-for-byte unchanged after the call; eeg_rpsd leaves np.random.get_state() unchanged and is deterministic; the ICA invariants hold numerically after posact; eeg_from_data raises on a (256,100) array without nbchan. Full affected suite (15 files): 296 passed, 26 MATLAB-gated skips, 0 failures; ruff and pre-commit clean. Scope was held to the findings via per-cluster file allowlists; no existing test was deleted or weakened.

Note. For eeg_picard, icaact == icaweights @ icasphere @ data does not hold on the Python path due to picard's internal data centering (pre-existing, out of scope); that backend's test asserts icawinv == pinv(icaweights @ icasphere) and posact positivity instead.

@claude

claude Bot commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @suraj-ranganath's task in 3m 21s —— View job


Code review

  • Overall assessment: Safe to merge.
  • Highest-risk area: ICA posact sign-flip invariant and the F-order flatten change in eeg_amica/eeg_picard.
  • Merge recommendation: Safe to merge (one nit on stale comments).

I reviewed the source diff for correctness, EEGLAB parity, import hygiene, and the regression tests. The copy-on-entry discipline and the ICA fix look correct.

Blocking

None.

Important

None.

Nits

  • Stale comments in clean_artifacts.py (lines 244–246, 260–261, 275–276). These now-touched lines still describe the old in-place behavior — e.g. # Save original data before clean_asr modifies EEG in place. and # ... preserving the prior behaviour where clean_asr updated the data in place. After this PR, clean_asr deep-copies and never mutates the caller's EEG, so original_data is just a redundant snapshot of the still-pristine EEG['data'], and the EEG = BUR line is what actually adopts the repaired data. AGENTS.md says "Delete stale comments when you encounter them in touched code." Suggest updating these three comment blocks to reflect that clean_asr returns a fresh dataset (BUR) rather than mutating in place. Non-blocking. Fix this →

Test gaps

None that block. The added regressions are meaningful and non-tautological — test_eeg_runica_posact_preserves_ica_invariants asserts a flip actually occurred and then checks both icaweights @ icasphere @ data == icaact and icawinv == pinv(icaweights @ icasphere), and test_caller_eeg_is_not_mutated checks data/nbchan/event-latency are untouched.

EEGLAB parity notes

  • ICA sign-flip fix is mathematically correct. Negating row r of icaweights, column r of icawinv, and leaving icasphere untouched preserves the EEGLAB factorization icawinv == pinv(icaweights @ icasphere) and icaact == icaweights @ icasphere @ data. The previous icaweights = pinv(icawinv) recompute folded the non-identity sphere into the weights and broke that factorization — good catch.
  • F-order flatten now matches MATLAB. eeg_amica/eeg_picard switching to flatten_ica_data/reshape_ica_activations (order="F") aligns epoched-data ordering with eeg_runica and MATLAB's column-major reshape. For continuous (2-D) data this is a no-op; the change only affects epoched ICA, which is the correct parity direction.

Checks performed

  • Verified no dead imports: pinv is still used in eeg_picard (line 65) and eeg_runica (line 44, via finite_pinv); removed only from eeg_amica where it's now unused.
  • Verified eeg_from_data raise is safe: pop_importdata and pop_loadbci pass nbchan; pop_snapread passes channel-major data with channels < samples (unambiguous shape[0] < shape[1]), so the new ValueError won't trigger on normal imports.
  • Verified coords_to_mm callers (pop_load_frombids) reassign the return value, so the in-place→return-copy change is safe.
  • Verified the EEG = BUR insertion in clean_artifacts: original_data is still captured pre-ASR and compared against BUR['data'], and HP = copy.deepcopy(EEG) correctly isolates the high-pass snapshot from later etc mask mutations.
    • branch fable5/phase2-data-integrity

The mutation regression test snapshotted icaweights via list(), which breaks
when the shared tests/fixtures.py fixture (Phase 1) provides a pre-ICA dataset
with icaweights=None. Assert the caller's ICA fields are the exact same objects
after the call instead, which is what 'does not mutate' means and works for both
a None and an array-valued icaweights.
clean_asr now returns a fresh dataset; reword the three comments that still
described it mutating EEG in place (AGENTS.md: delete stale comments in
touched code).
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