Skip to content

Fix the resampling ratio for non-integer sampling rates, and drop sympy - #397

Merged
neuromechanist merged 2 commits into
developfrom
fix/396-resample-ratio
Sep 20, 2026
Merged

neuromechanist merged 2 commits into
developfrom
fix/396-resample-ratio

Conversation

@neuromechanist

@neuromechanist neuromechanist commented Sep 20, 2026 •

Copy link
Copy Markdown
Member

Fixes #396. Found while auditing the base dependencies for browser installability (#395); the dependency question turned out to be the smaller half.

The defect

EEGLAB computes the resampling ratio as rat(freq/EEG.srate, 1e-12) (pop_resample.m line 119, with a looser 0.0001 on the line above it commented "not used right now"). That was ported as sympy.nsimplify, which is a different function: it looks for a simple symbolic expression rather than a rational one, and returns an irrational when no simple fraction is close enough. as_numer_denom then hands back a numerator that is not an integer, and int() truncates it silently.

2000 Hz -> 999.9 Hz   nsimplify -> 2**(222/367)*3**(8/367)*5**(270/367)*7**(31/367)/12
                      p = 5.9994 (symbolic), q = 12  ->  int() -> 5/12 = 0.4167
                      true ratio 0.49995             ->  16.66 percent low

p and q drive both the polyphase resampling and the event-latency rescaling, while the output is stamped with the rate that was requested whatever the ratio turned out to be. The data was resampled by the wrong factor and labeled correctly, and because the latencies were rescaled by the same wrong ratio the result stayed internally consistent, leaving nothing for a reader to notice.

Sweeping realistic downsampling pairs, 24 of 86 returned a wrong ratio; every one had a fractional source rate and every whole-number pair was exact. The worst asked for 128 Hz from a 512.03 Hz recording and produced 117.04 Hz, labeled 128 Hz.

The fix

_rational_within expands the continued fraction for the value one term at a time and stops at the first convergent inside the tolerance. That is what rat does, the result is a ratio by construction so the truncation cannot happen, and it returns the smallest denominator that will do.

The smallest denominator matters beyond tidiness, which is the review's doing: an earlier draft searched by doubling a denominator cap and handing the result to Fraction.limit_denominator, which can overshoot the minimal answer, and every unnecessary unit of denominator is paid for in filter taps (see below).

It reproduces the old answers exactly on every whole-number pair (250/1000 -> 1/4, 44100/48000 -> 147/160, 1000/1024 -> 125/128, ...), which test_whole_number_rates_are_unchanged pins, and it is exact where the old code was wrong: 999.9/2000 -> 9999/20000, 1023.4/2000 -> 5117/10000. Worst relative error across the table is 2.8e-17 against a 1e-12 tolerance.

The cost of being right, and the warning that goes with it

Being exact means an exact denominator. 128 Hz from 512.03 Hz is 12800/51203, and _resample_poly_segment sets its filter transition width to df / max(p, q), so that builds a filter of roughly 1.64 million taps; measured, it costs about 3 seconds per minute of 64-channel data against 0.044 seconds for a whole-number pair of the same magnitude.

That cost is EEGLAB's, inherited with its 1e-12 tolerance, and it is correct rather than a defect: MATLAB builds a comparable filter for the same recording. This pull request keeps the upstream tolerance rather than quietly choosing a different one, and RATIO_TOLERANCE is the one line to change if you would rather trade rate accuracy for a bounded filter. What it adds is a log warning when the denominator is large, so that a resample which appears to hang has a visible reason.

Testing

  • The ratio tests fail 28 subtests against the previous implementation.
  • test_a_fractional_rate_resamples_through_the_whole_pipeline drives pop_resample itself at a fractional source rate and fails against the previous implementation too, computing 21/84 where the correct ratio is 2560/9999. An earlier draft had only whole-number end-to-end coverage, which passed against the defect and was therefore worthless as a guard; the review caught that.
  • Full offline suite with sympy absent from the environment: 2710 passed, 1 pre-existing unrelated failure (test_public_api_examples.py::test_user_guide_example_runs[plot_reject_artifacts.py] needs the torch extra, not installed there).

Dropping sympy

