Skip to content

ASR can catastrophically amplify signals because np.linalg.pinv uses an insufficient rank tolerance #306

Closed

Description

@kevinavrilla-habs

Description

asr_process() can produce extremely large but finite reconstruction matrices when computing the pseudoinverse of the intentionally rank-deficient matrix Q.

In my case, the maximum absolute value of the reconstruction matrix suddenly reached approximately 3 × 10^13, resulting in EEG amplitudes up to approximately 10^17.

The problem appears to come from using NumPy's default pseudoinverse tolerance:

Z = np.linalg.pinv(Q)

or, in EEGPrep 0.3.0:

Z = finite_pinv(Q)

finite_pinv() ultimately calls np.linalg.pinv(Q) without specifying rcond, so NumPy uses its fixed default relative cutoff of 1e-15.

Environment

  • EEGPrep: 0.3.0
  • Python: 3.12.10
  • NumPy: 2.5.2
  • SciPy: 1.18.0
  • OS: Windows 11
  • Channels: 62
  • Samples: 4,739,276
  • Sampling rate: approximately 1000.011 Hz

Relevant ASR settings:

cutoff = 10.0
window_len = 0.5
lookahead = 0.25
step_size = 250
max_dims = 0.65  # The issue also occurred with 0.66
max_mem = 16000

Automatic calibration settings:

max_bad_channels = 0.075
zthresholds = (-np.inf, 5.5)
window_len = 1.0

Observed behavior

I added diagnostics around the reconstruction calculation:

Z = finite_pinv(Q)
R = np.real(finite_matmul(finite_matmul(M, Z), V.T))

singular_values = np.linalg.svd(Q, compute_uv=False)
pinv_cutoff = 1e-15 * singular_values[0]
retained = singular_values[singular_values > pinv_cutoff]

smallest_retained = retained[-1] if retained.size else 0.0
effective_condition = (
    singular_values[0] / smallest_retained
    if smallest_retained > 0
    else np.inf
)

logger.debug(
    "sample=%d time=%.3fs rejected=%d pinv_rank=%d "
    "smax=%.6e smin_retained=%.6e condition=%.6e "
    "max|Z|=%.6e max|R|=%.6e",
    sample_index,
    time_seconds,
    int(np.count_nonzero(~keep)),
    retained.size,
    singular_values[0],
    smallest_retained,
    effective_condition,
    np.max(np.abs(Z)),
    np.max(np.abs(R)),
)

The updates immediately preceding the failure were:

sample=213121 time=213.119s rejected=1 pinv_rank=61
smax=4.406669e+01 smin_retained=1.460547e+00
condition=3.017136e+01 max|Z|=2.746124e-01 max|R|=1.284169e+00

sample=213371 time=213.369s rejected=1 pinv_rank=61
smax=4.497851e+01 smin_retained=1.453209e+00
condition=3.095117e+01 max|Z|=3.005848e-01 max|R|=1.250325e+00

sample=214871 time=214.869s rejected=1 pinv_rank=61
smax=4.097472e+01 smin_retained=1.464354e+00
condition=2.798143e+01 max|Z|=2.749367e-01 max|R|=1.599294e+00

sample=215121 time=215.119s rejected=3 pinv_rank=59
smax=3.597073e+01 smin_retained=1.464285e+00
condition=2.456538e+01 max|Z|=2.314408e-01 max|R|=1.505436e+00

sample=215371 time=215.369s rejected=1 pinv_rank=61
smax=4.511252e+01 smin_retained=1.421342e+00
condition=3.173939e+01 max|Z|=5.123772e+12 max|R|=3.000218e+13

The reconstruction therefore changed abruptly from values around 1 to approximately 10^13, even though the diagnostic nonzero singular values remained well-conditioned.

Analysis

When one component is rejected, the masking operation intentionally gives Q a zero row:

keep_mask = keep[np.newaxis, :]
A = V.T @ M
masked_A_T = keep_mask * A.T
Q = masked_A_T.T

Therefore, with 62 channels and one rejected component, the mathematical rank of Q cannot exceed 61.

However, an SVD can represent the theoretically zero singular value as a small numerical value around machine precision.

NumPy uses the following default cutoff:

1e-15 * largest_singular_value

For the failing update, this was approximately:

1e-15 × 45.11 ≈ 4.5e-14

If the numerical representation of the theoretically zero singular value is slightly above this cutoff—for example around 10^-13—NumPy may invert it, producing values around:

1 / 10^-13 ≈ 10^13

This is consistent with the observed max|Z|.

The diagnostic rank was computed through a separate SVD call. That SVD classified the numerical null direction as zero, while the magnitude of Z indicates that the SVD performed internally by np.linalg.pinv() included a numerical-null direction.

This rank decision is highly discontinuous: a very small floating-point difference around the cutoff can change the result from a normal reconstruction matrix to one with coefficients around 10^13.

Tested correction

I replaced the default pseudoinverse with a dimension-aware relative tolerance:

rcond = max(Q.shape) * np.finfo(Q.dtype).eps
Z = np.linalg.pinv(Q, rcond=rcond)

For a 62 × 62 float64 matrix:

rcond ≈ 62 × 2.22e-16 ≈ 1.38e-14

At the failing update, this corresponds to an absolute cutoff of approximately:

1.38e-14 × 45.11 ≈ 6.2e-13

This correctly removes the numerical null direction.

With this change:

  • the catastrophic amplification disappears;
  • the complete ASR processing finishes successfully;
  • the EEGPrep 0.3.0 output reproduces my previous EEGPrep 0.2.23 output;
  • across 310 channel/segment RMSE measurements, the maximum difference between the corrected 0.3.0 result and the previous 0.2.23 result is only approximately 1.18e-12.

I also tested EEGPrep 0.3.0 using externally computed ASR spectral-filter coefficients matching those used previously. The divergence still occurred with NumPy's default pseudoinverse and disappeared after using the dimension-aware tolerance. Therefore, the issue does not appear to originate from the new Yule–Walker filter implementation.

Comparison with SciPy and MATLAB

SciPy's pseudoinverse uses a dimension-aware relative tolerance by default:

max(M, N) * eps

Documentation:

https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.pinv.html

MATLAB uses the absolute tolerance:

max(size(A)) * eps(norm(A))

Documentation:

https://www.mathworks.com/help/matlab/ref/pinv.html

NumPy instead defaults to a fixed relative cutoff of 1e-15:

https://numpy.org/doc/2.5/reference/generated/numpy.linalg.pinv.html

Since EEGPrep aims to reproduce the MATLAB ASR implementation, using a MATLAB-compatible tolerance—or at least SciPy's dimension-aware default—would appear more appropriate than NumPy's fixed default.

Possible fixes

One possible correction is:

rcond = max(Q.shape) * np.finfo(Q.dtype).eps
Z = np.linalg.pinv(Q, rcond=rcond)

Alternatively:

from scipy import linalg

Z = linalg.pinv(Q)

SciPy's default tolerance already uses max(M, N) * eps.

For maximum MATLAB compatibility, EEGPrep could explicitly translate MATLAB's absolute tolerance:

singular_values = np.linalg.svd(Q, compute_uv=False)
largest = singular_values[0]

absolute_tolerance = max(Q.shape) * np.spacing(largest)
relative_tolerance = absolute_tolerance / largest

Z = np.linalg.pinv(Q, rcond=relative_tolerance)

The maintainers may wish to decide which tolerance most closely matches MATLAB across supported platforms.

Expected behavior

ASR should treat the deliberately removed directions in Q as numerical null directions and should not invert floating-point residuals associated with those directions.

The reconstruction matrix should not acquire coefficients around 10^13 and silently generate extremely large but finite EEG values.

Regression test suggestion

A regression test could construct an ASR-like rank-deficient Q containing:

  • normal singular values comparable to those observed here;
  • one or more deliberately removed dimensions;
  • a numerical residual around 10^-13.

The test should verify that:

  1. the effective rank matches the number of retained components;
  2. the numerical-null singular values are not inverted;
  3. Z and R remain bounded and finite;
  4. the result follows MATLAB's pseudoinverse tolerance closely.

Additional note about EEGPrep 0.2.23

EEGPrep 0.2.23 also called np.linalg.pinv(Q) without an explicit tolerance, so the underlying numerical risk was already present.

It did not trigger for my previous processing because the corresponding numerical singular value apparently remained below NumPy's cutoff. Small upstream floating-point differences in calibration or processing can move a numerical-null singular value across that threshold.

Therefore, this appears to be a latent numerical-stability issue rather than a problem exclusive to the new spectral-filter implementation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions