Skip to content

Fix Edit and Tools audit findings (#675) - #677

Merged
suraj-ranganath merged 12 commits into
developfrom
cursor/fix-edit-tools-audit-675-623e
Nov 24, 2026
Merged

suraj-ranganath merged 12 commits into
developfrom
cursor/fix-edit-tools-audit-675-623e

Conversation

@suraj-ranganath

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

Copy link
Copy Markdown
Member

pop_runica passes lrate 0.001 unless set and omits it from history. That default now reaches every eeg_runica caller, including bids_preproc, matching EEGLAB pop_runica. JADE uses general eig on a non-symmetric matrix. Dipole slices stay upright and scale by voxel size, so avg152t1 matches its 2 mm bounds. Spherical plots use avg152t1 and MNI plots use standard_mri. Fine-fit OK stores the on-screen dipole, including a flipped moment, and records those coordinates so the menu and history replay them without refitting. Plot map is titled IC n. Plot dipole honours select for a nonzero unchecked dipole and draws projection lines. Insert, append, and delete keep the field edits that follow, in that command order. Named SOBI text and ['p', 100] raise the same error; sobi.m ignores n. Multifit stores the identity transform.

EEGLAB reference on this head: https://github.com/sccn/eegprep/actions/runs/45316172997, dispatched by suraj-ranganath on 2afe7bd (EEGLAB d0963be9, eeglab_tests fec88f9f). Shards heavy, misc, stats, hybrid and parity passed. core: 4 failed, 2919 passed, 17 skipped. study: 1 failed, 340 passed, 27 skipped. test_seeded_pop_runica_on_eeglab_data_matches_pythoncompat passes at the unchanged tolerance.

The 5 failures are the develop failures tracked in #685: test_coregister_parity.py (2 tests), test_dipfit_bem.py::test_bem_leadfield_and_multifit_match_fieldtrip, test_study_clustering.py::test_matlab_kmeans_numbering_matches_fixed_initial_centroids and test_phase2_file_channel_location.py::test_struct_near_assertion_matches_source. The coregister and BEM Python results are bit-identical on develop 7e17c30 and on this branch, and this PR does not touch the kmeans or struct_near tests or the MATLAB transport. The earlier run on 5e24e40 (https://github.com/sccn/eegprep/actions/runs/45309848204) showed the same 5 plus the runica transport failure fixed in 2afe7bd.

Fixes #675

Open in Web Open in Cursor 

Match the epoch window, Parks-McClellan order, and DIPFIT co-registration
from the November 23 GUI audit. Inspect/label components stores rejection
flags on OK. MRI head models and eLORETA stay disabled.

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.

@claude

claude Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

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


Code review

  • Overall assessment: Needs changes. Three changes here introduce regressions. Most of the other audit items read correctly: pop_firpmord uses the Herrmann remlpord formula, the pop_icflag history is a NaN matrix, DIPFIT history is in name/value form, and the epoched time crop follows the epoch.m window.
  • Highest-risk area: DIPFIT plotting and settings (pop_dipplot, resolved_coord_transform).
  • Merge recommendation: Needs changes. The EEGLAB MATLAB reference run is also still outstanding (the PR touches pop_select, pop_firpmord, and DIPFIT).

Blocking

None.

Important

  1. Plot dipoles now fails for BESA datasets (plugins/dipfit/pop_dipplot.py:171). MRI slices are now always drawn (use_mri = True). The dialog fills mri with the BESA template's standard_BESA/avg152t1.mat, and _validate_mri_option refuses that path with DIPFITUnavailableError. When it is not refused, spherical BESA positions are drawn on MNI slices with no transform. Fix: draw slices only for MNI coordinates (or transform BESA→MNI first), accept the template's own mrifile, and remove the dead else: branch.
  2. pop_select drops events on the last sample of a point range in epoched data (functions/popfunc/pop_select.py:451-461). The data keep both named samples, but the event filter keeps the half-open tmax*srate bound. Example: with point=[1 64] on a 128-point epoch starting at −0.5 s, an event at local sample 64 is discarded while sample 64 is kept. Fix: in the point_mat branch, compute the event upper bound from stop.
  3. A failed DIPFIT warp leaves coord_transform empty with no error (plugins/dipfit/_utils.py:213-216, used by pop_dipfit_settings.py:231). pop_dipfit_settings(EEG, model='standardBEM') with an unmatched montage stores [] (identity) if the warp raises. The old BEM default rotation was removed, so the fit runs on uncoregistered electrodes and the user is not told. Fix: raise in _apply_settings with a pop_dipfit_settings:-prefixed message that gives the fix. Also, the dialog now runs the warp for every template each time it opens. Compute it only for the selected template.

Nits

  • pop_selectcomps.py:41: hasattr(renderer, "run") dispatch is ruled out by AGENTS.md ("No ad-hoc compatibility hacks such as hasattr…"). The Qt browser also creates its own QApplication inside a popfunc module; it would fit better under functions/guifunc/.
  • pop_selectcomps._run_component_browser calls pop_prop(..., plot="off"), so clicking a component shows only ACCEPT/Close, with no map or properties to look at before labelling it.

Test gaps

  • pop_dipplot on a BESA-fitted dataset with the dialog defaults. Item 1 would have caught this.
  • An epoched pop_select(point=[a b]) with an event on sample b, checking the event survives with the right latency.
  • pop_dipfit_settings(EEG, model='standardBEM') for a montage the warp cannot fit, checking that it raises rather than storing [].

EEGLAB parity notes

  • I could not check the pop_firpmord length against MATLAB firpmord here: there is no MATLAB and no vendored src/eegprep/eeglab/ in this checkout. Please confirm in the reference run that a highpass [0 1] (stopband deviation passed first to remlpord) gives the same order as MATLAB.
  • I could not confirm the pop_firws window labels against pop_firws.m for the same reason. From memory, EEGLAB prints PB dev=0.0063 and 0.0022 for Hann and Hamming; the PR has 0.006 and 0.002.
  • Applying gcompreject only on OK, and refusing a time range that misses the data, are reasonable documented deviations.

Checked for correctness bugs, EEGLAB parity, data structure compatibility, changed-behavior tests, and CLAUDE.md/AGENTS.md compliance. Inline comments are posted on the four flagged lines.

use_mri = (
_option_on(options.get("summary")) or _option_on(options.get("projimg")) or _option_on(options.get("cornermri"))
)
use_mri = True

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). use_mri = True means _plot_mri_slices → _validate_mri_option now runs on every plot. For a BESA (standardBESA) dataset the dialog pre-fills mri with dipfit.mrifile = 'standard_BESA/avg152t1.mat' (pop_dipplot.py:72, _utils.py:51). That path has neither standard_mri nor standard_BEM in it, so _validate_mri_option raises DIPFITUnavailableError. In practice, Plot dipoles after a BESA fit now fails when the dialog runs with its default values. Before this change it only failed when summary, projimg, or cornermri was on.

On the command line without mri, BESA dipoles are in spherical coordinates and get drawn on MNI slices with no transform, so they land in the wrong place.

Suggested fix: draw slices only when coordformat is MNI (or apply the BESA→MNI transform first), and accept the template's own mrifile. Add a test that runs pop_dipplot on a BESA-fitted dataset with the dialog defaults. The else: branch below is now dead code and should be removed.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🤖 Fixed in 9d5748a. Slices are drawn only when coordformat is MNI, so a BESA dialog default of standard_BESA/avg152t1.mat no longer calls _validate_mri_option and no longer paints spherical positions on the MNI volume. Packaged template MRI names are accepted; a custom file still raises DIPFITUnavailableError. The non-MNI branch builds the 3-D axes only. test_besa_dipole_plot_uses_the_dialog_mri_without_mni_slices runs pop_dipplot with that dialog MRI and checks the figure has one axes.

A BESA-to-MNI transform of the dipole positions is not applied. EEGLAB hands the MRI path to dipplot, which keeps spherical coordinates on a sphere. Putting those positions through an extra transform here would not match that plot.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🤖 Updated in cff84e9. Spherical BESA plots now draw the packaged avg152t1 slices, the same volume EEGLAB uses for that template. A custom MRI is still refused. test_besa_dipole_plot_uses_the_dialog_mri_without_mni_slices checks eegprep_mri == "avg152t1" and that a slice image is on the figure.

Comment on lines +451 to +461
lim1 = tmin * srate
lim2 = tmax * srate
newevents = []
for ev in EEG['event']:
if 'epoch' in ev and 'latency' in ev:
epoch_offset = int(ev['epoch']) - 1
local_latency = float(ev['latency']) - epoch_offset * old_pnts
if a <= local_latency <= b:
ev['latency'] = local_latency - (a - 1) + epoch_offset * pnts
newevents.append(ev)
if 'epoch' not in ev or 'latency' not in ev:
continue
epoch_index = int(ev['epoch']) - 1
locking = time0 + epoch_index * old_pnts
pos0 = math.floor(locking)
latency = float(ev['latency'])
if latency < pos0 + lim1 or latency >= pos0 + lim2:

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. With a point range, the data slice keeps both named samples (stop = last). The event filter still uses the half-open epoch.m bound latency >= pos0 + tmax*srate, and tmax comes from eeg_point2lat(last). As a result, an event on the last kept sample is dropped while its sample is kept.

Example: xmin=-0.5, srate=128, pnts=128, point=[1 64]. Here lim2 = -1 and pos0 = 65, so an event at local sample 64 hits 64 >= 64 and is discarded, even though sample 64 is in the output.

Suggested fix: in the point_mat branch, set the upper bound from stop, e.g. lim2 = (stop - math.floor(time0)) + 1 in the same units, so the event window matches the kept samples. Add a test for an epoched point range with an event on the last sample.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🤖 Fixed in 9d5748a. For a point range the event window is [reallim1, reallim2 + 1), so an event on the named last sample is kept and the next sample is not. Time ranges still use the unrounded half-open epoch.m bounds. test_epoched_point_range_keeps_the_event_on_the_last_sample uses xmin=-0.5, srate=128, point=[1, 64], keeps the event at latency 64, and drops the event at 65.

Comment thread src/eegprep/plugins/dipfit/_utils.py Outdated
Comment on lines +213 to +216
try:
return False, align_channels_to_template(EEG, chanfile)
except (OSError, ValueError):
return 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.

Important. If the warp fails, the OSError/ValueError is caught and [] is returned. On the command line, _apply_settings (pop_dipfit_settings.py:231) then stores coord_transform = [] without any error. The BEM template also no longer has its old default rotation, so a later fit uses an identity transform with uncoregistered electrodes and nothing tells the user. The dialog does refuse an empty matrix, but pop_dipfit_settings(EEG, model='standardBEM') does not.

Suggested fix: let the coregister error propagate in _apply_settings, with pop_dipfit_settings: in the message and the exact fix (pass coord_transform or [] explicitly). Keep the swallow only for pre-filling the dialog, if it is needed there.

Also note that _dialog_template_state runs this warp for each template every time the dialog opens, which is two optimizer runs per open for an unmatched montage. Consider computing it only for the selected template, or when the user changes the menu.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🤖 Fixed in 9d5748a. resolved_coord_transform no longer swallows a failed warp. pop_dipfit_settings(EEG, model='standardBEM') raises ValueError naming pop_dipfit_settings and the fix (coord_transform as nine numbers, or coord_transform=[]). The dialog still catches that error while filling the text field, and it warps only the selected template. The other templates still get the cheap keyword lookup, so switching the menu does not run a second optimizer. test_unmatched_montage_without_enough_landmarks_names_the_fix covers the command-line error and checks the dialog still opens. Synthetic tests that have no template labels now pass coord_transform=[] explicitly.

return (EEG, "") if return_com else EEG
compnum = result.get("compnum", "")
reject = result.get("reject", "")
if renderer is not None and hasattr(renderer, "run"):

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 (AGENTS.md). hasattr(renderer, "run") is the duck-typing dispatch that AGENTS.md rules out ("No ad-hoc compatibility hacks such as hasattr(obj, "old_attr")"). It also puts the Qt-only browser path in front of the inputgui path for any renderer without run. Suggested fix: branch on renderer is None and use the browser there. Better still, move _run_component_browser into functions/guifunc/ so this popfunc module does not create its own QApplication.

A related UX point: open_component calls pop_prop(..., plot="off"), so clicking a component shows only ACCEPT/Close, with no map or spectrum. The user is asked to label a component they cannot see. This is acknowledged in the PR body, but it is worth showing the pop_prop figure (plot="on") before the chooser.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🤖 Fixed the hasattr branch in 9d5748a: a passed renderer uses inputgui, and renderer is None opens the component browser. Clicking a component now calls pop_prop with plotting on, so the map and spectrum are shown before ACCEPT/REJECT. figure.show() does not block, so the chooser still opens.

The browser stays in pop_selectcomps. The window's only job is to return the gcompreject flags that this function writes on OK, and moving the widgets into guifunc would pass that same array back. The existing click test still patches pop_prop, so it does not open a figure.

cursoragent and others added 4 commits November 23, 2026 20:41
Draw MRI slices only for MNI coordinates, keep the event on the last sample
of a point range, and report a failed montage warp instead of storing an
empty transform.

Co-authored-by: Suraj Ranganath <[email protected]>
Use the Qt6 nested enums and a real dict for the event-structure edits so
the type check can resolve the attributes it flagged.

Co-authored-by: Suraj Ranganath <[email protected]>
Co-register the packaged BEM and BESA templates, match MATLAB firpmord, and complete the component, ICA, and dipole workflows from the #675 review.

Co-authored-by: Suraj Ranganath <[email protected]>
The global *.mat ignore was dropping standard_BESA.mat, so a checkout could not resolve the template head-model path.

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

cursor Bot commented Nov 23, 2026

Copy link
Copy Markdown

🤖 Specification for cff84e9.

Problem. Default BEM Co-register passed standard_vol.mat into the headplot mesh loader, which only ships as npz. The BESA cap385 electrode file was not packaged. Disabled head-model and eLORETA tooltips were dropped before the main window. pop_firpmord did not follow MATLAB firpmord on multiband orders. Inspect/label components did not draw maps, page past 35, prompt for the component list, or put ACCEPT/REJECT in pop_prop. SOBI, JADE, dipole navigation, Desikan-Killiany labels, the channel-location lookup list, the flagged pop_subcomp prompts, and the fine-fit Plot/Flip/Fit buttons were still open.

Approach. coregister resolves a BEM scalp from the packaged volume and a BESA sphere of radius 85. The cap385 elp, its four-shell volume, and the witheog montage are packaged. ExtensionMenu.tooltip is copied onto the real QAction. firpmord uses relative deviations and, for more than two bands, the max Herrmann length of each inner band against both neighbours, then adds one tap when the last band passes and the order is odd. pop_selectcomps prompts, pages by 35, draws topoplot on each button, and toggles rejection inside pop_prop. sobi.m and jader.m are ported into pop_runica. dipplot adds Plot one/Next/Prev and eeg_compatlas stores model.areadk. The lookup list, subcomp prompts, and fine-fit actions follow the EEGLAB dialogs. Warp text uses full precision, event-structure edits stay off the dialog spec, and BESA dipole plots draw avg152t1.

Tests. Each item has a regression that failed on the old behavior: a Co-register click on the default BEM dialog, a BESA warp, main-window tooltips, the MATLAB firpmord orders (53, 210, 166, 95, 211, 174, 162, 191), component maps plus paging and the pop_prop toggle, SOBI/JADE recovery, dipole navigation and atlas labels, the lookup default, the flagged subcomp buttons, and a fine-fit button that writes the new position. Tolerances, goldens, and parity JSON were not changed.

Use numpy Vh for the SOBI whitener, RMS-scale SOBI and JADE columns, and record positional SOBI history. Empty BESA transforms stay identity, spherical dipoles use sph2spm, and the fine-fit and inspect dialogs show the figures EEGLAB shows.

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

cursor Bot commented Nov 23, 2026

Copy link
Copy Markdown

🤖 Specification for c3df234.

Problem. sobi.py whitened with Vh.T, so the matched |corr| with MATLAB bottomed at 0.17. pop_runica did not RMS-scale SOBI or JADE, and its SOBI history used named 'p', 100, which sobi.m cannot replay. Inspect/label maps died on the array chanlocs pop_loadset returns. Spherical BESA dipoles skipped sph2spm. Fine-fit Plot map and Plot dipole built figures that never showed. Empty BESA coord_transform fell through to the spherical atlas default. Four Qt tests failed because fakes were not real widgets.

Approach. The whitener is pinv(S) @ Vh, which is MATLAB VV'. _dataset_from_ica calls scale_ica_to_rms_microvolt after the variance reorder. Empty SOBI history is EEG = pop_runica(EEG, 'icatype', 'sobi'); typed counts are 'options', {n p}. The Jade label matches pop_runica.m. Chanlocs use an is None check and the map error is no longer swallowed. Spherical positions and moments go through sph2spm before the scatter and the slices. Next and Prev redraw the slices for the current component and the area label includes the component number. Plot map calls pop_topoplot(EEG, 0, comp, ..., [1, 1], 1). Plot dipole plots the dialog fields. Flip uses g format and co-register fields use .4g. An empty coord_transform is the identity [0 0 0 0 0 0 1 1 1] in eeg_checkset and in eeg_compatlas. Headless coregister also searches resources/dipfit. Subcomp ERPs are a per-channel grid raised with show_figures. The Qt tests use real QListWidget, QComboBox, QLineEdit, and QFileDialog.

JADE. jader.py uses the same pair order (p = 1..m-1, q = p+1..m) and the same stop (abs(theta) > 1/sqrt(T)/100). The residual is the unsorted MATLAB eig versus numpy eigh at initialization, plus the unconditional variance reorder. Components 12 and 13 stay swapped. After scaling, activation r is at least 0.99994 and winv is within 9.6e-3 relative. The Jacobi sweep updates the cumulant matrix in place, so there is no separate vectorisation that keeps that order. 10.8 s versus MATLAB 5.6 s is that loop.

F69. The sphere does not use the RNG and matches to 5.8e-9. Weights use RandomState(5489), the pythoncompat stream rng(5489, 'twister'), not EEGLAB's rndreset-off stream rand('state', 0). The median correlation of 0.91 is the gap between those two seeds. The seed is unchanged and no tolerance was loosened. tolerances.toml has no new entry. The MATLAB sobi comparison uses assert_matlab_near and is selected only with --eeglab-backend=matlab. ml_rmbase is not in this checkout; the BESA label test places component 1 on the superiorfrontal R atlas vertex through the identity transform and expects that label.

pop_runica passes lrate 0.001 unless the caller sets one. JADE uses the general eigenpath when a matrix is not exactly symmetric. Dipole slices are transposed so the anatomy is upright, and each head model uses its own volume.

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

cursor Bot commented Nov 23, 2026

Copy link
Copy Markdown

🤖 Specification for eb5e9a2.

Problem. The seeded runica gap was not the RNG. After rng(5489,'twister'), MATLAB rand matches RandomState(5489). pop_runica.m lines 503 and 523 always pass lrate 0.001, and eegprep was falling through to 0.00065/log(nchans). JADE swapped components 12 and 13 because jader.py used eigh on a cumulant block that is not exactly symmetric (MATLAB eig takes the general path). Every dipplot MRI slice was upside down: rot90 plus origin lower flips z on the sagittal and coronal views and y on the axial. Spherical plots were labeled avg152t1 while drawing the Colin volume. Fine-fit Plot dipole drew an unchecked second dipole at the origin, omitted projection lines, and did not title the figure IC n. The SOBI box accepted 'p', 100 as n=100. Multifit left coord_transform empty.

Approach. eeg_runica copies its options and sets lrate to 0.001 only when the caller did not pass one, so the history command stays EEGLAB's vararg2str(g.options). jader._matlab_eig uses eigh only when A equals A.'; otherwise it uses np.linalg.eig and keeps real parts only when that result is real. The covariance is mirrored from the lower triangle first, because MATLAB's X*X' is exactly symmetric and eigh reads that triangle. dipfit_mri_slices uses the transposed plane with origin lower. Spherical plots load the packaged avg152t1 volume and MNI plots load standard_mri, and the figure label is that volume's name. pop_dipplot draws only rows in model.select, and the fine-fit button passes normlen on, projlines on, and title IC n. Named SOBI or JADE option text raises pop_runica with the positional form. pop_multifit ends in the existing empty-transform normalizer, which stores [0 0 0 0 0 0 1 1 1].

JADE speed. On a 32 by 2000 matrix the eigh init took 315 sweeps and 45.7 s. The general-eig init takes 114 sweeps and 13.2 s. The remaining time is the in-place pair sweep, which is unchanged so the order stays p = 1..m-1, q = p+1..m.

Tests. A mocked runica call checks lrate 0.001, a caller override of 1e-5, and that only the override appears in history. test_seeded_pop_runica_on_eeglab_data_matches_pythoncompat compares pop_runica on eeglab_data.set with EEGLAB pythoncompat through assert_matlab_near. It is selected only with --eeglab-backend=matlab. The JADE test fails if eigh is used on a matrix that is not exactly symmetric. The slice test uses the component 3 position (-0.05, 61.6, -41.1): air above the vertex is the top of the coronal image, the sagittal superior band is above the neck, and the axial anterior span is narrower than the posterior span. Spherical figures are labeled avg152t1 with shape (91, 109); MNI figures are labeled standard_mri with shape (181, 217). An unchecked dipole at the origin is not drawn. 'p', 100 raises, and 2 1 stays positional. Multifit on an empty BESA transform stores the identity. Tolerances and parity JSON were not changed.

avg152t1 extents now follow the 2 mm affine, Plot map uses IC n, and named SOBI lists raise the same pop_runica error as the text form.

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

cursor Bot commented Nov 24, 2026

Copy link
Copy Markdown

🤖 Round 5, head 7cb54e5.

Problem. _mri.py built slice coordinates as grid + origin, so avg152t1 (2 mm voxels) reported axial extents around x -91..-1 and y -127..-19 and dipoles fell outside the images. The slice shift was a bare [-3, 3, -3] voxel count. Plot map still titled the figure "Component map". A SOBI list such as ['p', 100] died in int() with "invalid literal for int()". The jader covariance comment justified the lower-triangle mirror.

Approach. World position on each axis is transform[axis, axis] * grid + transform[axis, 3]. dipplot.m shifts the slice by three grid steps (-x, +y, -z); that is 3 mm on standard_mri and 6 mm on avg152t1, and the Colin indices stay (87, 108, 109). Plot map uses "IC n". Text and list/tuple SOBI or Jade names share one pop_runica error that shows {32 100} or p=100. The rejection stays: sobi.m ignores n, and EEGPrep does not. Plot dipole still honours select when the unchecked dipole is nonzero. The jader comment is gone; the mirror stays.

Tests. avg152t1 and standard_mri slice extents equal the affine world bounds, and a 3-voxel move of 3 * voxel size millimetres shifts the index by 3. Plot map records the title IC 1. options ['p', 100] and ('p', 100) match the text error. An unchecked dipole at [10, 20, 30] is not drawn. ./pre-commit.py --fix passed. tests/test_dipfit_workflows.py and tests/test_eeg_runica.py: 48 passed, 2 MATLAB tests deselected.

@suraj-ranganath
suraj-ranganath marked this pull request as draft November 24, 2026 01:46
@suraj-ranganath
suraj-ranganath marked this pull request as ready for review November 24, 2026 01:46
@claude

claude Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

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


Code review (head 7cb54e58)

  • Overall assessment: Needs changes. The three regressions from the first review are fixed in this head:

    • The pop_select point-range event window now uses reallim2 + 1.
    • resolved_coord_transform now raises when the warp fails, and pop_dipfit_settings names the fix.
    • pop_selectcomps no longer dispatches on hasattr, and pop_dipplot no longer refuses BESA datasets.

    Two newly enabled dialog buttons lose what the user did when they press OK.

  • Highest-risk area: the GUI buttons this PR enables (pop_editeventvals Insert/Append/Delete and the pop_dipfit_nonlinear Flip/fit buttons).

  • Merge recommendation: Needs changes. The MATLAB reference run is also still missing from the PR body (see parity notes).

Blocking

None.

Important

  1. pop_editeventvals: after Insert, Append or Delete, field edits are dropped, and Append on the last event raises on OK (pop_editeventvals.py:199-201, qt.py:1632).
    • When structure_ops is non-empty, _run_gui returns early, so values typed into an inserted event never reach changefield. The new event is stored blank.
    • Append on event N sets eventnum to N+1, and the range check, which still uses the original count, raises event number N+1 is outside 1 to N.
    • Fix: add the changefield entries from field_displays after the structure ops, and check eventnum against len(displays).
  2. pop_dipfit_nonlinear: OK undoes Flip and fit-moment-only (pop_dipfit_nonlinear.py:59-63, buttons at 114-128).
    • OK still runs a full nonlinear="yes" fit on the values in the dialog. That re-solves the moment, so a flip is reversed, and it re-fits the position after "fit only moment".
    • The known_differences note that described refit-on-OK was removed in this PR.
    • Fix: in the GUI path, store the displayed model without refitting. Keep run_nonlinear for the command-line form.

Nits

  • _mri._grid_steps multiplies the 3-voxel shift by xgrid[1] - xgrid[0]. These grids are 1-based voxel indices (the slice extents use transform[a,a] * grid + offset), so the step is always 1 and the factor does nothing. The description's "6 mm on avg152t1" comes from the voxel size, not from this factor. Drop it, or rename it so nobody later feeds it millimetre grids.
  • eeg_compatlas._transform uses try/except (TypeError, ValueError): pass around the stored transform. AGENTS.md asks to avoid this kind of defensive catch. Also, eeg_checkset now always fills the identity transform, so the _MNI_TRANSFORM/_SPHERICAL_TRANSFORM fallback only runs when a dataset skipped eeg_checkset.

Test gaps

  • pop_editeventvals: Insert, type field values, OK → the event has those values. Append on the last event, then OK → no error and N+1 events. The existing test_event_structure_edits_do_not_mutate_the_dialog_spec never presses OK.
  • pop_dipfit_nonlinear: click Flip, press OK → the stored momxyz keeps the flipped sign. Click fit-moment, press OK → posxyz is unchanged.
  • test_standard_mri/avg152_slice_extents_match_the_world_bounds rebuild the expected extents with the same transform[a,a] * grid + offset formula as _world_axis, so they cannot catch a wrong affine. The upright-anatomy test (component 3) is the useful check. Consider pinning the known avg152t1 bounds (≈ −90..90, −126..90, −72..108 mm) as literals.

EEGLAB parity notes

  • AGENTS.md requires the EEGLAB MATLAB reference run before merging a core-function change. This PR changes pop_select epoch cropping, eeg_runica (lrate 0.001 is now the default for every caller, including bids_preproc), the new sobi/jader ports, pop_firpmord, and DIPFIT. The PR body has no run (command or workflow, the commits, pass/fail/skip counts). Please trigger eeglab-reference.yml on this branch and add the result.
  • There is no vendored src/eegprep/eeglab/ in this checkout, so I could not compare eeg_compatlas.m, pop_dipfit_nonlinear.m (OK behaviour), or dipplot.m (slice offset sign) line by line. Finding 2 is based on what the code does, not on the .m file.
  • These deviations are documented and tested, so they are fine: SOBI/JADE named-option rejection, refusing a time range that misses the data, applying gcompreject on OK, and filling the montage warp.

Checked for correctness bugs, EEGLAB parity, data structure compatibility, changed-behavior tests, and CLAUDE.md/AGENTS.md compliance. Inline comments are posted on findings 1 and 2.

Comment on lines +199 to +201
options: list[tuple[str, Any]] = list(structure_ops)
if structure_ops:
return 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 (bug). This PR enables Insert, Append and Delete, and that exposes two failures when the user presses OK:

  1. Field edits are lost. As soon as structure_ops has an entry, the function returns before the changefield loop. Example: click Insert event, type type=stim and a latency into the new blank event, press OK. The command and the dataset get only ('insert', 1), so an empty event is stored and the typed values are discarded. Edits made to existing events in the same session are dropped too. EEGLAB records 'insert'/'append' and also the 'changefield' entries that follow.
  2. Append on the last event raises. _edit_event_structure (qt.py:1632) sets eventnum to index + 2. On the last of N events that is N+1, so the range check at lines 188-192 (which still uses the original len(events)) raises event number N+1 is outside 1 to N.

Suggested fix: after applying structure_ops, compare field_displays (already re-indexed for the new event list) with the post-structure events and add the changefield entries, rather than returning early. Check eventnum against len(displays) instead of len(events). The current test only clicks Insert and never presses OK. Add one that does Insert → type values → OK, and another that does Append on the last event → OK.

) from exc
if event_index < 1 or event_index > len(events):
raise ValueError(
f"pop_editeventvals: event number {event_index} is outside 1 to {len(events)}. "
"Type an event number in that range and press Enter."
)
if "field_displays" in result or "structure_ops" in result:
displays = result.get("field_displays") or []
structure_ops = list(result.get("structure_ops") or [])
else:
displays = _indexed_field_displays(spec, "navigate_event")
structure_ops = _structure_operations(spec)
options: list[tuple[str, Any]] = list(structure_ops)
if structure_ops:
return options
for index, event in enumerate(events, start=1):
source = result if index == event_index else _display_row(displays, index)
if source is None:
continue
for field in fields:
value = _parse_gui_value(source.get(f"field_{field}"))
if value != _display_event_value(EEG, event, field):
options.append(("changefield", [index, field, value]))
return options

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🤖 Fixed in 3f6b7e2. Insert, append, and delete stay in the command, and the field edits that follow are changefield entries at the indices after those structure ops. That is the order EEGLAB expands for replay: the structure action, then changefield. The event number is checked against the display list, so append on the last of N events is N+1. Tests cover insert then OK, append on the last event then OK, and delete plus an edit on a remaining event. Each history command replays to the same events.

