Skip to content

Add reject_by_annotation support to AMICAICA.fit and AMICAICA._data_for - #252

Merged
neuromechanist merged 4 commits into
sccn:devfrom
psysunyuhong:pAMICAdevSYH
Aug 22, 2026
Merged

neuromechanist merged 4 commits into
sccn:devfrom
psysunyuhong:pAMICAdevSYH

Conversation

@psysunyuhong

@psysunyuhong psysunyuhong commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Background

This PR addresses Issue #251.

When using AMICAICA with MNE Raw data, segments marked with bad_* annotations should not be used during AMICA fitting, consistent with the behavior of MNE's ICA.fit().
Previously, AMICAICA.fit() always used the complete Raw data, including samples covered by bad annotations. This could cause artifact-contaminated segments to be included during AMICA model fitting.

Changes

This PR adds reject_by_annotation support to AMICAICA.fit().

  • Added reject_by_annotation=True as a fitting parameter.
  • When enabled, samples covered by annotations whose description starts with "bad" are excluded from AMICA fitting.
  • The original Raw sample mask is stored in good_sample_mask_.
  • The mask preserves the correspondence between the fitted data and the original Raw sample timeline.
  • When reject_by_annotation=False, all samples are retained, preserving the previous behavior.

Model Probability Reconstruction

The stored sample mask also allows per-sample AMICA model probabilities to be mapped back to the original Raw timeline.
For example, if a 30-second recording contains 600 rejected samples:

  • Original Raw data: 3000 samples
  • Samples used for AMICA fitting: 2400 samples
  • Rejected samples: 600 samples

The model probabilities can therefore be reconstructed to the original 3000-sample timeline, with rejected samples represented as NaN.
This preserves the temporal correspondence required for subsequent time-resolved model weighting and reconstruction.

Testing

A test was added using an artificial 30-second MNE Raw object with three bad_* annotation segments.

The test verifies that:

  • reject_by_annotation=True excludes the expected samples.
  • reject_by_annotation=False retains all samples.
  • good_sample_mask_ has the correct length and number of rejected samples.
  • Model probabilities can be mapped back to the original Raw timeline.
  • Rejected samples are represented as NaN.
  • Good-sample probabilities are preserved after reconstruction.

All tests pass. Test file available in pamica/tests/mne_tests/test_bad_annotation.py
Test on 306-channel Elekta data with around ~70 rank, test pass.
Related to #251

@neuromechanist

Copy link
Copy Markdown
Member

@claude, can you do pr review here?

@neuromechanist neuromechanist added the good first issue Good for newcomers label Aug 22, 2026
@neuromechanist
neuromechanist changed the base branch from main to dev August 22, 2026 22:39
Derive good_sample_mask_ from the same get_data call that produces the fitted data (public API, no private MNE import), false outside start/stop; score by the passed instance's own annotations with timeline-aligned NaN output; restore the Epochs path (Epochs.get_data has no reject_by_annotation kwarg); rewrite the test as a real-sample-data pytest suite.
@neuromechanist

Copy link
Copy Markdown
Member

Thanks @psysunyuhong -- this is a well-aimed contribution and the good_sample_mask_ idea is exactly right. I reviewed it, kept your design, and pushed a rework commit (95dd55f) directly to your branch, plus a merge of dev (now the repository default branch and this PR's base). What the review found and how the rework addresses it:

Bugs fixed

  1. start/stop composition: the mask stayed True outside the fitted [start, stop) range, so mask.sum() disagreed with the number of fitted samples and the reconstruction workflow broke whenever a sample range was used. The mask is now False outside the range (test: test_start_stop_composes_with_rejection).

  2. Epochs path: Epochs.get_data(reject_by_annotation=None) raises TypeError -- MNE's Epochs.get_data has no such kwarg (only Raw's does), so every Epochs fit would have crashed. Restored the plain call (test: test_epochs_fit_is_unaffected).

  3. Private import: mne.annotations._annotations_starts_stops is private API and also failed the ty CI job. The mask is now derived from the public get_data(reject_by_annotation="omit", return_times=True) -- the same call that produces the fitted array, so mask and data cannot disagree by construction (test: test_mask_indexes_exactly_the_fitted_columns).

Semantics adjusted

Your _data_for applied the stored fit-time mask to whatever instance is passed, which shortens get_model_probability output (while get_sources stays full-length) and forces consumers to re-index manually -- your test did exactly that dance. MNE's own precedent (ICA.score_sources(..., reject_by_annotation=True)) rejects by the passed instance's annotations at evaluation time. So now get_model_probability, plot_model_probability, mir, and pmi all take reject_by_annotation=True, reject by the passed instance's own bad_* annotations, and per-sample outputs keep the full n_times timeline with NaN in rejected columns. That is the "Model Probability Reconstruction" section of your PR description built into the library: ica.get_model_probability(raw) returns the full-timeline array with NaN over the bad segments directly, no manual mapping, and it stays correct when scoring a different Raw than was fitted.

good_sample_mask_ and reject_by_annotation_ are kept as fitted attributes recording exactly what the fit consumed, as you proposed.

Tests

Rewritten as a pytest suite on the bundled real sample EEG (project policy: no synthetic-data tests; the script form also executed two AMICA fits at import time and printed FAIL without failing the build). The new suite additionally pins that fitting an annotated Raw equals fitting AMICA directly on the kept columns (test_fit_equals_manual_column_drop) and that NaN samples inside a bad-annotated span are tolerated (dropped before the finite check), which matters for your MEG use case.

All 64 MNE-wrapper tests pass locally, ruff/ty clean. Once CI is green I will squash-merge. Thanks again for the report and the implementation -- and for offering to test on your Elekta data.

One consistent ValueError when a scored Raw is entirely bad-annotated (was: silent all-NaN from get_model_probability, opaque zero-size reduction from mir/pmi); distinguish an empty start/stop range from annotation rejection in fit's error; document the new ValueError; extract _expand_to_timeline; add tests for both edges.
@neuromechanist
neuromechanist merged commit bf2ee0a into sccn:dev Aug 22, 2026
8 checks passed
neuromechanist added a commit that referenced this pull request Aug 25, 2026
* Complete 0.3.3 changelog for release

Rename Unreleased to 0.3.3 with a release summary and add the missing
user-facing entries: best-of-N restarts (#198/#299), MNE bad_* annotation
rejection (#251/#252), the numpy comp_used staleness fix (#240/#243), and
the nd pre-update gm weighting (#219/#241). Docs only, not tested beyond
proofread.

* Correct stale counts and citations in changelog

The 0.3.3 param-reader entry still said 36 unsupported keywords and
listed the do_opt_block search among them; #232 moved those four keys
to identity mappings, leaving 32 (fortran_params.py's own arithmetic:
57 + 32 = 89). Also aligned two Fortran citations with the literal
source: the loglik/modloglik allocation spans 2617-2620 and the
reject_data zeroing block 2231-2234, matching the ranges now used
across the codebase. Docs only.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

good first issue Good for newcomers

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants