Skip to content

[clean_rawdata] ASR: pseudo-invert only the kept components in the reconstruction matrix - #832

Merged
neuromechanist merged 6 commits into
developfrom
fix/asr-reconstruction-kept-rows
Nov 28, 2026
Merged

neuromechanist merged 6 commits into
developfrom
fix/asr-reconstruction-kept-rows

Conversation

@neuromechanist

Copy link
Copy Markdown
Member

Summary

asr_subspace_reconstruction, the port of R = real(M*pinv(bsxfun(@times,keep',V'*M))*V') (asr_process.m line 176, asr_process_r.m line 188), now pseudo-inverts only the kept rows of V' * M and places the result in the kept columns of an otherwise zero matrix.
In exact arithmetic this is the same matrix, so Artifact Subspace Reconstruction (ASR) output does not change where the old expression was sound.
It stops pinv from inverting the roundoff singular value of a rejected (zeroed) row, which with some LAPACK (Linear Algebra PACKage) builds lands just above the MATLAB cutoff and scales one update's reconstruction matrix by about 1e13.

The defect

Each rejected component zeroes one row of keep .* (V' * M), so with k of C components kept, C - k of its singular values are 0 in exact arithmetic.
In floating point the singular value decomposition (SVD) inside pinv returns them as roundoff of order C * eps(s_max), which is also pinv's cutoff, max(size(A)) * eps(norm(A)).
With NumPy 2.5.4 (its wheels bundle OpenBLAS 0.3.34), such a value sometimes lands just above the cutoff; pinv then inverts it, and that update's reconstruction matrix gains a factor of about 1e13.
With NumPy 2.2.6, 2.3.5 and 2.4.4 (OpenBLAS 0.3.29 to 0.3.31) and with Accelerate, we never saw that value above 0.3 times the cutoff, in at least 2,400 synthetic cases per build.

Measurement on a public dataset

Setting: eegprep 0.5.0 and NumPy 2.5.4 on Linux x86_64, clean_asr(cutoff=30, maxmem=1024) applied to the 240 recordings of the ERP CORE dataset of event-related potentials (Kappenman et al., 2021; 40 participants, 6 tasks, 27 to 29 channels after earlier cleaning steps).
On sub-001_task-MMN, one update of 537 keeps 26 of 27 components; the kept rows are well conditioned (singular values 28.8 to 1.89), but the zeroed row's singular value comes back as 1.02e-13, above the cutoff of 9.59e-14.
pinv inverts it: that update's reconstruction matrix has a 2-norm of 8.9e13, where every other update is at most 2.8, and over 123 samples (0.49 s) the output reaches 2.5e15 µV where the input peaks at 116 µV.
The output's covariance then has numerical rank 1, so an independent component analysis (ICA) that follows returns a single component.
Across the 240 recordings, 8 hit this (about 1 update in 7,450, in MMN, flankers, N170, N2pc and P3 recordings); the worst update of every other recording stays at or below 16.5.
Inverting the kept rows alone gives a 2-norm of 1.39 at the sub-001_task-MMN update, and 1.17 to 3.23 at the worst update of each of the 8 recordings.

Why the two forms are the same matrix

Let A = V' * M, and let S (k x C) select the kept rows, so keep .* A = S' * (S * A).
Because S' has orthonormal columns, pinv(S' * (S * A)) = pinv(S * A) * S: the pseudo-inverse of the kept rows, pinv(A(keep, :)), in the kept columns, with zero columns for the rejected rows.
The MATLAB cutoff is unchanged, since both matrices have C columns and the same largest singular value, so a kept component whose singular value falls below the cutoff is still dropped.
With every component kept the computation is the one before, and with none kept the result is all zeros, as before.
The new pinv call goes through finite_pinv, the pseudo-inverse counterpart of the finite_matmul guards the function already uses: on macOS, Accelerate raised spurious matmul warnings for the new, non-square argument.

Tests (tests/test_riemannian_asr.py)

  • test_reconstruction_ignores_the_singular_value_of_a_rejected_row, 64 seeds: 27 channels, one rejected component, and the 26 kept rows of V' * M with singular values in [31.8, 31.9], so pinv's cutoff is 9.59e-14. Every seed requires a 2-norm below 100, agreement with B' (B B')^-1 for the kept rows B to 1e-10 relative, and R @ V[:, ~keep] of about 0, so the rejected direction is removed.
  • The test runs on every BLAS build, but it fails before this change only with NumPy 2.5 (bundled OpenBLAS 0.3.34): there, 38 of the 64 seeds fail on develop, with 2-norms from 6.8e11 to 1.4e14. With NumPy 2.2.6 (the version in uv.lock, OpenBLAS 0.3.29) and with Accelerate, the zeroed row's singular value never reaches the cutoff, so the test passes on develop as well. With this change all 64 seeds pass on both NumPy versions.
  • test_reconstruction_matches_the_masked_pinv_when_pinv_drops_the_zeroed_rows, with 0, 1, 4, 9 and 27 of 27 components rejected: where M * pinv(keep .* (V' * M)) * V' drops every zeroed row, the new result equals it to 1e-12 relative.
  • Restoring the old expression fails 38 seeds of the first test with NumPy 2.5.4; inverting all rows of V' * M and keeping only the kept columns fails the second test on both NumPy versions.

Checks run

  • The suite as continuous integration (CI) runs it, with EEGPREP_SKIP_MATLAB=1 and without the gui and visual markers, on macOS arm64 with NumPy 2.2.6: this branch 3200 passed, 2 failed, 153 skipped; develop 3128 passed, 5 failed, 153 skipped. Every test that passes on develop passes here. Both failures also fail on develop (test_process_r_updates_final_sample_when_length_mod_step_is_one, and a spurious Accelerate matmul warning at asr_process_r.py line 127); three *_without_warning_noise tests that stopped on develop on the same warning from the old pinv call now pass.
  • ruff check ., ruff format --check ., ty check and ./pre-commit.py --changed-from origin/develop: pass.

Not run

  • The MATLAB parity tests (TestCleanASR, TestRiemannianASRMatlab and the MATLAB classes in test_pinv.py), as no MATLAB license was available to run them; CI's matlab-batch lane runs them. As a stand-in, the new output against the old on their inputs: at most 2.1e-7 relative per sample on EmotionValence.set (the test allows 1e-6 against MATLAB) and 2.9e-11 on the Riemannian signal (it allows 1e-8). On EmotionValence.set the old expression itself varies by up to 1.9e-6 across Accelerate, OpenBLAS 0.3.29 and OpenBLAS 0.3.34; the new one varies by at most 7.2e-8.
  • The EEGLAB Python backend lane and the Pyodide job.

Agentic AI tools were used. Workflows follow the Research Skills (doi:10.5281/zenodo.20696515). The author assumes full responsibility for this content and associated changes.

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

@claude

claude Bot commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @neuromechanist's task in 44s —— View job


Code review

  • Overall assessment: The fix looks correct. Because the rejected rows of keep .* (V' * M) are exactly zero, pinv(S'·S·A) = pinv(S·A)·S. The new inverse[:, keep] = pinv(A[keep]) therefore gives the same matrix as asr_process.m:176 and asr_process_r.m:188 in exact arithmetic. The MATLAB cutoff max(size) * eps(norm) is unchanged, since both matrices have C columns and the same top singular value. The 0-kept case still returns zeros: pinv of a (0, C) array returns (C, 0). The all-kept case matches the computation before this change. Both callers, asr_process.py:202 and asr_process_r.py:148, and the LinAlgError fallback are unaffected.
  • Highest-risk area: numerical drift against MATLAB in the ASR parity tests, which were not run (see Blocking).
  • Merge recommendation: Hold off merging until the MATLAB reference evidence is in the PR body. The code itself needs no changes.

Blocking

  • Required MATLAB reference run is missing from the PR body. This changes a core EEGLAB-ported processing function (plugins/clean_rawdata/private/riemann.py::asr_subspace_reconstruction), which both asr_process and asr_process_r call. AGENTS.md §Testing says: "Before merging a PR that changes core function implementations … trigger .github/workflows/eeglab-reference.yml … on the PR branch, or run the suite locally once on the final branch", and "Put that run in the PR description: the exact command or workflow run, the EEGLAB and eeglab_tests commits, pass/fail/skip counts, runtime…". The "Not run" section says the MATLAB parity tests were skipped and points to CI's matlab-batch lane, but that lane is not the required run. Your NumPy stand-in comparison (≤2.1e-7 relative on EmotionValence.set) is useful, but it does not replace that run.
    Fix: trigger eeglab-reference.yml via workflow_dispatch on fix/asr-reconstruction-kept-rows. Then add the run link, commits, counts and runtime to the description, with particular attention to TestCleanASR and TestRiemannianASRMatlab.

Important

None.

Nits

None.

Test gaps

None. test_reconstruction_ignores_the_singular_value_of_a_rejected_row computes the expected value independently with B' (B B')^-1, which is not tautological. It also checks the reconstruction norm and that the rejected direction is removed. The 0/1/4/9/27-rejected sweep against the masked pinv covers the equivalence claim, including the edges where none or all components are rejected.

EEGLAB parity notes

  • The masked-row pinv in asr_process.m:176 and asr_process_r.m:188 is replaced by a form that equals it in exact arithmetic. The docstring explains the deviation and the changelog records it. This fits the repo rule that EEGPrep does the mathematically sound thing where MATLAB's expression is fragile and documents the difference.

I checked correctness of the kept-row equivalence (cutoff, shapes, dtype, the 0-kept and all-kept edges), both callers, the finite_pinv usage against existing call sites, the test design, the changelog, and AGENTS.md compliance. I could not run the tests in this job: the Bash command needed approval.

@arnodelorme

Copy link
Copy Markdown
Collaborator

The MATLAB side of this fix is now sccn/clean_rawdata#52, for both asr_process.m and asr_process_r.m, with the variable renamed Rinv because P is the look-ahead length there. Please merge the two together, so that the repair-mode parity tests compare the same computation on both sides.

On the 13 recordings of sccn/eegprep_parity_test, this pull request leaves step 3 bit for bit unchanged (BurstRejection on), on Accelerate and on OpenBLAS 0.3.34 (Apple silicon build).

— orchestrator

@arnodelorme

Copy link
Copy Markdown
Collaborator

Merge advice asked by Arno on November 28, 2026, now that the MATLAB side (sccn/clean_rawdata#52) is merged.

  • Ready to merge. The two sides should not stay apart: clean_rawdata master already has the kept-rows form.
  • Parity: with this pull request and Add EEGLAB-style cart2topo, pop_reref, and pop_interp parity workflows #52, steps 2 and 3 of sccn/eegprep_parity_test give the same channel and sample counts as MATLAB R2025b on the 12 subjects of the table, with at most 7.1e-6 µV between the two (native arm64 Python). This was measured with the float64 average reference of develop. With the single precision one of Revert the float64 average reference of #606 to restore EEGLAB parity #833, it is 13 of 13 recordings and at most 1.4e-5 µV.
  • Windows check: the step "Run Python tests" also fails on the last completed runs of other branches, develop included (commit 163bbbd), so it does not come from this change. I could not read which test fails.
  • One small point, not blocking: inverse is created real with np.zeros, so a complex projected would lose its imaginary part at the assignment, where MATLAB's Rinv would turn complex before real(). The covariance square root and the eigenvectors are real here, so this cannot matter in practice.

— orchestrator

@neuromechanist
neuromechanist merged commit 4df5bbe into develop Nov 28, 2026
20 of 22 checks passed
@neuromechanist
neuromechanist deleted the fix/asr-reconstruction-kept-rows branch November 28, 2026 22:36
neuromechanist added a commit to nemarOrg/neuroschema that referenced this pull request Nov 29, 2026
Regenerated sensor-field and sensor-layout vectors with eegprep 4df5bbe8 (sccn/eegprep#832); every value is bit-identical, only /reference/commit changes. CI runs on release/** pull requests.
neuromechanist added a commit to nemarOrg/nemar-cli that referenced this pull request Nov 29, 2026
nemar-process #123 (FX3) pins eegprep at 4df5bbe8 (sccn/eegprep#832, the ASR fix); RECIPE_ENGINE follows, recipe versions unchanged (1.0.0-b2). Vendors neuroschema v0.6.2, whose sensor vectors were regenerated at that commit (bit-identical values; only the reference commit changed). Owner step before the release: repin COMPUTE_RUNTIME_IMAGE to an image built with the new pin. Tested: drift test against nemar-process dev, build-vendor --check, contract and compute suites.
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.

2 participants