Skip to content

[pop_runica] Reduce rank-deficient runica to the estimated rank - #601

Merged
suraj-ranganath merged 5 commits into
developfrom
cursor/fix-567-runica-rank-0f06
Nov 18, 2026
Merged

suraj-ranganath merged 5 commits into
developfrom
cursor/fix-567-runica-rank-0f06

Conversation

@suraj-ranganath

@suraj-ranganath suraj-ranganath commented Nov 11, 2026 •

Copy link
Copy Markdown
Member

pop_runica passes the estimated runica rank as pca and records it. An explicit pca is unchanged. Direct runica still spheres every channel and is ill-conditioned on an average-reference null. Reconstruction is compared with the rank-31 PCA projection at the existing sphere tolerance, rtol 1e-10 and atol 1e-12. Aligned maps use the existing 0.9999 correlation bound: their elementwise difference is 6.3e-7 because EEGLAB's scaled product leaves its projector by 5.7e-8. Please rerun tests/test_runica.py::TestRunicaParity::test_parity_average_reference_pop_runica_rank. The reference suite was not run here.
Fixes #567

Open in Web Open in Cursor 

Average-referenced data fails EEGLAB's covariance-eigenvalue rank check.
Pass that rank as pca unless the caller set pca, and record it in history.

Co-authored-by: Suraj Ranganath <[email protected]>

@claude claude 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.

⚠️ Code review skipped — your organization has no extra usage available to pay for this review.

If your organization's extra usage balance is empty, an organization admin can add extra usage credits at claude.ai/admin-settings/usage. If its monthly spend limit was reached, an admin can raise it on the same page. If neither applies, contact Anthropic support.

Once extra usage is available, someone with write access to this repository can comment @claude review on this pull request to trigger a review.

@suraj-ranganath
suraj-ranganath marked this pull request as draft November 11, 2026 18:33
@suraj-ranganath
suraj-ranganath marked this pull request as ready for review November 11, 2026 18:33
EEGLAB's icawinv*icaweights*icasphere*data leaves its own PCA projector by
5.7e-8 after RMS scaling. EEGPrep stays on that projector.

Co-authored-by: Suraj Ranganath <[email protected]>
@suraj-ranganath
suraj-ranganath marked this pull request as draft November 11, 2026 18:56
@suraj-ranganath
suraj-ranganath marked this pull request as ready for review November 11, 2026 18:56
@suraj-ranganath
suraj-ranganath marked this pull request as draft November 18, 2026 06:56
@suraj-ranganath
suraj-ranganath marked this pull request as ready for review November 18, 2026 06:57

@claude claude 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.

⚠️ Code review skipped — your organization has no extra usage available to pay for this review.

If your organization's extra usage balance is empty, an organization admin can add extra usage credits at claude.ai/admin-settings/usage. If its monthly spend limit was reached, an admin can raise it on the same page. If neither applies, contact Anthropic support.

Once extra usage is available, someone with write access to this repository can comment @claude review on this pull request to trigger a review.

Keep the pop_runica rank changelog entry with the newer unreleased notes.

Co-authored-by: Suraj Ranganath <[email protected]>
@suraj-ranganath
suraj-ranganath marked this pull request as draft November 18, 2026 09:34
@suraj-ranganath
suraj-ranganath marked this pull request as ready for review November 18, 2026 09:35
@claude

claude Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @suraj-ranganath's task in 1m 38s —— View job


Code review

  • Overall assessment: Needs changes. The rank logic matches EEGLAB getrank: first 3000 frames, rank tolerance max(size)*eps(s1), cov(...,1) eigenvalues above 1e-7, and the minimum when they disagree. It runs on the chanind subset, and the concatenated and per-dataset history paths behave correctly. One problem remains: the explicit-pca check is case-sensitive.
  • Highest-risk area: _options_for_ica_backend and eeg_runica, where the code decides whether the caller supplied pca.
  • Merge recommendation: Needs changes.

Blocking

None.

Important

  1. An explicit pca with different capitalization is silently overwritten. This affects pop_runica.py _options_for_ica_backend and eeg_runica.py eeg_runica.
    • Cause: both places check "pca" in options, which is case-sensitive. A dict passed through options= is not lowercased; _normalise_ica_options lowercases only the string and list paths. eeg_runica kwargs are not lowercased either.
    • Example: pop_runica(EEG, icatype='runica', options={'PCA': 20}) on average-referenced 32-channel data produces {'PCA': 20, 'pca': 31}. runica then lowercases keys through parse_key_value_args (value_parsing.py:27-29), and the later pca=31 wins.
    • Result: 31 components instead of 20, and the history records both keys. eeg_runica(EEG, PCA=20) fails the same way.
    • Why it matters: EEGLAB matches option names with strcmpi, so this breaks the "an explicit pca is kept" contract the PR documents.
    • Fix: check the key case-insensitively in both places, e.g. any(str(k).lower() == "pca" for k in options), and add a test with options={'PCA': 20}. The inline comment has a suggestion for the pop_runica.py side.
  2. The MATLAB reference run is missing. This PR changes core pop_runica/eeg_runica numerics, and the description says the reference suite was not run. AGENTS.md §Testing requires one eeglab-reference.yml dispatch, or a local --eeglab-backend=matlab run, before merge. The PR body should include the EEGLAB and eeglab_tests commits and the pass/fail/skip counts.

Nits

  • apply_runica_data_rank(..., pca_requested=True) computes the rank only to log the inconsistency warning, then returns the options unchanged. AGENTS.md lists boolean dispatch as a pattern to avoid. Consider calling eeglab_data_rank(data, pca_requested=True) directly from _options_for_ica_backend and removing the flag from apply_runica_data_rank.
  • On full-rank data the rank is estimated twice on the pop_runica path: once in _options_for_ica_backend, then again in eeg_runica because pca is still absent. The cost is small with 3000 frames, but the check could live in one layer.

Test gaps

  • No test passes an explicit pca with different capitalization, either through options={...} or as an eeg_runica kwarg (see Important 1).

EEGLAB parity notes

  • EEGLAB pop_runica does not add the estimated 'pca' to com; EEGPrep records it in history. This deviation is documented and tested in test_gui_pop_runica.py and test_runica.py, and it makes history replay explicit, so it is fine.
  • This CI checkout has no vendored EEGLAB pop_runica.m, so the getrank comparison above is against EEGLAB's upstream pop_runica.m.

· Branch: cursor/fix-567-runica-rank-0f06

def _options_for_ica_backend(EEG, icatype, options):
if icatype != "runica":
return options
return apply_runica_data_rank(EEG["data"], options, pca_requested="pca" in options)

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.

Important: the check for an explicit pca is case-sensitive.

_normalise_ica_options does not lowercase dict options. So pop_runica(EEG, icatype='runica', options={'PCA': 20}) misses this check, and the rank estimate adds pca=31. runica then lowercases keys through parse_key_value_args, and the later pca=31 overrides the user's 20. History records both keys. EEGLAB matches option names with strcmpi.

The same check exists in eeg_runica (if 'pca' not in kwargs), so eeg_runica(EEG, PCA=20) has the same problem.

Suggested fix: check the key case-insensitively in both places, and add a test with options={'PCA': 20}.

Suggested change
return apply_runica_data_rank(EEG["data"], options, pca_requested="pca" in options)
return apply_runica_data_rank(
EEG["data"], options, pca_requested=any(str(key).lower() == "pca" for key in options)
)

(eeg_runica.py needs the matching change.)

EEGLAB matches the pca option with strcmpi. An uppercase key is the
caller's choice, so it is not replaced by the estimated rank.

Co-authored-by: Suraj Ranganath <[email protected]>
@suraj-ranganath
suraj-ranganath marked this pull request as draft November 18, 2026 10:20
@suraj-ranganath
suraj-ranganath marked this pull request as ready for review November 18, 2026 10:20
@claude

claude Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @suraj-ranganath's task in 1m 25s —— View job


Code review

  • Pre-review gate and head check (e510e05, matches the PR head)

  • Read diff and repository instructions

  • Review passes (AGENTS.md, conventions, correctness, EEGLAB parity)

  • Post review

  • Overall assessment: Needs more context. Commit e510e05 fixes the earlier case-sensitivity finding. _pca_option_key now matches PCA in both pop_runica and eeg_runica, and test_pop_runica_matches_an_uppercase_pca_key covers both paths. The rank logic, the chanind subset handling, and the history recording look correct. The concatenated, per-dataset and concatcond cases also look correct.

  • Highest-risk area: the default eeg_runica behavior changed, and it reaches beyond pop_runica.

  • Merge recommendation: Needs more context. The MATLAB reference run is still missing.

Blocking

None.

Important

  1. The MATLAB reference run is still missing. This PR changes core pop_runica/eeg_runica numerics, and the description still says "The reference suite was not run here." AGENTS.md §Testing requires one eeglab-reference.yml dispatch on this branch, or a local --eeglab-backend=matlab run. Add to the PR body:

    • the command or workflow run
    • the EEGLAB and eeglab_tests commits
    • the pass/fail/skip counts and runtime

    That includes tests/test_runica.py::TestRunicaParity::test_parity_average_reference_pop_runica_rank, which only runs with MATLAB.

  2. eeg_runica now reduces rank for every caller, and the changelog only mentions pop_runica. bids_preproc.py:847 calls eeg_runica(EEG, posact=True, sortcomps=True, rndreset='off') directly. Its runica stage will now produce fewer components than channels whenever the cleaned data is rank-deficient, for example after an average reference. The change is reasonable, but it is visible to BIDS pipeline users and is not documented.

    • Fix: extend the changelog entry and ica_rejection.rst to name eeg_runica, and say that the bids_preproc runica stage inherits the new behavior.

Nits

  • apply_runica_data_rank(..., pca_requested=...) has a redundant flag (inline comment at eeg_runica.py:64-74). Both callers derive it from options. The function then checks _pca_option_key(options) again. When pca is explicit, it also runs an SVD and an eigendecomposition only to maybe log a warning. Removing the flag also removes the if guard at eeg_runica.py:115.
  • pop_runica.py:21 imports the private _pca_option_key from eeg_runica. That import is no longer needed if the flag above is removed.
  • On full-rank data, the pop_runica path still estimates the rank twice: once in _options_for_ica_backend, then again in eeg_runica because no pca was added. Each estimate covers at most 3000 frames, so this is cheap, but one layer could own the check.
  • test_matlab_eps_at_zero_is_eps_of_one tests a private helper directly. The rank tests already cover the behavior, so this is the kind of implementation-detail test AGENTS.md §Testing advises against.

Test gaps

None. The tests cover:

  • explicit, negative and uppercase pca
  • the 3000-frame window
  • the covariance-eigenvalue minimum
  • separate and concatenated datasets
  • recording the estimate in GUI history
  • source recovery under reduction

EEGLAB parity notes

  • This checkout has no vendored pop_runica.m (src/eegprep/eeglab/ is absent), so these points were checked against EEGLAB's upstream pop_runica.m and getrank:
    • the rank uses the first 3000 frames of EEG.data(chanind,:)
    • the matrix-rank tolerance is max(size)*eps(s1)
    • the covariance is cov(...,1) and eigenvalues count when above 1e-7
    • the smaller of the two counts wins when they disagree
    • 'pca', tmprank is passed only when no pca is given
  • EEGLAB does not put the estimated pca in com; EEGPrep does. This deviation is documented and tested in test_gui_pop_runica.py and test_runica.py, and it makes history replay explicit, so it is fine.
    · Branch: cursor/fix-567-runica-rank-0f06

Comment on lines +64 to +74
def apply_runica_data_rank(data, options, *, pca_requested):
"""Return ``options`` with ``pca`` set from :func:`eeglab_data_rank` when needed."""
options = dict(options)
if pca_requested or _pca_option_key(options) is not None:
logger.warning(
"you have used PCA to reduce dimensionality so ICA "
"is not modeling the entire data, only the PCA-reduced data."
)
eeglab_data_rank(data, pca_requested=True)
return options
rank = eeglab_data_rank(data, pca_requested=False)

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.

Nit: pca_requested repeats what the function can already work out from options.

Both callers compute it from options. pop_runica._options_for_ica_backend passes _pca_option_key(options) is not None. eeg_runica passes False only when that key is absent. Line 67 then checks _pca_option_key(options) again. The flag never adds information, and AGENTS.md lists boolean dispatch as a pattern to avoid.

The explicit-pca branch also runs a full SVD and covariance eigendecomposition (line 72) and discards the result, only to maybe log EEGLAB's inconsistency warning.

Suggested fix: remove the parameter and branch on _pca_option_key(options) alone. Then change the callers to apply_runica_data_rank(EEG["data"], options) in pop_runica.py:248 and apply_runica_data_rank(data, kwargs) in eeg_runica.py:116. The if guard in eeg_runica becomes unnecessary.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Non-blocking. The flag is redundant with _pca_option_key, and the extra SVD on an explicit pca only feeds the inconsistency warning. It does not change the stored pca or the fit. Leaving it as is.