Comment on lines +114 to +128
ControlSpec("pushbutton", "Flip (in|out)", tag="flip1", callback=action("flip1")),
ControlSpec("text", "#2", tag="dip2"),
ControlSpec("checkbox", tag="dip2sel", value=second_selected),
ControlSpec("spacer"),
ControlSpec("edit", tag="dip2pos", value=_format_dialog_triplet(model.get("posxyz"), 1)),
ControlSpec("edit", tag="dip2mom", value=_format_dialog_triplet(model.get("momxyz"), 1)),
ControlSpec("pushbutton", "Flip (in|out)", tag="flip2", enabled=False),
ControlSpec("pushbutton", "Flip (in|out)", tag="flip2", callback=action("flip2")),
ControlSpec("checkbox", "Symmetry constrain for dipole #2", tag="dip2sym", value=True),
ControlSpec("pushbutton", "Fit dipole(s)' position & moment", tag="fitposition", enabled=False),
ControlSpec("pushbutton", "OR fit only dipole(s)' moment", tag="fitmoment", enabled=False),
ControlSpec("pushbutton", "Plot dipole(s)", tag="plotdip", enabled=False),
),
known_differences=(
"EEGPrep OK applies the displayed values and runs a spherical nonlinear fit; individual MATLAB callbacks are not mirrored.",
ControlSpec(
"pushbutton",
"Fit dipole(s)' position & moment",
tag="fitposition",
callback=action("fitposition"),
),
ControlSpec("pushbutton", "OR fit only dipole(s)' moment", tag="fitmoment", callback=action("fitmoment")),

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 (behavior). These buttons are now enabled, but OK still runs run_nonlinear(working, ..., nonlinear="yes") on the values shown in the dialog (lines 59-63). So:

  • After Flip (in|out), OK refits position and moment. The least-squares moment comes back with its original sign, so the flip is undone.
  • After OR fit only dipole(s)' moment, OK runs a full position fit, so the dipole that gets stored is not the one the user just saw.
  • Positions or moments typed by hand are also overwritten.

This PR also removed the known_differences note that said "OK … runs a spherical nonlinear fit", so this is no longer documented.

Suggested fix: in the GUI branch, store working (the values on screen) without refitting, so OK keeps the result of the last button press. Keep run_nonlinear for the command-line form. If refit-on-OK is intended, restore the known-difference note and disable Flip and fit-moment. Add a test: click Flip, press OK, and check that momxyz keeps the flipped sign.

if gui:
result = inputgui(pop_dipfit_nonlinear_dialog_spec(EEG), renderer=renderer)
if result is None:
return (EEG, "") if return_com else EEG
working, component = _apply_nonlinear_gui_model(EEG, result)
if result.get("dip2sel") and result.get("dip2sym"):
symmetry = "x" if str(dipfit_record(EEG).get("coordformat", "")).lower() == "mni" else "y"
component_index = _single_component(component, working)
out = run_nonlinear(working, component=component_index, nonlinear=nonlinear, symmetry=symmetry)
command = dipfit_history(
"pop_dipfit_nonlinear",
component=component_index,
nonlinear=nonlinear,
symmetry=symmetry or "",
)
return (out, command) if return_com else out

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🤖 Fixed in 3f6b7e2. GUI OK returns the on-screen model and does not call run_nonlinear. Command-line calls still do. Flip then OK keeps the flipped momxyz sign. Fit only moment then OK leaves posxyz unchanged. Typed position and moment survive OK.

cursoragent and others added 2 commits November 24, 2026 02:03
Insert, append, and delete now record the following field changes, and fine-fit OK stores the dialog model instead of refitting. A malformed coord_transform raises from eeg_compatlas.

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

claude Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

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


Code review (head 5e24e40)

  • Overall assessment: Needs changes.
    • Both findings from the last review are fixed in 3f6b7e2:
      • pop_editeventvals keeps the field edits after Insert, Append and Delete, using _events_after_structure, and checks the event number against the display list.
      • pop_dipfit_nonlinear no longer refits on OK.
    • The fix for the second one introduces a new regression in the menu path (see Important).
    • eeg_compatlas now raises on a malformed coord_transform instead of silently falling back. The merge commit 5e24e40 only brings in develop changes and the changelog.
  • Highest-risk area: DIPFIT fine-fit GUI and how it syncs with the session.
  • Merge recommendation: Needs changes.

Blocking

None.

Important

  1. Component dipole fine fit OK no longer stores anything in the app (plugins/dipfit/pop_dipfit_nonlinear.py:61).

    • What happens: GUI OK now returns (working, ""). The menu handler stores a result only when command is non-empty (functions/guifunc/menu_actions.py:1726), so the flipped, moment-only or typed dipole is dropped. EEG/ALLEEG in eegprep-console stay unchanged.
    • Before this commit: OK returned a dipfit_history command, so the result was stored.
    • Why the tests pass: the new tests call pop_dipfit_nonlinear directly and assert command == "", which locks in the broken path.
    • Why it matters: AGENTS.md says "GUI/menu actions must update datasets and history through EEGPrepSession helpers".
    • Fix: return a non-empty, replayable command for the on-screen model, then update the tests to expect it.

    Fix this →

Nits

None.

Test gaps

  • A menu-level test for fine fit: run the pop_dipfit_nonlinear menu action, click Flip, press OK, then check that session.EEG["dipfit"]["model"][c]["momxyz"] has the flipped sign and that ALLCOM has a new entry. Item 1 would have been caught by this test.

EEGLAB parity notes

  • The EEGLAB MATLAB reference run is still missing. This PR changes core functions (pop_select epoch cropping, the eeg_runica lrate default, the new sobi/jader ports, pop_firpmord, DIPFIT). The body says workflow_dispatch returned HTTP 403. Under AGENTS.md, a maintainer must trigger eeglab-reference.yml (or run it locally against the pinned commits) and add the counts to the PR body before merging.
  • The vendored src/eegprep/eeglab/ is not in this checkout, so I could not compare the history command that pop_dipfit_nonlinear.m returns after GUI OK line by line.

Checked for correctness bugs, EEGLAB parity, data structure compatibility, changed-behavior tests, and CLAUDE.md/AGENTS.md compliance. There is an inline comment on finding 1.

if result.get("dip2sel") and result.get("dip2sym"):
symmetry = "x" if str(dipfit_record(EEG).get("coordformat", "")).lower() == "mni" else "y"
working, _component = _apply_nonlinear_gui_model(EEG, result)
return (working, "") if return_com else working

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). GUI OK now returns an empty command. The menu handler for Tools > Locate dipoles > Component dipole fine fit only stores a result when the command is non-empty:

return
if not isinstance(out, tuple):
return
eeg_out, command = out[0], out[1] if len(out) > 1 else ""
if command:
self._store_current_from_gui(eeg_out, command=command)
self._refresh()

So in the app, OK is now a no-op. The flipped, moment-only, or typed dipole is thrown away, and EEG/ALLEEG in eegprep-console stay unchanged. Before this commit OK returned a refit with a dipfit_history command, so the dataset was stored. test_nonlinear_ok_keeps_* call pop_dipfit_nonlinear directly and assert command == "", so they lock in the behaviour that the menu drops.

Suggested fix: return a replayable command for the on-screen model, so the menu stores it and history replays it. For example, record the component plus the displayed posxyz/momxyz/select, or EEG = pop_dipfit_nonlinear(EEG) if you accept that replay is not exact. Then update the tests to expect a non-empty command, and add a menu-level test: run the fine-fit action, Flip, OK, and check that session.EEG["dipfit"]["model"] has the flipped moment.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

👾 Fixed in f6ec216. Fine-fit OK now records the on-screen component, posxyz, momxyz, and select. The menu stores that dataset, and replaying the command writes those coordinates without calling run_nonlinear. Flip, fit-only-moment, and typed values each replay to the same model, and the menu action keeps the flipped moment on session.EEG.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🤖 Fixed in f6ec216. Fine-fit OK now records the on-screen component, posxyz, momxyz, and select. The menu stores that dataset, and replaying the command writes those coordinates without calling run_nonlinear. Flip, fit-only-moment, and typed values each replay to the same model, and the menu action keeps the flipped moment on session.EEG.

OK writes the on-screen position, moment, and selection into a history
command that replays those coordinates without running the fit again.

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

claude Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

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


Code review (head f6ec216)

  • Overall assessment: The code looks good, but the MATLAB reference run still has to be recorded.
    • The one Important finding from the last review is fixed. GUI OK in pop_dipfit_nonlinear now returns a non-empty dipfit_history command with the on-screen posxyz, momxyz and select.
    • The menu handler stores that command, and replaying it writes the same coordinates without calling run_nonlinear.
    • All findings from the earlier reviews are fixed. These were: pop_select point-range events, the failed-warp error, the hasattr dispatch in pop_selectcomps, BESA pop_dipplot, field edits after a pop_editeventvals structure change, and refit-on-OK.
  • Highest-risk area: The numerics this PR changes: the new sobi/jader ports, the eeg_runica lrate default of 0.001 (which now reaches bids_preproc), pop_firpmord, and pop_select epoch cropping. Only the MATLAB reference run can confirm these.
  • Merge recommendation: Needs the MATLAB reference result before merging. No code changes are requested.

Blocking

None.

Important

None.

Nits

None.

Test gaps

None. The new tests cover what the last review asked for:

  • test_fine_fit_menu_stores_the_flipped_moment drives the real menu action through Flip and OK. It checks both session.EEG and ALLCOM.
  • The three test_nonlinear_ok_keeps_* tests now replay the recorded command through _console_python_command and check that the coordinates come back the same.

EEGLAB parity notes

  • The MATLAB reference run is still missing. AGENTS.md requires it before merging a core-function change, and a human has to approve the merge using it.
    • The run linked in the body (45309848204) is on 5e24e40. It does not include f6ec216, but f6ec216 only touches the DIPFIT GUI and history path, so a passing result on 5e24e40 would still cover the numerics.
    • Once the run finishes, add to the PR body: the EEGLAB and eeglab_tests commits, the pass/fail/skip counts, the runtime, and an explanation for each failure or skip.
  • pop_dipfit_nonlinear now takes posxyz/momxyz/select, which EEGLAB does not.
    • In EEGLAB the fine-fit OK changes EEG.dipfit directly, and no history command replays it.
    • This EEGPrep-only option is documented in the docstring and in eeglab_migration.rst, and tested. That makes it an acceptable documented difference, not a parity bug.

Checked for correctness bugs, EEGLAB parity, data structure compatibility, changed-behavior tests, and CLAUDE.md/AGENTS.md compliance.

The batch transport turns a Python EEG dict into a cell, so pop_runica
now receives the struct returned by MATLAB pop_loadset.

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

claude Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

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


Code review (head 2afe7bd)

  • Overall assessment: Looks good. I found no new issues.
    • The only commit since the last review is 2afe7bd, and it only touches a test. test_seeded_pop_runica_on_eeglab_data_matches_pythoncompat now gets the MATLAB dataset from eeglab_backend("pop_loadset", ...) and passes that struct to pop_runica.
    • Other reference tests already load data this way, for example tests/test_stream6_rejection_numbers.py:865 and tests/test_sigprocfunc_plotting_eeglab_tests.py:162.
    • The tolerance (assert_matlab_near) and the "lrate" not in command check are unchanged.
    • All findings from the earlier reviews (9d5748a, 3f6b7e2, f6ec216) are still fixed.
  • Highest-risk area: The numerics changes, which only the MATLAB reference run can confirm:
    • the default lrate of 0.001 in eeg_runica, which also reaches bids_preproc;
    • the new sobi and jader ports;
    • pop_firpmord;
    • epoch cropping in pop_select.
  • Merge recommendation: Ready for a human to approve. Before merging, re-run the core reference shard on 2afe7bd; see the parity notes.

Blocking

None.

Important

None.

Nits

None.

Test gaps

None.

EEGLAB parity notes

  • The reference run is now in the PR body: run 45309848204, on 5e24e40, against EEGLAB d0963be9 and eeglab_tests fec88f9f.
    • The heavy, misc, stats, hybrid and parity shards passed.
    • study: 1 failed, 340 passed, 27 skipped.
    • core: 5 failed, 2917 passed, 17 skipped.
  • The body explains each of the 6 failures:
    • test_seeded_pop_runica... failed because the dataset reached MATLAB as a cell. 2afe7bd is meant to fix that.
    • Three DIPFIT/coregister failures: the body says the Python results are identical on develop 7e17c30, so they come from develop.
    • Two study/transport failures are in code this PR does not touch.
    • These explanations hold up. f6ec216 and 2afe7bd don't touch numerics code, so the run on 5e24e40 still covers the numerics changes.
  • One thing left before merging: the runica fix has not been run against MATLAB yet. Please re-run the core shard, or just tests/test_eeg_runica.py --eeglab-backend=matlab, on 2afe7bd to confirm the seeded comparison passes at the unchanged tolerance. If it still fails, the RNG/lrate match described in the PR does not hold.
  • Not checked line by line: the vendored src/eegprep/eeglab/ tree is not in this checkout, so I could not compare against the .m sources. On both sides, the lrate 0.001 default (pop_runica.m lines 503 and 523) is applied only when the caller passes no lrate, and history records only a value the caller passed. That is consistent with EEGLAB's vararg2str(g.options).

I checked for correctness bugs, EEGLAB parity, data structure compatibility, tests for the changed behaviour, and compliance with CLAUDE.md and AGENTS.md. No inline comments.

@suraj-ranganath
suraj-ranganath merged commit f6bea53 into develop Nov 24, 2026
19 of 21 checks passed
@cursor cursor Bot mentioned this pull request Nov 24, 2026
29 tasks done
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.

GUI audit Nov 23: Edit and Tools fixes (DIPFIT co-registration and fine fit, epoched Select data, firpmord, Inspect/label components)

2 participants