Skip to content

Export headless spectrum summaries - #603

Merged
suraj-ranganath merged 6 commits into
developfrom
cursor/public-spectrum-summaries-ab6b
Nov 18, 2026
Merged

suraj-ranganath merged 6 commits into
developfrom
cursor/public-spectrum-summaries-ab6b

Conversation

@suraj-ranganath

Copy link
Copy Markdown
Member

Move the Welch estimator out of the plotting module and export it as compute_spectra, without a second implementation. line_noise_excess_db and channel_robust_amplitude report neighboring-bin excess and a normal-scaled MAD amplitude. spectopo's numeric output is unchanged.

MATLAB is not available in this environment, so MATLAB-backed tests, including tests/test_spectopo_parity.py and the EEGLAB reference suite, were not run.

Fixes #536

Open in Web Open in Cursor 

Move the Welch estimator out of the plotting module so it can be imported
without Matplotlib, and add line-noise excess and normal-scaled MAD helpers.
Keep spectopo's numeric output identical.

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:36
@suraj-ranganath
suraj-ranganath marked this pull request as ready for review November 11, 2026 18:37
@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.

…trum-summaries-ab6b

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

# Conflicts:
#	docs/source/changelog.rst
@suraj-ranganath
suraj-ranganath marked this pull request as draft November 18, 2026 09:32
@suraj-ranganath
suraj-ranganath marked this pull request as ready for review November 18, 2026 09:32
@claude

claude Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

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


Code review

  • Overall assessment: Mostly ready. The new estimator is the old one moved without changes (only the docstring was rewritten), every caller now imports from the new module, and the new helpers match issue Public spectrum summary and line-noise magnitude helpers #536. The one problem is a test that will fail when NumPy or SciPy change the last bits of their output.

  • Highest-risk area: tests/test_spectra_summaries.py, which checks hashes of raw float bytes.

  • Merge recommendation: Needs changes (one small test fix).

  • Pre-review gate: PR is open and not a draft, there is no earlier review, and the checked-out commit matches the PR head 20373f3.

  • Read the diff, issue Public spectrum summary and line-noise magnitude helpers #536, the callers and the tests

  • Review passes: AGENTS.md compliance, conventions, correctness, EEGLAB parity

  • Post review

Blocking

None.

Important

  • tests/test_spectra_summaries.py:37-103: the test hashes float output. It takes SHA-256 hashes of spectopo's spectra and frequency arrays. A tiny floating-point change from a NumPy or SciPy upgrade, or from running on a different platform, will fail the test even when the numbers are effectively the same. The same loop already asserts np.array_equal(spectra, direct) and spectopo_compute_spectra is compute_spectra, and those two checks are enough to catch spectopo drifting from the estimator. Fix: remove _FROZEN and _digest, or switch to assert_allclose on a few stored values. Details are in the inline comment.

Nits

  • tests/test_spectra_summaries.py:307-318: test_package_root_exports_the_numerical_functions only checks that names refer to the same objects. AGENTS.md says not to write tautological tests. The subprocess test at :280 already imports the three functions from eegprep and calls them, so this test can go. It also uses imports inside the function, while AGENTS.md says "All imports go at the top."

Test gaps

None. The new tests cover:

  • the 1 Hz grid and the density scaling
  • averaging the neighbor bins in dB rather than in linear power
  • the column-major order when epochs are concatenated in a 2-D array
  • the errors for frequencies above Nyquist, frequencies off the grid, and neighbor windows that leave the grid
  • NaN propagation in the MAD amplitude, and leaving the dataset unchanged
  • importing without Matplotlib

EEGLAB parity notes

None. The body of compute_spectra is the same as before the move, so spectopo, pop_prop, std_precomp and the ICLabel property numbers are unchanged. line_noise_excess_db and channel_robust_amplitude are new and have no EEGLAB counterpart. No numbers changed, so the EEGLAB reference run looks optional for this PR. A maintainer should confirm that.

Other things I checked

  • Lazy sigprocfunc/__init__.py: This is needed for the "no Matplotlib on import" claim, because importing sigprocfunc.spectra runs the package __init__ first, and that __init__ used to import headplot. Existing imports such as from eegprep.functions.sigprocfunc import erpimage still work, because Python falls back to importing the submodule when __getattr__ raises AttributeError.
  • miscfunc.misc.round_mat: Only imports NumPy and the standard library, so it does not pull in Matplotlib.
  • Old import paths: tests/test_pop_prop.py still imports compute_spectra from spectopo. That keeps working because spectopo re-imports the name.

I could not run pytest here because the command needed approval that this job doesn't have. CI "Tests" was still running when I wrote this; the docs build passed.

Comment thread tests/test_spectra_summaries.py Outdated
Comment on lines +37 to +103
# Digests of spectopo's spectra and frequency grids for _reference_signal.
_FROZEN = {
"default": (
"43acecdc43b1b1c89306565ad8f55a9f91405e511460ced27cd7d64fa1f12d3b",
"a2c297b161f5e61a7e16c45d19feb53ec8f2ae0103d1a97d7c91756ccfccba51",
(2, 65),
{},
),
"percent": (
"d14b6db8886cd0e1aa4be4626ef3de5fdcefce24bf856fce7207774a31f51c41",
"a2c297b161f5e61a7e16c45d19feb53ec8f2ae0103d1a97d7c91756ccfccba51",
(2, 65),
{"percent": 50},
),
"overlap": (
"402138c32b745057b68a9e4e434c51536dd9a4694d146084ed3ff5eb30778393",
"9287e14778ee197dd339ad57e60da907f264a23d5f074d4d284919838f48ded3",
(2, 33),
{"overlap": 32, "winsize": 64},
),
"blackman": (
"b311d13d3bf6fe5ab321433c06b58c07a009b9f2c6daf327aa33d709346d1353",
"9287e14778ee197dd339ad57e60da907f264a23d5f074d4d284919838f48ded3",
(2, 33),
{"wintype": "blackmanharris"},
),
"nfft": (
"feb6c9d9049241199b388d5710517beb00098087508f92ebd87c472afd5cc928",
"fd9a0ed0205cc3c1ac8223db9278715bb7349d63bf093fb76a18d502ac105b3b",
(2, 129),
{"nfft": 256, "winsize": 64},
),
"epochs": (
"6014d735b83bf8114f9b44ac4a3abfd9db26c191603908cd7c74d1972018fa64",
"9287e14778ee197dd339ad57e60da907f264a23d5f074d4d284919838f48ded3",
(2, 33),
{},
),
"concat": (
"35185bca7611e8a9a383bb44b75c84a86ba911676b16296cb11aa132d485cb85",
"9287e14778ee197dd339ad57e60da907f264a23d5f074d4d284919838f48ded3",
(2, 33),
{},
),
}


def _digest(values: np.ndarray) -> str:
return hashlib.sha256(np.ascontiguousarray(values).tobytes()).hexdigest()


def test_spectopo_numeric_output_matches_the_moved_estimator():
data, pnts, srate = _reference_signal()
epochs = data.reshape(2, 64, 4)
inputs = {"epochs": (epochs, 64), "concat": (data, 64)}
for name, (spectra_hash, frequency_hash, shape, kwargs) in _FROZEN.items():
array, frames = inputs.get(name, (data, pnts))
spectra, freqs, first, second, specstd, figure = spectopo(array, frames, srate, plot="off", **kwargs)
direct, direct_freqs, direct_std = compute_spectra(array, frames, srate, **kwargs)
assert spectra.shape == shape
assert _digest(spectra) == spectra_hash
assert _digest(freqs) == frequency_hash
assert np.array_equal(spectra, direct)
assert np.array_equal(freqs, direct_freqs)
assert spectopo_compute_spectra is compute_spectra
assert specstd is None and direct_std is None
assert first is None and second is None and figure is None

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 (test brittleness): These SHA-256 digests hash the raw float bytes of spectopo output. Any last-bit change from a NumPy or SciPy upgrade (for example to pocketfft or get_window), or from platform FMA/SIMD differences, will make this test fail even when the spectra are numerically identical. AGENTS.md asks for tests of behavior, and tests/test_spectopo_parity.py already checks the numbers against MATLAB.

The regression this test is meant to catch, spectopo drifting from the moved estimator, is already caught by np.array_equal(spectra, direct) together with spectopo_compute_spectra is compute_spectra, both in this same loop. The current hash values also only show that the move kept results byte-identical in one environment, which the reviewer can check once from the diff.

Suggested fix: remove the _FROZEN digests and _digest, and keep the loop over the kwargs cases with the array_equal and identity assertions. If a value-level freeze is still wanted, store a few rounded spectrum values and compare them with np.testing.assert_allclose(..., rtol=1e-12) instead of hashing bytes.

spectopo and compute_spectra share one estimator, so the cases that were
frozen as SHA-256 digests now require exact array equality. Hypothesis
integer draws include literals from modules the sigprocfunc package used
to import on load. The fuzz harness imports those modules before drawing
so the golden cases stay on that set.

Co-authored-by: Suraj Ranganath <[email protected]>
@suraj-ranganath
suraj-ranganath marked this pull request as draft November 18, 2026 10:31
@suraj-ranganath
suraj-ranganath marked this pull request as ready for review November 18, 2026 10:31
@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

  • Pre-review gate: the PR is open and not a draft, no earlier comment carries the review marker, and HEAD matches the PR head 36475ed

  • Read the diff, the callers, and the commit added since the last review

  • Review passes: AGENTS.md compliance, conventions, correctness, EEGLAB parity

  • Post review

  • Overall assessment: Needs changes. The hash-based test from the last review is fixed: 36475ed removes the SHA-256 checks and keeps the array_equal and identity checks. compute_spectra was moved without changing its body. The new helpers do what issue Public spectrum summary and line-noise magnitude helpers #536 asks. One import regression remains.

  • Highest-risk area: the lazy src/eegprep/functions/sigprocfunc/__init__.py.

  • Merge recommendation: Needs changes.

Blocking

None.

Important

  • sigprocfunc/__init__.py:34-41: the lazy re-exports can return the submodule instead of the function. Each of the 18 lazy names is the same as its submodule's name. Importing a submodule directly makes Python set package.<name> to that module, and after that the package __getattr__ is never called.
    • EEGPrep imports these submodules directly in pop_biosig, pop_chanedit, pop_writeeeg, pop_headplot and eegmovie, and eegprep.cbar does the same. So import eegprep.functions.popfunc.pop_biosig; from eegprep.functions.sigprocfunc import readbdf now gives a module, and calling it raises TypeError: 'module' object is not callable.
    • Before this PR, these imports always returned the function.
    • The subprocess test misses this because it imports cbar in a fresh process, before any submodule is loaded.
    • Fix: nothing in src/ or tests/ uses these package-level aliases. Make __init__.py contain only its docstring (AGENTS.md: "No backward compatibility by default"), note the change in the changelog, and import cbar from its submodule in the test. Details are in the inline comment.

Nits

  • tests/test_spectra_summaries.py:265-276: this was raised in the last review and is still there. test_package_root_exports_the_numerical_functions only checks that names refer to the same objects, and it imports inside the function. AGENTS.md says not to write "tautological tests that only assert types, constants, or implementation details", and "All imports go at the top." The subprocess test at :238 already imports all three functions from eegprep and calls them, so this test can be removed.
  • tests/fuzz/harness.py:64-85: _SIGPROC_CONSTANT_MODULES repeats the 18 module paths from sigprocfunc._LAZY_EXPORTS by hand, only to keep Hypothesis's pool of integer constants the same. If the __init__ fix above empties that package, this list becomes the only record of which modules to import. Leave a pointer to it, or seed the fuzz runs in a way that does not depend on which modules are loaded.

Test gaps

None beyond the import-order case above. A test for it: after import eegprep.functions.popfunc.pop_biosig, check what from eegprep.functions.sigprocfunc import readbdf returns. With the suggested fix that test is no longer needed.

EEGLAB parity notes

None. The body of compute_spectra is the same as before the move, so the numbers from spectopo, pop_prop, std_precomp and ICLabel do not change. line_noise_excess_db and channel_robust_amplitude are new and have no EEGLAB counterpart.

I could not run pytest, the Python import check, or gh pr checks in this job because those commands needed approval. The submodule behavior above comes from how Python's import system works, not from a run.

Comment on lines +34 to +41
def __getattr__(name: str) -> Any:
try:
module_name, attr_name = _LAZY_EXPORTS[name]
except KeyError as exc:
raise AttributeError(f"module {__name__!r} has no attribute {name!r}") from exc
value = getattr(import_module(module_name), attr_name)
globals()[name] = value
return value

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 (regression): the lazy re-exports can return the submodule instead of the function. Each of the 18 names has the same name as its submodule (readbdf/readbdf, headplot/headplot, …). When anything imports the submodule directly, Python's import system runs setattr(package, "readbdf", <module>), and from then on module __getattr__ is never consulted. EEGPrep does that itself: pop_biosig.py:16-17 imports sigprocfunc.openbdf/readbdf, pop_chanedit.py:26 imports forcelocs, pop_writeeeg.py:17 imports writegdf, and pop_headplot.py/eegmovie.py import headplot. The root lazy export eegprep.cbar does it too.

Failure scenario:

import eegprep.functions.popfunc.pop_biosig
from eegprep.functions.sigprocfunc import readbdf
readbdf(...)  # TypeError: 'module' object is not callable

Before this PR, from .readbdf import readbdf rebound the package attribute to the function after the submodule loaded, so this always returned the function. test_numerical_imports_do_not_load_matplotlib misses it because it imports cbar in a fresh process before anything else has loaded the submodule.

Suggested fix: nothing in src/ or tests/ uses these package-level function aliases; the public names come from eegprep.<name>. Under AGENTS.md ("No backward compatibility by default"), the simplest fix is to make sigprocfunc/__init__.py contain only its docstring, add a changelog note, and change the subprocess test to import from eegprep.functions.sigprocfunc.cbar import cbar. If the aliases must stay, __getattr__ alone cannot keep them working; the helpers would have to be bound eagerly without importing Matplotlib.

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.

Agreed. This is a real regression from the eager aliases, so I am holding the merge until __init__.py is reduced to its docstring (plus a changelog note) or the functions are bound in a way that survives a direct submodule import.

…ment.

Hypothesis 6.169 has no supported way to disable or pin local-constant
collection, and clearing it changes the golden draws. The sigproc modules
stay imported before the draw, under a name that says why.

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

claude Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

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


Code review

  • Pre-review gate: the PR is open and not a draft, no earlier comment carries the review marker, and HEAD matches the PR head 04c06b4

  • Read the commit added since the last review (04c06b4) and checked whether the earlier findings are still there

  • Review passes: AGENTS.md compliance, conventions, correctness, EEGLAB parity

  • Post review

  • Overall assessment: Needs changes. 04c06b4 only renames the Hypothesis pre-import tuple in tests/fuzz/harness.py and drops its comment. It does not touch the import regression in sigprocfunc/__init__.py from the last review. compute_spectra is still a move with no change to its body, and the new helpers still do what issue Public spectrum summary and line-noise magnitude helpers #536 asks.

  • Highest-risk area: the lazy src/eegprep/functions/sigprocfunc/__init__.py.

  • Merge recommendation: Needs changes.

Blocking

None.

Important

  • sigprocfunc/__init__.py:10-41: the lazy re-exports can return a submodule instead of a function. This is still not fixed.
    • Each of the 18 lazy names is the same as the name of its submodule. When code imports a submodule directly, Python binds package.<name> to that module, and the package __getattr__ is never called for that name again.
    • EEGPrep itself imports these submodules directly:
      • pop_biosig.py:16-17 imports openbdf and readbdf
      • pop_chanedit.py:26 imports forcelocs
      • eegmovie.py:17 imports headplot
    • So after import eegprep.functions.popfunc.pop_biosig, from eegprep.functions.sigprocfunc import readbdf gives the module. Calling it raises TypeError: 'module' object is not callable. Before this PR, the eager from .readbdf import readbdf always bound the function.
    • Fix: nothing in src/ or tests/ uses these package-level aliases. Reduce __init__.py to its docstring (AGENTS.md: "No backward compatibility by default"), add a changelog note, and import cbar from eegprep.functions.sigprocfunc.cbar in the subprocess test. With the package __init__ empty, the Matplotlib-free import still works.
    • Fix this →

Nits

  • tests/test_spectra_summaries.py:265: this has been raised twice and is still there. test_package_root_exports_the_numerical_functions only checks that names refer to the same objects, and it imports inside the function. AGENTS.md says not to write "tautological tests that only assert types, constants, or implementation details", and "All imports go at the top." The subprocess test at :238 already imports the three functions from eegprep and calls them, so this test can go.

Test gaps

None beyond the import-order case above. With the suggested fix that case cannot happen, so it needs no test.

EEGLAB parity notes

None. The body of compute_spectra is the same as before the move, so the numbers from spectopo, pop_prop, std_precomp and ICLabel do not change. line_noise_excess_db and channel_robust_amplitude are new and have no EEGLAB counterpart.

I could not run the Python import check in this job because uv run needs approval. The submodule finding comes from how Python's import system works and from the direct imports quoted above, not from a run. The inline comment from the last review on __init__.py:41 still applies, so I did not post a duplicate.

Copy link
Copy Markdown
Member Author

The pre-import of sigprocfunc modules in tests/fuzz/harness.py is accepted. Hypothesis 6.169 has no opt-out for local-constant collection, and re-recording the golden draws is Suraj's call.

The lazy re-export point is valid, and I am holding the merge on this head. After a direct submodule import such as from eegprep.functions.sigprocfunc.readbdf import readbdf in pop_biosig, from eegprep.functions.sigprocfunc import readbdf binds the module, and a later call raises TypeError. Develop's eager aliases always bound the function. Emptying __init__.py down to its docstring, with a changelog note, is the right fix. That change does not touch spectra numbers or the golden draws.

The tautological package-root export test is a nit.

Importing a same-named submodule binds the module on the package and hides
a lazy __getattr__ export. Lookup returns the exported function either way.

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

claude Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

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


Code review

  • Pre-review gate: the PR is open and not a draft, and HEAD matches the PR head 4103b97

  • Read the new commit 4103b97 and checked the earlier findings against it

  • Review passes: AGENTS.md compliance, conventions, correctness, EEGLAB parity

  • Post review

  • Overall assessment: Safe to merge, once the maintainer approves. 4103b97 fixes the lazy re-export problem from the last two reviews. The fix takes the second option the maintainer accepted, binding the functions in a way that survives a direct submodule import, rather than emptying __init__.py.

  • Highest-risk area: the module class swap in src/eegprep/functions/sigprocfunc/__init__.py.

  • Merge recommendation: Safe to merge.

Blocking

None.

Important

None.

  • Package-level readbdf returns the function. _SigProcFuncModule.__getattribute__ checks _LAZY_EXPORTS before the module's normal attribute lookup. So a submodule that Python's import system bound onto the package with setattr(package, "readbdf", <module>) no longer hides the function. After pop_biosig imports sigprocfunc.readbdf, from eegprep.functions.sigprocfunc import readbdf returns the function again.
  • Other import forms (checked by reading the code):
    • from eegprep.functions.sigprocfunc.headplot import HeadplotMesh and similar imports bring in the submodule itself, so they still work.
    • mock.patch("eegprep.functions.sigprocfunc.readbdf.x") resolves the path through pkgutil.resolve_name, which imports the submodule, so it still works.
    • import eegprep.functions.sigprocfunc.readbdf as m gives the function. The eager aliases on develop also gave the function here, so this did not change.
  • Test: test_sigprocfunc_exports_are_functions_in_either_import_order runs both import orders in a fresh subprocess, so it covers the failure case.

Nits

  • tests/test_spectra_summaries.py:290-301: This has been raised before, and the maintainer called it a nit. test_package_root_exports_the_numerical_functions only checks that names refer to the same objects, and it imports inside the function. The subprocess test at :238 already imports and calls all three functions from eegprep. You can drop it or keep it.

Test gaps

None.

EEGLAB parity notes

None. The body of compute_spectra is unchanged, so the numbers from spectopo, pop_prop, std_precomp and ICLabel stay the same. line_noise_excess_db and channel_robust_amplitude are new and have no EEGLAB counterpart.

I couldn't run anything in this job because uv run python and gh pr checks needed approval. I didn't run the import probe or pytest, and I didn't check CI. The import-form conclusions above come from reading the code.

…trum-summaries-ab6b

Drop the sigprocfunc pre-import. The draw generator from #640 no longer
reads Hypothesis local constants, and the golden draws still match.

Co-authored-by: Suraj Ranganath <[email protected]>
@suraj-ranganath
suraj-ranganath merged commit ec6ad7c into develop Nov 18, 2026
22 of 23 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.

Public spectrum summary and line-noise magnitude helpers

2 participants