The nsimplify above was its only use anywhere in src/. Verified by running the suite with sympy absent from the environment, not merely absent from pyproject.toml. That distinction is not pedantic: an earlier revision of this pull request also dropped eeglabio, which likewise has no import site in src/, and 12 tests failed on every platform because mne imports it when asked to write an EEGLAB file and eeg_mne2eeg exports through mne. eeglabio is restored and untouched here; the audit in #395 is corrected.

The uv.lock edit removes the two lines naming sympy in eegprep's own dependency lists, scoped to eegprep's package block. An earlier draft used an unscoped replace and took torch's sympy edge with it, orphaning the package entry. uv lock --check still passed, because the lock remained self-consistent, and no CI job installs the torch extra with --locked, so nothing would have caught it. Also caught by the review. A full uv lock produces the correct edges too, but rewrites a few hundred unrelated lines in my environment (a reviewer saw no churn in theirs, so treat that as environment-dependent rather than a claim about uv); the scoped edit is a 2-line diff and uv sync --locked accepts it.

_resample_ratio is byte-identical on develop and epic/324-pyodide-browser, so this lands on develop without touching the open epic.

@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, reopen this pull request to trigger a review.

@claude

claude Bot commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

Claude encountered an error after 0s —— View job


I'll analyze this and get back to you.

@neuromechanist
neuromechanist force-pushed the fix/396-resample-ratio branch 2 times, most recently from 8b1899a to c4b8bb2 Compare September 20, 2026 16:57
@neuromechanist neuromechanist changed the title Fix the resampling ratio for non-integer sampling rates, and drop two unused dependencies Fix the resampling ratio for non-integer sampling rates, and drop sympy Sep 20, 2026
EEGLAB computes the ratio as rat(freq/EEG.srate, 1e-12), pop_resample.m
line 119. This was ported as sympy.nsimplify, which is a different
function: it looks for a simple symbolic expression rather than a
rational one, and returns an irrational when no simple fraction is close
enough. as_numer_denom then hands back a numerator that is not an
integer and int() truncates it silently.

A 2000 Hz recording resampled to 999.9 Hz was therefore resampled by
5/12 instead of 9999/20000, a 16.7 percent error, while the output was
stamped with the rate that was asked for. The event latencies were
rescaled by the same wrong ratio, so the result stayed internally
consistent and gave the reader nothing to notice. Across realistic
downsampling pairs, 24 of 86 came back wrong, all of them with a
fractional source rate; the worst produced 117.04 Hz labeled 128 Hz.

_rational_within expands the continued fraction one term at a time and
stops at the first convergent inside the tolerance, which is what rat
does and which returns the smallest denominator that will do. That
matters beyond tidiness, because the denominator sets the anti-aliasing
filter length: an earlier draft searched by doubling a denominator cap,
which can overshoot the minimal answer and buy filter taps for nothing.

The ratio tests fail 28 subtests against the previous implementation,
and the end-to-end test added here fails against it too, computing
21/84 where the correct ratio is 2560/9999. An earlier draft of that
test used whole-number rates only and passed against the defect, which
made it worthless as a guard.

Also logs a warning when the ratio's denominator is large. 128 Hz from a
512.03 Hz recording is 12800/51203, which builds a filter of about 1.64
million taps and costs seconds per minute of 64-channel data against
milliseconds for a whole-number pair. That cost is EEGLAB's, inherited
with its tolerance, and correct rather than a defect, but a resample
that appears to hang should say why.
The nsimplify the previous commit replaced was the only use of sympy
anywhere in src/, so it leaves the base install.

Verified by running the suite with sympy absent from the environment
rather than merely absent from pyproject.toml, which is the only check
that means anything here: eeglabio has no import site in src/ either,
and is not removable, because mne imports it when asked to write an
EEGLAB file and eeg_mne2eeg exports through mne.

The uv.lock edit removes the two lines naming sympy in eegprep's own
dependency lists, and is scoped to eegprep's package block. An earlier
draft used an unscoped replace and took torch's sympy edge with it,
orphaning the package entry: uv lock --check still passed, because the
lock stayed self-consistent, and no CI job installs the torch extra with
--locked, so nothing would have caught it.
@neuromechanist
neuromechanist merged commit e8ac563 into develop Sep 20, 2026
9 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.

pop_resample computes a wrong resampling ratio for non-integer sampling rates, and labels the result with the requested rate

1 participant