pop_runica is not the only caller. eeg_runica applies the same estimate,
and bids_preproc's runica stage calls eeg_runica.

Co-authored-by: Suraj Ranganath <[email protected]>
@suraj-ranganath
suraj-ranganath marked this pull request as draft November 18, 2026 10:43
@suraj-ranganath
suraj-ranganath marked this pull request as ready for review November 18, 2026 10:43
@claude

claude Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

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


Code review

  • Checked that the review is on the PR head (0d9b165)

  • Read the diff and AGENTS.md

  • Reviewed correctness, EEGLAB parity and tests

  • Posted the review

  • Overall assessment: Needs more context. Commit 0d9b165 fixes the remaining documentation finding: the changelog and ica_rejection.rst now say that eeg_runica and the bids_preproc runica stage also reduce rank. The earlier case-sensitivity fix from e510e05 is still correct. I re-checked these areas and found no new correctness issues:

    • the rank estimate and its 3000-frame window
    • matrix rank versus covariance eigenvalues, taking the minimum
    • the chanind subset
    • history recording for single, separate, concatenated and concatcond datasets
    • explicit, negative and uppercase pca
  • Highest-risk area: the default eeg_runica output now depends on the estimated rank, which changes numerics for every caller.

  • Merge recommendation: Needs more context. The MATLAB reference run is still missing.

Blocking

None.

Important

  1. The MATLAB reference run is still missing. This PR changes core pop_runica/eeg_runica numerics, and the description still says "The reference suite was not run here." AGENTS.md §Testing requires one of these before merge:

    • an eeglab-reference.yml dispatch on this branch, or
    • a local --eeglab-backend=matlab run.

    Add to the PR body:

    • the command or workflow run
    • the EEGLAB and eeglab_tests commits
    • the pass/fail/skip counts and runtime

    This also covers tests/test_runica.py::TestRunicaParity::test_parity_average_reference_pop_runica_rank, which only runs with MATLAB.

Nits

These were raised in the last review and are still open:

  • pca_requested is redundant. In apply_runica_data_rank (eeg_runica.py:117-126), both callers compute the flag from options, and the function checks _pca_option_key(options) again. When pca is explicit, the function also runs an SVD and an eigendecomposition only to maybe log a warning. Removing the flag would also remove the if guard in eeg_runica (eeg_runica.py:153) and the private _pca_option_key import in pop_runica.py:21. Fix this →
  • The rank is estimated twice on full-rank data. On the pop_runica path it runs once in _options_for_ica_backend and again in eeg_runica, because no pca was added. Each estimate covers at most 3000 frames, so this is cheap, but one layer could own the check.
  • One test checks a private helper. test_matlab_eps_at_zero_is_eps_of_one tests _matlab_eps directly, and the rank tests already cover that behavior. AGENTS.md §Testing advises against implementation-detail tests.

Test gaps

None. The tests cover:

  • explicit, negative and uppercase pca
  • the 3000-frame window
  • the covariance-eigenvalue minimum
  • separate and concatenated datasets
  • GUI history
  • source recovery under reduction

EEGLAB parity notes

  • The rank estimate follows EEGLAB pop_runica/getrank:
    • the first 3000 frames of the chanind data
    • rank tolerance max(size)*eps(s1)
    • cov(...,1) eigenvalues above 1e-7
    • the minimum when the two counts disagree
  • EEGLAB does not write the estimated pca into com; EEGPrep does. This deviation is documented and tested, and it makes history replay explicit, so it is fine.
  • concatcond and separate-dataset history leave out the estimated pca. Replaying that history re-estimates the rank for each dataset or group and gets the same result.
    · Branch: cursor/fix-567-runica-rank-0f06

Copy link
Copy Markdown
Member Author

The latest review has no blocking points.

The MATLAB parity tests that this PR asks for were run on jamming at e510e05, which is the same code as 0d9b165 except for docs. tests/test_runica.py::TestRunicaParity passed, including test_parity_average_reference_pop_runica_rank. The other runica and pop_runica tests also passed.

The pca_requested flag, the second rank estimate on full-rank data, and test_matlab_eps_at_zero_is_eps_of_one are nits. They do not change the estimated rank or the recorded pca, so I am leaving them.

@suraj-ranganath
suraj-ranganath merged commit 7ef6805 into develop Nov 18, 2026
19 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.

runica: sphere differs from EEGLAB on average-referenced (rank-deficient) data

2 participants