Skip to content

Fix File menu and data I/O audit findings (#673) - #676

Merged
suraj-ranganath merged 29 commits into
developfrom
cursor/file-menu-io-audit-673-aa6d
Nov 24, 2026
Merged

suraj-ranganath merged 29 commits into
developfrom
cursor/file-menu-io-audit-673-aa6d

Conversation

@suraj-ranganath

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

Copy link
Copy Markdown
Member

Fixes #673

File-menu and data I/O fixes from the Nov 23, 2026 side-by-side audit against EEGLAB 8ac485f6. The final head is bd045f8b.

EEGLAB reference suite

The MATLAB reference workflow ran on d37522c2 in 29m 13s, using EEGLAB d0963be9d81acc5b66e84f8d3d7c89e3ce127cc4 and eeglab_tests fec88f9ffe7c225eb1de8924db8b6a3e0d53a4d9. Across seven jobs, 4,424 tests passed, 5 failed and 58 were skipped. The only differences between the tested tree and the final head are the documentation edits described below. Reference run 45444166424

Job Passed Failed Skipped Deselected pytest runtime
Core 3,010 4 17 0 23:02
Study 340 1 27 3 14:32
Heavy 3 0 0 29 8:58
Parity 10 0 2 0 23:28
Misc 661 0 8 0 7:46
Stats 257 0 0 0 1:51
Hybrid 143 0 4 0 0:40

All five failures are tracked on develop. The failing assertions and reported values match the run on PR #672. After fetching origin/develop, git diff --name-only origin/develop...HEAD showed no changes to the failing tests or the implementations responsible for those assertions. Issue #685 · PR #672 reference run

Failing test Observed discrepancy
test_coregister_traditional_warp_matches_eeglab One of nine fitted transform parameters differed from EEGLAB by 0.00384488, outside the absolute and relative tolerances of 0.001 and 0.0001.
test_synthetic_traditional_warp_matches_fieldtrip Seven of nine synthetic warp parameters differed from FieldTrip beyond the same tolerances. The largest difference was 1.38408718 in the z rotation.
test_bem_leadfield_and_multifit_match_fieldtrip The leadfield comparison passed. The third fitted dipole was 7.94557 mm from the FieldTrip position, above the 1 mm limit.
test_matlab_kmeans_numbering_matches_fixed_initial_centroids The test compares MATLAB labels with Python labels plus one. MATLAB returned [1, 2, 1, 1, 2, 2], and the test expected [2, 3, 2, 2, 3, 3].
test_struct_near_assertion_matches_source MATLAB's near.m returned false for a pair that Python's assert_matlab_struct_near accepted. The expected AssertionError was never raised.

Of the 58 skips, 36 required --run-heavy-reference in their job. Eight needed BioSig's openbdf, three needed Neuroscan I/O, two needed ERPSS and three needed a working AMICA binary. Two BIDS tests require specific hosts, two dependency checks cover packages outside eegprep-lean, one path test requires Windows and one pop_chanedit menu lookup requires an interactive session.

Save current study (a7cc1b28)

File > Save current study > Yes and scripts using resavedatasets='on' write only datasets marked saved='no'. Each successful save marks the dataset 'yes' in the returned ALLEEG. Tests reload an edited derivative and verify that a clean raw BIDS recording keeps its bytes and modification time for both 'yes' and 'justloaded'. Attempting to overwrite a modified raw recording still raises an error.

pop_savestudy and its callers dropped the unused return_com option. The function always returns (study, datasets, command). The console test saves a real study and checks the synchronized datasets and command history. The packaged help in pop_savestudy.md and the workflow guide show the three-value return, MATLAB v6 output, the v7.3 size fallback and optional JSON. They also explain that std_rmalldatafields removes cached measures from the disk copy while the returned STUDY keeps them.

Merge from develop (d37522c2)

The branch merged develop at 0641c239 and restored the changelog entries in d37522c2. The only conflict was in docs/source/changelog.rst. The resolution retains the File menu and data I/O entry (#673), the BIDS updates, the pAMICA reference (#674) and the topoplot entry (#670).

Study resave documentation (bd045f8b)

EEGLAB resaves a dataset marked saved='justloaded' during a study save. EEGPrep skips it because the dataset has not changed since loading. The pop_savestudy function notes, packaged help and study workflow guide now document this difference. On this head, all 90 file-menu audit and study metadata tests passed in 4.46s. ./pre-commit.py --all-files passed on 1,474 files. EEGLAB pop_saveset.m, line 175

Root causes that differed from the issue

  • Item 6: Python loadcnt() stores the same 0-based sample offset as MATLAB loadcnt. pop_loadcnt adds 1, matching pop_loadcnt.m line 152. Duration stays unset so a leading boundary is kept. CNT length is not extended by EEGLAB's three tail samples.
  • Item 5: With option_saveversion6, EEGLAB writes MAT v6 and falls back to v7.3 when that file is too large. Precomputed measures are stripped on disk with std_rmalldatafields and kept on the returned STUDY. Resaving a JSON .study writes MATLAB. The return is always (study, datasets, command).
  • Item 2: round is MATLAB half-away-from-zero, bitand casts float operands, 1<X<3 evaluates left to right, and ~ is logical not. Errors name the user's expression.
  • Item 1: Folder import records [STUDY ALLEEG] = pop_importbids(...) with no return_study option. A recording that has no ses- folder is written under sub-<label>/eeg. A folder import returns (STUDY, ALLEEG).
  • Item 17: pop_savestudy history names ALLEEG, as this issue asks. pop_savestudy.m interpolates EEG.
  • Item 24: option_single is not applied. Datasets stay float64.

Second review

  • Cluster sets of shape (2, 1) stay 2-D. Only comps is flattened.
  • Segmented MFF is read with read_raw_egi and split from categories.xml / epochs.xml.
  • pop_loadeeg history is positional and events are ordered by latency.
  • STUDY command cells are EEGLAB name/value cells. pop_studyerp browses per dataset and orders conditions on the outside. pop_studywizard records the grid fields.
  • BIDS export asks for power-line frequency, writes task-<task>_events.json, uses chanlocs.type, and keeps one task per wizard file. _acq- coordsystem names are allowed.
  • pop_runscript validates every line before running any of them. Quit still asks before discarding unsaved data; that difference from eeglab.m line 619 is documented.

Third review

  • Segmented MFF scales to microvolts, derives xmin from eventBegin and beginTime, and reads event tracks (code, label, duration, mffkey_*). The default time unit was corrected in the fourth review.
  • cluster.sets is saved as a numeric matrix. scipy.loadmat keeps shapes (2, 1) and (2, 2).
  • The v7.3 header version was corrected to 0x0200 in the fourth review. A 2-dataset study with a design reloads in Python. The fifth review records the later MATLAB load('-mat') check.
  • pop_studyerp and pop_studywizard do not preload files. A 2x2 ERP grid yields four datasets, (S01,A), (S01,B), (S02,A), (S02,B). Using one file twice raises the duplicate-dataset error.
  • pop_loadeeg history ends the folder with a file separator.
  • round(X)==-3, >=, <=, and ~= still update the channel. pop_chanevent.m line 225 does not. That difference is documented. bitand on a negative or non-integer channel raises an error that names pop_chanevent. EEGLAB also rejects bitand(abs(round(X)),1) on single-precision EEG.data.
  • task-<task>_events.json is written at the dataset root. Power-line frequency is a number when one is supplied, and n/a otherwise.
  • The export wizard shows 10 rows, column headers, a browse button on each row, and < > paging. Buttons are Help, Cancel, Ok.
  • The channel-event labels fit their column in a 720 px dialog. The 2x2 ERP grid is sized to its contents.

Fourth review

  • Missing MFF time units are microseconds. tests/fixtures/testmff.mff is EEGLAB sample_data/test_data/testmff.mff at 8ac485f6, and test_real_testmff_matches_eeglab_epochs imports it. Shape (257, 300, 2), max abs 19.749, xmin -0.202002, 10 events including the per-trial ULRN and LRND events, track durations 1000 samples, and EEG.epoch from eeg_checkset.
  • The v7.3 header bytes 124-127 are 00 02 IM. Structs are groups. Cell arrays and struct-array fields are object references into #refs#. A (2, 1) sets reloads as (2, 1). The fifth review records the later MATLAB load('-mat') check. The test writes pair.study under pytest's tmp path. With --basetemp=/tmp/eegprep-v73-pair the file was /tmp/eegprep-v73-pair/test_v73_study_with_two_datase0/pair.study.
  • Participant history is [EEG, STUDY, command] = pop_participantinfo(EEG, STUDY);. EEGLAB is interactive-only. EEGPrep's rows argument still scripts the table.
  • Weighted-column labels are not forced to their natural minimum width. pop_chanevent wraps the long labels. Dialog width is 720 px. test_f89_default_options_are_visible_without_scrolling passes.
  • Resaving a memory-mapped dataset to the same .fdt closes that mapping before the replace. Windows denied the replace while the file was still mapped.

Fifth review

At d64e7f8b. The sixth review replaces the clock-latency, empty-array, and CLear notes.

  • v7.3 MATLAB_class is a fixed-length ASCII scalar (|S4 'char', |S6 'double', 'struct', and so on), not an HDF5 vlen string. Char data stays uint16 UTF-16-LE. A non-empty char carries MATLAB_int_decode as int32 2.
  • MFF events that share a latency keep file order. On testmff.mff the first three types are stm+, LRND, LRND.
  • pop_mffimport returns eeg_checkset directly. The comments that named testmff.mff are gone.
  • Resave drops the memmap ndarray, then closes its mmap, inside a context manager before os.replace. gc.collect() is gone. The Linux resave test passes. Windows CI is the lock check.

MATLAB check for the v7.3 study

MATLAB R2025b on jamming already loaded this v7.3 STUDY (load -mat, pop_loadstudy with real datasets, std_checkset, and resave). The snippet below is the check that was used. name is 'Pair', filename is 'pair.study', and notes is ''.

uv run pytest tests/test_file_menu_audit_673.py::test_v73_study_with_two_datasets_and_a_design_reloads --basetemp=/tmp/eegprep-v73-pair

studyFile = 'pair.study';
S = load('-mat', studyFile);
fprintf('load class name=%s filename=%s notes=%s\n', class(S.STUDY.name), class(S.STUDY.filename), class(S.STUDY.notes));
assert(strcmp(class(S.STUDY.name), 'char'));
assert(strcmp(class(S.STUDY.filename), 'char'));
assert(strcmp(class(S.STUDY.notes), 'char'));
[STUDY, ALLEEG] = pop_loadstudy('filename', studyFile);
fprintf('pop_loadstudy class name=%s filename=%s notes=%s\n', class(STUDY.name), class(STUDY.filename), class(STUDY.notes));
assert(strcmp(class(STUDY.name), 'char'));
assert(strcmp(class(STUDY.filename), 'char'));
assert(strcmp(class(STUDY.notes), 'char'));

A later complaint that s01.set is missing is separate from Cannot read file / STUDY set file 'STUDYfile' not loaded.

Sixth review

Verified on MATLAB R2025b: the v7.3 STUDY loads, the exact MFF latency is 50.99 samples, and pop_studywizard opens. The seventh review corrects the mffkeys spacing below.

  • pop_studywizard(gui=True) and the BIDS export grid open in the real Qt renderer. Each Clear callback sets "button": f"clear{index}", which qt.py reads when it connects clear_widgets. test_wizard_dialogs_open_in_the_qt_renderer builds both dialogs offscreen and clicks Clear.
  • Clock latency is the exact microsecond difference between beginTime and recordTime, times srate. The first stm+ on testmff.mff is 203960 microseconds, which is 50.99 samples at 250 Hz. The first epoch eventlatency is -2.042 ms. EEGLAB reports 50.990568 because mff_decodetime.m uses 1.15251e-11 days per microsecond (0.42% below 1e-6/86400) and MATLAB's string datenum mis-parses the timestamp by 0.16 to 2.44 microseconds. EEGPrep does not copy either error. The migration notes, storage.rst, and pop_mffimport help say this.
  • classid is EVNT when a track event's XML omits it (Event.getClassID()). Category segments keep the <seg status="..."> attribute, and track events carry status as well.
  • The displayed Clear label is Clear. pop_studywizard.m writes CLear; supergui recapitalises it. Both wizard grids show a browse header, row numbers, and no header over Clear. The BIDS welcome button is Continue, with the bids_exporter.m text.
  • A 1-D empty (np.array([]), the shape of cache, changrp, group, run, and session) is stored as uint64 [0 0], so MATLAB reads 0-by-0. An empty char has MATLAB_empty and does not have MATLAB_int_decode. A non-empty char still has int32 2. MATLAB R2025b confirmed the v7.3 load.
  • pop_chanevent uses the 10-row pop_chanevent.m geometry, including the two spacer rows and (set = yes) beside Delete event channel(s)?.
  • File > Save no longer sets saved again in _apply_save_metadata; pop_saveset and mark_current_saved already do. The migration notes say a BIDS folder import writes the derivative .set files and the .study file to disk under derivatives/eeglab.

Seventh review

  • mffkeys matches EEGLAB's char(keylist), including the space after each colon (character codes 35, 58, 32, 49). The first stimulus is [cel#: 1, obs#: 3, pos#: 3, argu: 0]. Category events use the same text, for example [#seg: 15, subj: ...].
  • Category events also carry mffkeysbackup and classid set to ''. Track events still use EVNT when the XML omits classid.
  • pop_studywizard is 1186 by 500, the EEGLAB dialog size. The eighth review keeps that size when many files are selected.
  • The BIDS welcome Continue button is 110 px wide, so the label is not clipped to :ontinue. The test checks that the button's contents are at least as wide as the text.
  • Export-grid page 2 numbers the rows 11-20. Page 1 stays 1-10.
  • A BIDS import that cannot write derivatives/eeglab raises pop_importbids and tells you to copy the dataset to a writable folder. The migration notes name DataLad and OpenNeuro mounts as that case.

Eighth review

  • A study wizard with 40 files stays 1186 by 500, inside a 1280 by 800 screen. The file rows scroll vertically. There is no horizontal scrollbar. Clear on the first row is in the viewport, and after scrolling to the end Clear on row 40 is in the viewport. Ok stays below the scroller, so it stays reachable.
  • A read-only derivative write raises the pop_importbids error from the filesystem OSError. The ninth review restores the wrapped pop_saveset and pop_savestudy messages.

Ninth review

  • Saving a .set or a .study into a directory mode 0o555 again raises could not write and tells you to choose a writable path. The import path rewraps that ValueError only when its cause is an OSError, so a read-only BIDS import still says to copy the dataset to a writable folder.
  • The study-wizard scroll area fills the 1186 by 500 dialog. Row 10's Clear is visible with no vertical scrolling. A 40-file dialog stays inside 1280 by 800, and Ok stays reachable.

Tenth review

  • Ok, Cancel, and Help use the larger of the requested button size and the button's size hint in each dimension. A 28 px "Continue" grows past 110 px, so the label is not clipped.
  • Empty channel coordinates, including the (1, 0) X/Y/Z arrays on eeglab_data_epochs_ica.set, are missing. electrodes.tsv writes n/a for those cells, the same token EEGLAB's bids_writeelectrodefile uses when X is empty.
  • scipy.io.savemat rewrites a failed open of a path that is not a string as "Reader needs file name or open file-like object", hiding the permission error. The study writer passes a string path, so a read-only save says permission denied on that path inside the existing could-not-write message.

Eleventh review

Twelfth review

  • electrodes.tsv uses LF. The other export TSVs already did. JSON sidecars, README, CHANGES, and the preprocessing TSV and JSON writers open with an LF newline, so Windows does not turn those files into CRLF. The electrode test compares the file bytes, and the same export checks channels, events, and participants the same way.

Thirteenth review

  • Merged develop at a010da1c ([CI] Keep other PR comments from cancelling a Claude review #682) so .github/workflows/claude-code-review.yml matches.
  • Save study passes the datasets pop_savestudy returns when resave is on. The resaved dataset is saved='yes' with its filename and filepath, and a second Save study does not ask.
  • Quit and study resave call pop_saveset with savemode='resave'. When a modified raw BIDS .set would be overwritten, the file keeps its bytes and mtime, the warning explains the refusal, and the window stays open.
  • A same-path .fdt resave on POSIX drops the memmap handle with close() and replaces the file, so a live array view keeps its values. Windows unmaps only when no view is held; otherwise pop_saveset refuses and says to close the plot or console reference, or Save as a new file.

Fourteenth review

Checklist

  • 1. BIDS import writes derivatives/eeglab and refuses a raw-folder resave.
  • 2. pop_chanevent numeric edges, leading default, and MATLAB expression rules.
  • 3. Atomic .set/.fdt replace; a failed save leaves the original.
  • 4. Epoched and ICA export are column-major with LF.
  • 5. Save study writes MATLAB v6, falls back to v7.3, strips measures on disk, and rewrites a JSON .study as MATLAB.
  • 6. CNT latency is the 0-based loadcnt offset plus 1, with no duration.
  • 7. .eeg imports through pop_loadeeg with positional history and latency order.
  • 8. .mff imports through pop_mffimport using read_raw_egi plus category segments.
  • 9. Task info reaches the export, and a missing power-line frequency is prompted.
  • 10. Participant editor stores the table rows. History is EEGLAB's interactive line; rows scripts the table in EEGPrep.
  • 11. Simple ERP STUDY has a browse button per dataset and condition-major indexes.
  • 12. BIDS export wizard takes any row count and one task per file.
  • 13. BIDS export writes task-<task>_events.json and channel type from chanlocs.type.
  • 14. Event info stores Levels, LongName, Description, and Units.
  • 15. validate_bids flags run-, task-, desc-, and rec- on coordsystem names. acq- is allowed.
  • 16. Browse-for-datasets history is std_editset and keeps the grid fields.
  • 17. Study history is a replayable EEGLAB command cell.
  • 18. pop_runscript checks every .m line before running any of them.
  • 19. Dataset history is pop_saveh(EEG.history, ...).
  • 20. Load dataset history is pop_loadset('filename', ..., 'filepath', ...).
  • 21. An empty extension catalog says third-party extensions are pip packages.
  • 22. Event export uses LF.
  • 23. File imports go through pop_newset.
  • 24. BIOSIG setnames and option_single staying float64.
  • 25. BrainVision .mat history is pop_loadbva.
  • 26. FILE-IO honors the data-format popup, including dataformat.
  • 27. Multi-line comments round-trip.
  • 28. Migration notes cover the quit prompt, CNT latency, sessionless BIDS paths, and ERP subject codes.
  • D. Quit asks before discarding unsaved datasets. EEGLAB closes without asking; the difference is documented.

Earlier local verification

tests/test_file_menu_audit_673.py (64 tests), tests/test_pop_saveset.py, tests/test_study_metadata.py, tests/test_file_menu_pop_functions.py, tests/test_storage.py, and tests/test_gui_pop_study.py passed locally (132). ./pre-commit.py --all-files passed. uv run ruff format --check . passed. uv run ruff check . passed. An earlier MATLAB R2025b check loaded the v7.3 study, verified the 50.99-sample latency and opened the study wizard.

After the f6bea53c merge, 602 file-menu, save, study and Edit/Tools tests passed and 12 were skipped. tests/test_pop_select.py::TestPopSelectParity::test_parity_trial_subset failed because this environment has no EEGLAB checkout. ./pre-commit.py --all-files passed. uv run ruff format --check . passed.

The diff against develop contains no changes to tests/fuzz/tolerances.toml, goldens or parity JSON files.

Open in Web Open in Cursor 

Save datasets atomically, write EEGLAB MATLAB v6 study files, keep BIDS
imports out of the raw folder, and align the File-menu importers, export,
and study dialogs with the Nov 23, 2026 audit.

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

Code review

  • Overall assessment: Needs changes. Most of the audit fixes look correct: the pop_chanevent expression evaluator, the CNT 0-based offset plus 1, column-major export, LF writers, the v6/v7.3 STUDY writer, and the BIDS derivative import. Three new GUI and save paths have regressions.
  • Highest-risk area: The save paths for datasets and STUDY (menu_actions.py quit/save-study, and the same-file .fdt replace in pop_saveset).
  • Merge recommendation: Needs changes.

Blocking

None.

Important

  1. Save study: datasets resaved after "Yes" stay marked unsaved in the session. src/eegprep/functions/guifunc/menu_actions.py lines 924-947. The new prompt sets resavedatasets="on". But pop_savestudy resaves deep copies of the datasets (datasets = [deepcopy(eeg) ...]) and returns them as _datasets. The menu discards _datasets and calls self.session.set_study(study, command=command). As a result, session.ALLEEG keeps saved == "no" and the old filename/filepath. The next Save study asks again. Quit also reports those datasets as unsaved, and choosing "Yes" there rewrites them a second time. Fix: when resavedatasets == "on", pass the returned datasets back with self.session.set_study(study, _datasets, command=command). Add a GUI test that checks session.ALLEEG[i]["saved"] == "yes" after a "Yes".

  2. Quit → "Yes" skips the new raw-BIDS overwrite guard. menu_actions.py line 383 calls pop_saveset(eeg, target) with an explicit filename and no savemode. _save_target only calls _refuse_raw_bids_resave when savemode == 'resave' (pop_saveset.py lines 649-667). Raw BIDS datasets often store .set files under sub-*/eeg/. If a user loads one with File > Load existing dataset, edits it, and then quits with "Yes", the raw file is overwritten. Checklist item 1 of this PR says that should be refused. Fix: call pop_saveset(eeg, savemode="resave") here, which uses dataset_set_path and the guard. Catch the ValueError and show it with self._warn(...), then return without quitting.

  3. Resaving a memory-mapped dataset to its own .fdt now fails if any NumPy view of the data is still alive. pop_saveset.py lines 604-605 call MemmapData.close_file(), which calls array._mmap.close() directly. MemmapData.close() in the same file (storage.py lines 216-219) explains why that is unsafe: slices keep the map exported. In that case CPython raises BufferError: cannot close exported pointers exist. pop_saveset then reports this as "could not write …". Such views are common, for example x = EEG['data'][0] in eegprep-console, or a plot that still holds a slice. Before this change, the same resave worked on Linux and macOS. Fix: close the handle only where the OS requires it (os.name == "nt") and keep close() semantics elsewhere. Or catch BufferError and raise a pop_saveset error that names the cause and the fix. Add a test that holds a view, then resaves.

Nits

  • src/eegprep/resources/help/pop_savestudy.md is now wrong. It says the file is "EEGPrep-owned .study JSON" and shows STUDY, com = pop_savestudy(..., return_com=True). The function now writes MATLAB v6/v7.3 by default and always returns (study, datasets, command). AGENTS.md: "When adding a user-facing function or GUI dialog with a Help button, add or update the corresponding Markdown help resource". Update the usage lines and the format paragraph. Also, return_com in pop_savestudy's signature is now never read. Either honor it, as the other pop_* STUDY functions do, or remove it and update the callers that pass it.

Test gaps

  • No test covers the GUI "resave modified datasets? → Yes" path (finding 1) or the quit → "Yes" path on a dataset under a raw BIDS root (finding 2).

EEGLAB parity notes

None beyond the differences the PR already documents.


def _looks_segmented(path: Path) -> bool:
folder = path if path.is_dir() else path.parent
return any(folder.glob("Categories*")) or any(folder.glob("epochs*"))

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.

Blocking: every MFF is treated as segmented. Continuous MFF recordings also contain epochs.xml, one entry per recording block. Because of that, folder.glob("epochs*") matches every .mff folder. Continuous files then go through mne.read_epochs_egi instead of read_raw_egi, and they either fail or import as the wrong kind of dataset.

def _looks_segmented(path: Path) -> bool:
folder = path if path.is_dir() else path.parent
return any(folder.glob("Categories*")) or any(folder.glob("epochs*"))

Fix: base the check on categories.xml only. pop_mffimport.m creates epochs only when categories exist.

Suggested change
return any(folder.glob("Categories*")) or any(folder.glob("epochs*"))
return (folder / "categories.xml").is_file()

There is no testmff.mff fixture in the tree. Even a small synthetic folder with only the XML files would lock this branch with a test.

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 34ab759. _looks_segmented now looks only for categories.xml or Categories.xml. A folder that has epochs.xml and no categories file stays continuous. test_mff_segmentation_follows_categories_not_epochs_xml builds that folder.

for index, row in enumerate(np.asarray(epochs.events)):
event = {
"type": str(row[2]),
"latency": float(index * epochs.times.size + row[0] + 1),

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: epoch event latencies are wrong. For MNE Epochs, events[:, 0] is the absolute sample in the original continuous recording, not an offset inside the epoch. So index * pnts + row[0] + 1 can exceed pnts * trials, and eeg_checkset will drop or reject these events.

metadata = getattr(epochs, "metadata", None)
for index, row in enumerate(np.asarray(epochs.events)):
event = {
"type": str(row[2]),
"latency": float(index * epochs.times.size + row[0] + 1),
"epoch": index + 1,
}

Fix: put the time-locking event at the zero-time sample of each epoch, which is the EEGLAB convention for epoched latencies.

Suggested change
"latency": float(index * epochs.times.size + row[0] + 1),
"latency": float(index * epochs.times.size + int(np.argmin(np.abs(epochs.times))) + 1),

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 34ab759. Epoch events are placed at the zero-time sample of each epoch (argmin(abs(times))), not at events[:, 0]. The same test checks a time axis of [-0.1, 0, 0.1] and an event sample of 5000, and expects latency 2.

Comment on lines +37 to +44
result = inputgui(pop_mffimport_dialog_spec(), renderer=renderer)
if not result:
return ({}, "") if return_com else {}
try:
import mne
except ImportError as exc:
raise ValueError(
"pop_mffimport: MNE is required to read EGI MFF. Install it with `uv sync --group dev`, then import again."

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: two problems in this block.

  1. The typefield choice from the dialog is thrown away. result is only checked for Cancel, so picking label or mffkeys has no effect. Either use it to choose the event type (_epoch_events / mne_raw_to_eeg) and record it in the history command, or remove the dialog.
  2. mne is the eegprep[mne] extra, but the error tells pip users to run uv sync --group dev. Use the shared helper, as pop_fileio.py:152 does, so the message names the right extra:
mne = import_optional_dependency("mne", feature="pop_mffimport")

That also removes the local try/import.

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 34ab759. The dialog choice is typefield code, label, or mffkeys. It is a real argument, it selects the epoch event type, and the history command records it. MNE is loaded with import_optional_dependency("mne", feature="pop_mffimport"), so a missing install names eegprep[mne].

):
text = str(result.get(tag) or "").strip()
if text:
ranges[key] = text

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: dialog subsets crash loadeeg. The edit-box text goes in unparsed. loadeeg._one_based_indices runs np.asarray(value, dtype=float), so input like 1 2 3 or 1:10 raises ValueError: could not convert string to float. Only a single number works.

def _one_based_indices(value: Any, size: int, name: str) -> np.ndarray:
if _is_all(value):
return np.arange(size, dtype=int)
numeric = np.asarray(value, dtype=float).reshape(-1)
if np.any(numeric != np.floor(numeric)):

Fix: parse the text the same way pop_fileio does: ranges[key] = parse_numeric_sequence(text, dtype=int), imported from _pop_utils.

Related: the history at L84 is always pop_loadeeg(path), and pop_loadeeg takes no subset or precision kwargs. A GUI import that uses subsets therefore can't be replayed. Add the options to the signature and write them into the command.

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 34ab759. Subset text goes through parse_numeric_sequence, so 1:3 and 1 2 become integer lists before loadeeg. pop_loadeeg now takes triallist, typerange, chanlist, responsetype, and format, and the history command includes the ones that were set. test_pop_loadeeg_parses_subset_text_into_replayable_history covers the parse.

relative = resolved.relative_to(parent)
except ValueError:
return None
if relative.parts and relative.parts[0] == "derivatives":

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: resaving inside a derivatives pipeline is refused. BIDS derivative folders have their own dataset_description.json. For example, bids_preproc writes derivatives/eegprep/dataset_description.json (bids_preproc.py:1255).

Take derivatives/eegprep/sub-01/eeg/x.set. The loop stops at derivatives/eegprep, relative.parts[0] is sub-01, and that folder is returned as a raw root. File > Save then refuses a file that is already a derivative.

def raw_bids_root(path: Path) -> Path | None:
"""Return the BIDS root when ``path`` is a raw file outside ``derivatives/``."""
try:
resolved = path.resolve()
except OSError:
resolved = path
for parent in (resolved.parent, *resolved.parent.parents):
if not (parent / "dataset_description.json").is_file():
continue
try:
relative = resolved.relative_to(parent)
except ValueError:
return None
if relative.parts and relative.parts[0] == "derivatives":
return None
return parent
return None

Fix: return None when any ancestor is named derivatives, or when the found description has "DatasetType": "derivative". Add a test that resaves a file under derivatives/<pipeline>/ with its own description present.

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 34ab759. raw_bids_root returns no raw root when the path has a derivatives ancestor or the description it finds has DatasetType: derivative. A resave under derivatives/eegprep/ with its own description is allowed. test_derivative_dataset_can_be_resaved writes that layout and resaves. A file in the raw BIDS folder is still refused.

_write_study(path, study, fileformat)
command = build_matlab_call(
("STUDY", "ALLEEG"),
"pop_savestudy",

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: replaying this history in the console overwrites ALLEEG with a string. The command is now [STUDY ALLEEG] = pop_savestudy(...), which the console translates to STUDY, ALLEEG = pop_savestudy(...).

pop_savestudy returns (study, command). _extract_pop_study_state turns that into a ConsoleStudyResult with includes_alleeg=False, whose __iter__ yields (study, command). The replay therefore sets ALLEEG to the history string.

def __iter__(self) -> Iterator[Any]:
yield self.study
if self.includes_alleeg:
yield self.alleeg
else:
yield self.command

Fix: either keep the target as ("STUDY",), or have pop_savestudy return (study, ALLEEG, command). test_matlab_study_history_is_console_replayable only runs ast.parse on an std_editset line. Extend it to run the pop_savestudy command through the console and assert that ALLEEG is still a list.

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 34ab759. return_com=True now returns (study, datasets, command). The console study result therefore yields the dataset list as ALLEEG instead of the history string. Callers that unpacked two values were updated. test_pop_savestudy_replay_keeps_alleeg_as_datasets runs the command in the console and checks that ALLEEG is still a list of datasets.

{
"bids_field": bids_field,
"eeglab_field": eeglab_field,
"Levels": "",

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: reopening Event info erases saved Levels, LongName, and Units. The table always starts with blank Levels, LongName, and Units. When the user presses Ok, _event_field_map builds a new dict per field, and .update(metadata) replaces the stored dict, so values entered earlier are lost.

Fix: when current is a dict, prefill every column from it, e.g. "Levels": str(current.get("Levels") or ""). Levels is a dict in BIDS, so it needs a round-trippable text form. Do the same for LongName and Units, and add a test that opens the table twice.

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 34ab759. Reopening the event table prefills Levels, LongName, Description, and Units from the stored field. Levels of the form 1=rare is stored as a dict and shown again as 1=rare. test_event_info_reopen_keeps_levels_longname_and_units writes the row, rebuilds the table rows, and writes them back.

datasets = []
task = "eeg"
for entry in entries:
dataset = pop_loadset(str(entry["file"]))

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: the wizard cannot read raw files. The welcome page says "Continue to choose raw files", but every grid row is loaded with pop_loadset, which only reads .set files. An .edf, .bdf, or .vhdr row fails with "not a valid EEG .set dataset". EEGLAB's bids_exporter.m exists to convert raw recordings.

Fix: dispatch by extension to the existing importers (pop_biosig, pop_loadbv, pop_fileio), the same way MenuActionDispatcher._import_dataset does. If that is out of scope, change the welcome text and grid label to say .set files.

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 34ab759. The wizard loads .edf, .bdf, and .gdf with pop_biosig, BrainVision .vhdr with pop_loadbv, .set with pop_loadset, and anything else with pop_fileio. test_bids_wizard_sends_edf_to_pop_biosig checks that an .edf row reaches pop_biosig.

cursoragent and others added 3 commits November 23, 2026 20:31
Segment MFF only when categories exist, keep epoch events at time zero,
and let study-history replay leave ALLEEG as datasets. Derivative BIDS
folders can be resaved, and the export wizard reads raw recordings.

Co-authored-by: Suraj Ranganath <[email protected]>
A MATLAB study stores cluster sets as a matrix with one column per
component. Flattening that matrix made pop_clust reject the parent
cluster. Also declare the MFF importer's MNE extra and narrow the
Neuroscan import result for the type checker.

Co-authored-by: Suraj Ranganath <[email protected]>
Keep a (2, 1) cluster sets matrix, add one to CNT event latency, and epoch segmented MFF from categories.xml. Study and BIDS history now replays in EEGLAB, including per-file tasks, shared events.json, and MATLAB expression rules.

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

cursor Bot commented Nov 23, 2026

Copy link
Copy Markdown

🤖 Follow-up at 0b508e6b for the remaining Claude review notes that were not inline threads, and for the box/EEGLAB pass on 36e13f1d.

  • pop_studywizard history is now [STUDY ALLEEG] = std_editset(STUDY, [], 'commands', {...}, 'updatedat', 'on') plus std_checkset. Each command cell keeps subject, session, run, condition, group, and task.
  • The participant table no longer stores {'rows': N}. The history line is pop_participantinfo(..., 'rows', { {'participant_id', ...}, ... }).
  • Channel type comes from chanlocs.type when it is set. The label is only the fallback, and EOG already covers HEOG/VEOG.
  • The all-true enabled column is gone from the chanevent spec, and Quit no longer sets saved again after pop_saveset.
  • Cluster sets of shape (2, 1) stay rows by components. CNT latency is the 0-based loadcnt offset plus 1. Segmented MFF uses read_raw_egi and categories.xml / epochs.xml (locked MNE 1.12.1 has no read_epochs_egi). pop_chanevent uses MATLAB round, integer bitand, left-to-right comparisons, and ~.
  • Folder import history is [STUDY ALLEEG] = pop_importbids(...) with no return_study. A dataset with no ses- folder is saved under sub-<label>/eeg.
  • pop_savestudy strips precomputed measures on disk, falls back to MATLAB 7.3, rewrites a JSON .study as MAT, and always returns (study, datasets, command).
  • pop_studyerp has a ... browse button on every dataset and uses EEGLAB's condition-outer index. pop_runscript rejects an unsupported line before running anything else.

The eight earlier inline threads already have replies. CI on 0b508e6b is still running, including the EEGLAB Python backend job that failed at 34ab7595. I could not convert this ready PR back to draft from here; it should not be treated as ready for another Claude review until that run is green.

A folder import returns STUDY and ALLEEG. The gallery example still
indexed that pair as a dataset, which failed the docs build.

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

cursor Bot commented Nov 23, 2026

Copy link
Copy Markdown

🤖 Docs build failed at 0b508e6b because examples/plot_import_data.py treated a folder import as a dataset list. A folder import returns (STUDY, ALLEEG). f3ed5166 unpacks that pair, and the local HTML build succeeds. CI on that head is running, including the EEGLAB Python backend job. This PR should stay unreviewed until that run is green.

Ruff format rejects the wrapped ternary in the synthetic CNT writer.

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

cursor Bot commented Nov 23, 2026

Copy link
Copy Markdown

🤖 Ruff format failed at f3ed5166 on the wrapped ternary in tests/test_cnt_eeglab_tests.py. 86abcb59 formats that line. The docs build and the EEGLAB Python backend job both passed at f3ed5166. CI on 86abcb59 is running. This PR should stay unreviewed until that run is green.

Segmented MFF uses the XML time unit, microvolts, epoch xmin, and event tracks. Cluster sets stay numeric matrices, and the v7.3 writer uses a MATLAB header and unique #refs#. ERP loads no longer insert the same file twice. BIDS events.json is at the dataset root, power-line frequency is numeric, and the export grid pages.

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

cursor Bot commented Nov 23, 2026

Copy link
Copy Markdown

🤖 Round 3 is ebde121b. tests/test_file_menu_audit_673.py is 53 passed, 1 skipped. Ruff and ty are clean. MATLAB load('-mat') was not run.

  1. Segmented MFF now scales to µV, derives xmin from eventBegin/beginTime, reads Events_.xml (code, label, duration, mffkey_), and uses the XML time unit (default ns). A synthetic file checks shape (257, 300, 2), max 1e6, xmin -0.202, and the track events. testmff.mff is not here, so test_real_testmff_matches_eeglab_epochs skips. Not verified on the real file.
  2. cluster.sets round-trips through scipy.loadmat as float arrays of shape (2, 1) and (2, 2).
  3. The v7.3 writer uses header bytes 124:128 00 01 IM, MATLAB_class=struct, and unique #refs# names. A 2-dataset study plus a design reloads with pop_loadstudy. MATLAB load was not run.
  4. A 2x2 pop_studyerp grid loads four datasets: (S01, A, a1.set), (S01, B, a2.set), (S02, A, a3.set), (S02, B, a4.set). The same file twice raises "Duplicate dataset ... Copy and rename".
  5. pop_loadeeg history ends the folder with a trailing separator. Both participant-info history forms are [EEG, STUDY, command] = pop_participantinfo(EEG, STUDY, ...).
  6. round(X)==-3, >=, <=, and ~= still change the channel. That difference from pop_chanevent.m:225 is in eeglab_migration.rst. bitand on a negative or non-integer channel raises an error that names pop_chanevent and says to round or take abs first.
  7. task-<task>_events.json is written at the BIDS root, not under sub-*/eeg.
  8. PowerLineFrequency is JSON number 60 from the prompt and 50 from an EEG value of "50". A scripted export with no value stays "n/a".
  9. The export grid has 10 rows, the column headers, a ... button on each row, and < > paging. Page 2 stores dataset 11.
  10. The four clipped pop_chanevent labels each have width >= sizeHint after the dialog is shown.
  11. The 2x2 studyerp grid has no scroll area, and the hint label fits the dialog.

cursoragent and others added 2 commits November 23, 2026 22:42
Epoch and category times without a unit are microseconds, matching
mff_import.m on EEGLAB's testmff.mff. The v7.3 study header is version
0x0200 and object references point at #refs# datasets. Participant-info
history is the interactive EEGLAB line, and weighted-column labels no
longer force every dialog wider.

Co-authored-by: Suraj Ranganath <[email protected]>
Windows denies the replace while the .fdt is still memory-mapped, so
resaving that dataset to the same file failed in CI.

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

cursor Bot commented Nov 24, 2026

Copy link
Copy Markdown

🤖 Round 4 is on de96e936. CI on that commit is green: docs, ruff/ty, pre-commit, the base install, the EEGLAB Python backend, Python 3.12 ubuntu/macos/windows, Python 3.13 ubuntu, the E1 report, and the Pyodide/ICLabel job. Pages deploy was skipped.

  1. Segmented MFF. tests/fixtures/testmff.mff is EEGLAB sample_data/test_data/testmff.mff at 8ac485f6 (the file is not at sample_data/testmff.mff). test_real_testmff_matches_eeglab_epochs no longer skips. Import of that folder: shape (257, 300, 2), max abs 19.749235153198242, xmin -0.202002, 10 events. Track durations are 1000 samples. The two category time-locks are ULRN at latency 51.5005 and LRND at 351.5005. EEG.epoch has length 2 and each epoch has event and eventlatency, built by eeg_checkset. MATLAB was not run in this environment, so this is the Python import of the real file, not a new ml_mff.set diff.

  2. v7.3 study. Header bytes 124-127 are 00 02 49 4d. Structs are groups with MATLAB_class=struct. Struct-array fields are object references into #refs# with no MATLAB_class on the pointer and no value wrapper. Python reload keeps sets shapes (2, 1) and (2, 2). MATLAB load('-mat') was not run here. The test writes pair.study under pytest's tmp path. On this machine, uv run pytest tests/test_file_menu_audit_673.py::test_v73_study_with_two_datasets_and_a_design_reloads --basetemp=/tmp/eegprep-v73-pair wrote /tmp/eegprep-v73-pair/test_v73_study_with_two_datase0/pair.study.

  3. Participant history is exactly [EEG, STUDY, command] = pop_participantinfo(EEG, STUDY);. rows still writes the table in EEGPrep. eeglab_migration.rst says EEGLAB's function is interactive-only.

  4. The weighted-column minimum-width change in qt.py is reverted. pop_chanevent word-wraps the long labels. The built dialog is 720 by 562, and each of those four labels is wider than its full text (237-262 px of text in a 332 px column). test_f89_default_options_are_visible_without_scrolling passed locally and the 3.13 ubuntu / 3.12 windows / 3.12 macos jobs are green.

Windows also failed test_memmap_resave_to_same_sidecar_preserves_data on acb8471c with WinError 5 while replacing a still-mapped .fdt. de96e936 closes that mapping before the replace. That job is green on this commit.

cursoragent and others added 6 commits November 24, 2026 00:35
Char and empty MATLAB values now use fixed-length class names, uint64
empty dimensions, and UTF-16 decode flags. MFF events keep file order,
datenum latencies, and the EEGLAB key fields.

Co-authored-by: Suraj Ranganath <[email protected]>
The Qt renderer reads a button key that the Clear callbacks omitted. Clock latency is the exact microsecond difference, and a 1-D empty MATLAB array is stored as 0-by-0 without MATLAB_int_decode on an empty char.

Co-authored-by: Suraj Ranganath <[email protected]>
mffkeys keeps the space after each colon. The study wizard is 1186 by 500 so Clear stays in view, the BIDS welcome button fits Continue, and later export pages number rows from 11.

Co-authored-by: Suraj Ranganath <[email protected]>
The 1186 by 500 dialog scrolls vertically so Ok stays reachable, and a read-only BIDS import reports pop_importbids from the filesystem error.

Co-authored-by: Suraj Ranganath <[email protected]>
Read-only saves again say which function failed and to choose a writable path. The wizard scroller fills the 500 px dialog, so row 10 stays on screen and a long file list still scrolls.

Co-authored-by: Suraj Ranganath <[email protected]>
Dialog buttons grow to their text when a fixed size would clip. Empty channel coordinates export as n/a. A read-only study save reports permission denied on the path.

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

Copy link
Copy Markdown
Member Author

claude review this

return_com=True,
)
self.session.echo_command(command)
self.session.set_study(study, command=command)

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: pop_savestudy resaves deep copies of the datasets and returns them as _datasets. This line drops them, so after the user answers "Yes", session.ALLEEG still has saved == "no" and the old filename. The next Save study prompts again, and Quit treats the datasets as unsaved.

Suggested change
self.session.set_study(study, command=command)
self.session.set_study(study, _datasets if resavedatasets == "on" else None, command=command)

See

study, datasets = std_checkset(ensure_study(STUDY), EEG)
datasets = [deepcopy(eeg) for eeg in datasets]
path = _save_path(study, filename, filepath, savemode=savemode)
path.parent.mkdir(parents=True, exist_ok=True)
if resavedatasets == "on":
_resave_datasets(study, datasets, path.parent)
study["filename"] = path.name

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🤖 Save study now keeps the datasets pop_savestudy returns when the user chooses Yes: self.session.set_study(study, _datasets if resavedatasets == "on" else None, command=command). A dataset with saved='no' becomes saved='yes' with its filename and filepath updated, and a second Save study does not ask again.

"Use File > Save current dataset as, then quit again.",
)
return
pop_saveset(eeg, target)

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: This call passes an explicit filename and no savemode, so the new raw-BIDS guard never runs. _refuse_raw_bids_resave only runs for savemode == 'resave':

filepath = options.get('filepath')
if savemode == 'resave' and filename in {None, ''}:
target = dataset_set_path(EEG)
if target is None or target.suffix.lower() != '.set':
shown = os.fspath(target) if target is not None else '(none)'
raise ValueError(
"pop_saveset cannot resave this dataset because it has no .set filename "
f"(current filename is {shown}). Save it with File > Save current dataset as "
"and choose a .set file."
)
_refuse_raw_bids_resave(target)
return target, savemode
if filename in {None, ''}:
raise ValueError("file_name argument is required")
path = Path(os.fspath(filename))
if filepath not in {None, ''} and not path.is_absolute():
path = Path(os.fspath(filepath)) / path.name
target = _as_set_path(path)
if savemode == 'resave':
_refuse_raw_bids_resave(target)
return target, savemode

A raw BIDS dataset stored as .set under sub-*/eeg/ that was edited and then saved from Quit → "Yes" is overwritten in place.

Fix: call pop_saveset(eeg, savemode="resave"). Catch the ValueError, show it with self._warn(parent, str(exc)), and return without closing.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🤖 Quit → Yes now calls pop_saveset(eeg, savemode="resave"). A ValueError is shown with _warn and the window stays open. Study resave calls pop_saveset(eeg, path, savemode="resave"), so _refuse_raw_bids_resave runs. Quit → Yes on an edited raw-BIDS .set leaves the bytes and mtime unchanged and the warning names the refusal. pop_savestudy(..., resavedatasets='on') on a raw-BIDS dataset raises that refusal.

os.remove(file_name)
scipy.io.savemat(set_tmp, eeglab_dict, appendmat=False, long_field_names=True)
if save_two_files:
with _unlocked_sidecar(data_value, fdt_final):

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: close_file() calls array._mmap.close() directly. If any NumPy view of the mapped data is still alive, CPython raises BufferError: cannot close exported pointers exist. Common cases are x = EEG['data'][0] in eegprep-console and a plot that still holds a slice. The resave then fails with "could not write …", although it worked on Linux and macOS before this change. MemmapData.close() explains this hazard:

def close(self) -> None:
"""Flush and release the backing memory map handle."""
array = self._array
if array is None:
return
self._array = None
array.flush()
# Do not close ``array._mmap`` directly: NumPy slices can retain views
# of this map after the handle object is replaced inside an EEG dict.
# Releasing our reference lets NumPy close the OS map once every view
# is gone and avoids invalidating those still-live arrays.
def close_file(self) -> None:
"""Close the OS mapping so the sidecar can be replaced.
The ndarray owns the buffer. Closing the mmap while that export is
still alive leaves the Windows file lock until a later collection.
Drop the array first, then close the handle.
"""
array = self._array
self._array = None
if array is None:
return
array.flush()
handle = getattr(array, "_mmap", None)
del array
if handle is not None and not getattr(handle, "closed", True):
handle.close()

Fix: force-close the handle only on Windows (os.name == "nt"). Elsewhere, use close(). Alternatively, convert BufferError into a pop_saveset error that says how to fix it. Add a test that holds a view and then resaves.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🤖 Resave no longer calls close_file() under a live view. On POSIX it uses data.close() and os.replace, so the old inode stays valid for existing slices. On Windows it unmaps only when nothing else holds the mapping; if a plot or the console still has a view, pop_saveset refuses and says to close those references or Save as a new file. A resave with no live view still replaces the .fdt. Holding view = np.asarray(eeg['data'])[0] through a same-path resave keeps the view values, and reloading the new .fdt matches the data written at save time. On Windows that live-view resave raises the refusal instead.

cursoragent and others added 3 commits November 24, 2026 04:06
Save study stores the datasets pop_savestudy returns. Quit and study resave use savemode=resave, so a raw BIDS .set is refused. POSIX resave releases the memmap handle without closing it under a live view; Windows refuses that resave instead of unmapping.

Co-authored-by: Suraj Ranganath <[email protected]>
Keep the #675 Edit and Tools changelog bullet beside the #673 file-menu bullet. Dialog buttons keep OK as the default button and still grow to the label size hint.

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

claude Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

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


Code review

  • Overall assessment: Needs changes, but only two small items. 8de429c fixes all three Important findings from the last review:
    • Save study now passes the resaved datasets to set_study.
    • Quit → Yes calls pop_saveset(..., savemode="resave") and shows a refusal with _warn.
    • The memmap release uses close() on POSIX. On Windows it refuses the save if a view is still open. Slices of np.memmap keep base pointing at _array, so the refcount check does detect an open view.
  • Highest-risk area: pop_savestudy(..., resavedatasets='on'), which now meets the raw-BIDS refusal.
  • Merge recommendation: Needs changes.

Blocking

None.

Important

  1. resavedatasets='on' rewrites unmodified datasets, so the new raw-BIDS refusal can block Save study. In src/eegprep/functions/studyfunc/pop_savestudy.py, _resave_datasets (line 419) loops over every dataset. Each call now uses savemode="resave". A study with one unmodified raw-BIDS .set and one edited dataset fails on Save study → "Yes", and nothing is saved. As I remember pop_savestudy.m, EEGLAB resaves only datasets with saved equal to 'no'. The EEGLAB source is not vendored in this checkout, so I could not cite the line. Fix: skip datasets whose saved != "no". Add a test with one clean raw-BIDS dataset and one modified dataset (see the inline comment).

Nits

  • src/eegprep/resources/help/pop_savestudy.md is still unchanged from the previous review.
    • It says the file is "EEGPrep-owned .study JSON" and that cached measures are saved in it. The function now writes MATLAB v6 or v7.3 and strips measures with std_rmalldatafields.
    • Its usage lines, STUDY, com = pop_savestudy(...), now fail to unpack the three values (study, datasets, command).
    • return_com in the pop_savestudy signature is never read.
    • Update the help text to match study_workflows.rst:87, and either honor return_com or drop it. AGENTS.md: "add or update the corresponding Markdown help resource" and "Remove imports, variables … your change made unused."

Test gaps

  • Covered by Important 1: pop_savestudy(resavedatasets='on') on a study that mixes a clean raw-BIDS dataset and a modified dataset.

EEGLAB parity notes

None beyond the differences the PR already documents (quit prompt, round(X)==-3 channel update, MFF clock latency, CLear label).

Re-checked at 814375f:

  • Quit and Save study resave paths
  • _unlocked_sidecar, _release_mapped_sidecar and the live-view refcount check
  • Cleanup of _MappedFileInUse temporaries
  • pop_savestudy callers (menu_actions, pop_studydesign, pop_importbids, docs examples)
  • Console replay of [STUDY ALLEEG]

if not path.is_absolute():
path = Path(filepath) / path.name
pop_saveset(eeg, path)
pop_saveset(eeg, path, savemode="resave")

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: _resave_datasets rewrites every dataset in the study, including unmodified ones. Now that this call uses savemode="resave", the raw-BIDS refusal applies to all of them. In a study that holds an unmodified raw-BIDS .set plus one edited dataset, Save study → "Yes" raises the refusal and saves nothing. Unchanged sidecars are also rewritten for no reason.

def _resave_datasets(study: dict[str, Any], datasets: list[dict[str, Any]], study_directory: Path) -> None:
if not datasets:
raise ValueError("resavedatasets='on' requires loaded ALLEEG datasets")
infos = study.get("datasetinfo") or []
for index, eeg in enumerate(datasets):
if isinstance(eeg.get("data"), OffloadedData):
eeg = pop_loadset(str(eeg["data"].set_path))
datasets[index] = eeg
info = infos[index] if index < len(infos) and isinstance(infos[index], dict) else {}
filename = eeg.get("filename") or info.get("filename")
if not filename:
raise ValueError(f"Dataset {index + 1} needs a filename before resavedatasets='on'")
filepath = eeg.get("filepath") or info.get("filepath") or study_directory
path = Path(str(filename))
if not path.is_absolute():
path = Path(filepath) / path.name
pop_saveset(eeg, path, savemode="resave")
eeg["filename"] = path.name
eeg["filepath"] = str(path.parent)
eeg["saved"] = "yes"

In pop_savestudy.m, as I remember it, only datasets with saved equal to 'no' are resaved. The EEGLAB source is not vendored in this checkout, so I could not check the line. The menu asks this question only when some dataset has saved == "no".

Fix: at the top of the loop, skip datasets whose saved is not "no", as in if eeg.get("saved") != "no": continue. Add a test with one clean raw-BIDS dataset and one modified derivative dataset. With resavedatasets='on', the study should save, and the raw file's mtime should not change.

Copy link
Copy Markdown
Member Author

Replies to the review on 814375f, fixed at a7cc1b2:

Dataset resaving (4675467575). Fixed. Scripts and File > Save current study > Yes now write only datasets marked saved='no'. The tests reload the edited derivative, check that the clean raw-BIDS file keeps its bytes and mtime for both yes and justloaded, and confirm that a modified raw recording still raises the refusal.

Difference from EEGLAB: pop_saveset.m skips saved='yes' datasets only when its immediate caller is inside EEGLAB (the multi-dataset loop at lines 173-185 and the single-dataset check at 188-190). A user script calling pop_saveset directly on one dataset resaves it. EEGPrep skips unmodified datasets regardless of caller; this is documented in the pop_savestudy Notes.

Packaged help. resources/help/pop_savestudy.md and the study workflow guide now describe MATLAB v6 with the v7.3 fallback, measures stripped from the disk copy by std_rmalldatafields, and the (study, datasets, command) return.

return_com. Removed from pop_savestudy and every caller (menu, study design editor, docs, example, tests). The console test now saves a real study.

Local checks: pre-commit, ruff format, ty, and 382 tests across the study, file menu, console, GUI and BIDS export modules passed; the group-analysis example ran end to end.

@suraj-ranganath
suraj-ranganath marked this pull request as draft November 24, 2026 08:38
@suraj-ranganath
suraj-ranganath marked this pull request as ready for review November 24, 2026 08:38
@suraj-ranganath
suraj-ranganath marked this pull request as draft November 24, 2026 12:55
@suraj-ranganath
suraj-ranganath marked this pull request as ready for review November 24, 2026 12:55
@claude

claude Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

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


Review skipped

I did not run a new review on d37522c. The github-pr-review skill skips automatic re-reviews, and this run started from the ready_for_review event. No one asked for a review in a comment, and an earlier Claude review is already on this PR (marked eegprep-claude-review).

  • Pre-review gate: the PR is open and not a draft, and the head is d37522c both here and on GitHub. A prior review exists and this run was not asked for, so the gate says stop.
  • Read diff since last review (not done)
  • Review passes (not done)
  • Post review (not done)

To get a review of the fixes in a7cc1b28 (only saved='no' datasets are resaved, pop_savestudy.md is updated, return_com is removed) and of the later merge, comment @claude review this.

Copy link
Copy Markdown
Member Author

@claude review this. Please cover the fixes from your last review (only saved='no' datasets are resaved, pop_savestudy.md updated, return_com removed) and the develop merge at d37522c.

@claude

claude Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Code review

  • Overall assessment: The code looks good. I reviewed a7cc1b28 and the develop merge at d37522c2.
    • Only saved='no' datasets are resaved. _resave_datasets skips every other dataset (pop_savestudy.py line 416). The menu asks only when some dataset is saved == "no", the same condition as pop_savestudy.m line 94. It passes the returned datasets to set_study only when resave is on. test_save_study_resaves_only_the_modified_derivative runs the script and menu paths with the raw dataset set to yes and to justloaded. It checks that the raw .set bytes and mtime do not change, the derivative is written, and the flags end as [raw_saved, "yes"].
    • pop_savestudy.md is updated. It shows the 3-value return, the v6/v7.3 format, the resavedatasets behavior, and the JSON and resave rules. study_workflows.rst matches.
    • return_com is removed. No caller in src/, docs/, or tests/ still passes it to pop_savestudy. Passing it now raises Unknown pop_savestudy option(s). eegprep-console adds return_com only when the function's signature names it, and **kwargs does not count (console.py _accepts_return_com). Bare console calls therefore work, and the rewritten console test saves a real file.
    • Develop merge. 38d84e5e reset the changelog, and d37522c2 restores the PR's text. The GUI audit Nov 23: File menu and data I/O fixes (BIDS resave overwrite, .study format, text export, importers, BIDS tools) #673 bullet, the (#674) tag, and the pop_importbids derivative and history bullets are back. Develop's topoplot and ICLabel changes do not touch files this PR changes, and no conflict markers are left.
  • Highest-risk area: Merge process. This PR changes EEGLAB-ported core functions, and the PR description has no MATLAB reference-suite run.
  • Merge recommendation: Needs more context. The code is ready, but merging is blocked on the reference-suite evidence below.

Blocking

None.

Important

  1. The required EEGLAB reference-suite evidence is missing from the PR description. The PR changes core ported functions: the loadcnt/pop_loadcnt event offset, the pop_chanevent expression evaluator, and the pop_saveset atomic replace. The Verification section says "The MATLAB reference suite was not run here." AGENTS.md (Testing) requires this run for such PRs: "Before merging a PR that changes core function implementations … trigger .github/workflows/eeglab-reference.yml … on the PR branch, or run the suite locally once on the final branch," and "Put that run in the PR description." Fix: run the EEGLAB reference workflow on d37522c2. Then add the run link, the EEGLAB and eeglab_tests commits, pass/fail/skip counts, runtime, and the reason for any failure or skip. While you edit the description, it still says "Head is 814375f2" and has no section for a7cc1b28 or the develop merge.

Nits

  • pop_savestudy docstring Notes (pop_savestudy.py lines 43-50): the note describes EEGLAB's skip as saved='yes' only, but does not say that EEGPrep also skips 'justloaded'. pop_saveset.m line 175 tests only strcmpi(EEG(index).saved, 'yes'), so EEGLAB still resaves a 'justloaded' dataset. Skipping it is the safer choice, and the new test covers it. Add one sentence to the note that names this difference, so the deviation is documented where the code is.

Test gaps

None.

EEGLAB parity notes

None beyond the nit above. The prompt condition matches pop_savestudy.m line 94. The pop_saveset(..., savemode="resave") call matches pop_savestudy.m line 126.

Copy link
Copy Markdown
Member Author

Both points from the last review are handled at bd045f8.

@suraj-ranganath
suraj-ranganath merged commit a33f758 into develop Nov 24, 2026
13 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.

GUI audit Nov 23: File menu and data I/O fixes (BIDS resave overwrite, .study format, text export, importers, BIDS tools)

2 participants