Skip to content

[History] Save session history from ALLCOM and write Python for .py scripts - #797

Merged
arnodelorme merged 15 commits into
developfrom
agent/20261128-fix-785
Nov 29, 2026
Merged

arnodelorme merged 15 commits into
developfrom
agent/20261128-fix-785

Conversation

@claude

@claude claude Bot commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

File > History scripts > Save session history script now saves ALLCOM, and a .py file holds Python that runs. Replaying a saved session .py file keeps its history and shows its datasets in the main window. A .m file is written exactly as before.

The main window after replaying the saved session: EEGLAB, EEGPrep before, EEGPrep now

One real session in EEGLAB (MATLAB R2025b): load sample_data/eeglab_data.set, re-reference to average, resample to 64 Hz, save the session history, run the saved file. The same six commands were then saved by EEGPrep as .py and run with Python.

After running the saved session file Datasets Current dataset Entries in ALLCOM
EEGLAB (MATLAB R2025b), .m file 3 3, Continuous EEG Data resampled, 64 Hz 0
EEGPrep before (c85b689), .py file 3, window shows none 3, Continuous EEG Data resampled, 64 Hz 0
EEGPrep now (8c83da5), .py file 3, window shows dataset 3 3, Continuous EEG Data resampled, 64 Hz 6, the commands of the session

One difference from EEGLAB, asked for by Arno ("Do not empty ALLCOM"). EEGLAB itself ends with an empty ALLCOM after it runs a saved session file: the first line [ALLEEG EEG CURRENTSET ALLCOM] = eeglab; returns an empty history, and the replayed commands do not call eegh. EEGPrep now keeps the six commands. This concerns the history list only. No dataset and no number differ.

The saved session .py file, before and now

Before (c85b689):

# EEGPrep history file generated on 2026-11-29
# ------------------------------------------------
import eegprep
from eegprep import *
ALLEEG, EEG, CURRENTSET, ALLCOM = [], {}, 0, []
EEG = pop_loadset(filename='eeglab_data.set', filepath='/Users/arno/GitHub/core_eeg/eeglab/sample_data/')
[ALLEEG, EEG, CURRENTSET] = eeg_store(ALLEEG, EEG, 0)
EEG = pop_reref(EEG, ref=[])
ALLEEG, EEG, CURRENTSET, LASTCOM = pop_newset(ALLEEG, EEG, CURRENTSET=1, gui='off')
EEG = pop_resample(EEG, freq=64)
ALLEEG, EEG, CURRENTSET, LASTCOM = pop_newset(ALLEEG, EEG, CURRENTSET=2, gui='off')
eegprep.eeglab()

Now (8c83da5):

# EEGPrep history file generated on 2026-11-29
# ------------------------------------------------
import eegprep
from eegprep import *
ALLEEG, EEG, CURRENTSET, STUDY, CURRENTSTUDY = [], {}, 0, None, 0
ALLCOM = [
    "EEG = pop_loadset('filename','eeglab_data.set','filepath','/Users/arno/GitHub/core_eeg/eeglab/sample_data/');",
    '[ALLEEG, EEG, CURRENTSET] = eeg_store( ALLEEG, EEG, 0 );',
    'EEG = pop_reref( EEG, []);',
    "[ALLEEG EEG CURRENTSET] = pop_newset(ALLEEG, EEG, 1,'gui','off'); ",
    'EEG = pop_resample( EEG, 64);',
    "[ALLEEG EEG CURRENTSET] = pop_newset(ALLEEG, EEG, 2,'gui','off'); ",
]
EEG = pop_loadset(filename='eeglab_data.set', filepath='/Users/arno/GitHub/core_eeg/eeglab/sample_data/')
[ALLEEG, EEG, CURRENTSET] = eeg_store(ALLEEG, EEG, 0)
EEG = pop_reref(EEG, ref=[])
ALLEEG, EEG, CURRENTSET, LASTCOM = pop_newset(ALLEEG, EEG, CURRENTSET=1, gui='off')
EEG = pop_resample(EEG, freq=64)
ALLEEG, EEG, CURRENTSET, LASTCOM = pop_newset(ALLEEG, EEG, CURRENTSET=2, gui='off')
LASTCOM = ALLCOM[-1]
eegprep.eeglab('redraw', workspace=globals())

The session .m file is the same before and now, and has the layout of the file EEGLAB saves:

% EEGPrep history file generated on 2026-11-29
% ------------------------------------------------
[ALLEEG EEG CURRENTSET ALLCOM] = eeglab;
EEG = pop_loadset('filename','eeglab_data.set','filepath','/Users/arno/GitHub/core_eeg/eeglab/sample_data/');
[ALLEEG, EEG, CURRENTSET] = eeg_store( ALLEEG, EEG, 0 );
EEG = pop_reref( EEG, []);
[ALLEEG EEG CURRENTSET] = pop_newset(ALLEEG, EEG, 1,'gui','off'); 
EEG = pop_resample( EEG, 64);
[ALLEEG EEG CURRENTSET] = pop_newset(ALLEEG, EEG, 2,'gui','off'); 
eeglab redraw;
What changed today, for the four findings of the review

The findings are numbered as in the review comment of November 29.

  • Finding 2, replaying a session no longer empties ALLCOM. pop_saveh writes ALLCOM = [...] with the commands as they were recorded, in place of ALLCOM = []. After the replay ALLCOM equals the saved history, in a new Python process and through File > History scripts > Run script.
  • Finding 3, the last line shows the datasets. The last line is eegprep.eeglab('redraw', workspace=globals()). It reads ALLEEG, EEG, CURRENTSET, ALLCOM, STUDY and CURRENTSTUDY from the script, as eeglab redraw reads the MATLAB workspace. The main window on screen is updated, and a new one opens only when there is none. So the script run twice, run from File > History scripts > Run script or run in the console always leaves one window, with the datasets of the script. Before, Run script on a session file left two windows open.
  • Finding 4, a comment with no semicolon before it. The converter receives MATLAB history and Python typed in the console, because ALLCOM and EEG.history hold both. The rule: a line that Python can parse is not MATLAB, so its % is left alone and x = 7 % 3 stays a modulo. Any other line is MATLAB, and its first % outside a string starts a comment. EEG = pop_reref( EEG, []) % average reference becomes EEG = pop_reref(EEG, ref=[]) # average reference. Limit: a comment that makes the whole line valid Python is not seen. x = 1 % note (one word) stays as it is, since nothing in the text tells it from a modulo. x = 1 % a note is translated.
  • Finding 5, a transpose no longer hides the comment. In a MATLAB line, a quote right after a name, a closing bracket, a dot or another transpose is a transpose and not the start of a string. x = A'; % note becomes x = A' # note. Limit: the transpose itself is not translated to NumPy, so that statement is still not Python and Run script names its line.

The rule is in the shared converter _console_python_command (adminfunc/console.py), so it also serves File > History scripts > Run script and the console.

What the first review by Gemini found on that change, and what commits b23ecba and 38ad63f fix

The review is in the comment "Code review" below. Its findings, in its own numbers:

  • 1, fixed (it existed on develop). A valid Python line with an apostrophe inside a double-quoted string was broken: EEG["setname"] = "don't" came out with a quote too many. A double-quoted string now keeps its text. A # comment is kept.
  • 2, fixed. File > History scripts > Run script on a session .py file added a second copy of the last pop_newset line to ALLCOM. Two causes in shared code: the script left LASTCOM on an earlier command, so it now sets LASTCOM = ALLCOM[-1] before the redraw, and EEGLAB records the pop_newset line with a blank at its end, so the session now keeps and compares the last command without trailing blanks. After Run script ALLCOM holds the six commands and the pop_runscript line, nothing twice.
  • 3, fixed. With a window already open, the redraw line returned without updating it, and in the console it opened a second window. It now updates the window on screen and returns it.
  • 4, fixed (it existed on develop). In a line read as MATLAB a backslash inside a string is an ordinary character, so a Windows folder such as 'C:\data\' ends at its quote and the ; and the comment after it are seen.
  • 5, fixed. A session .py file defines STUDY and CURRENTSTUDY, and the redraw reads them.
  • 6, left as a limit (it existed on develop). x = r' * s';, two transposes of which the first follows a variable named r, b, f or u, is also a valid Python prefixed string, so it is read as Python. No EEGLAB history line has this form.
  • 7, fixed. Replaying a session with no dataset leaves the empty dataset of eeg_emptyset, not {}.

One more limit of the rule: a MATLAB double-quoted string with a doubled quote inside, in a line that Python also parses, is read as Python. EEGLAB writes its history with single quotes.

What the second review by Gemini found, and what commit 8c83da5 fixes
  • Blocking, fixed. My first answer to finding 1 broke a valid Python string that ends with an escaped backslash, filepath='C:\\'. The rule is now: a line that Python parses and that has a keyword argument (filename='a.set') or a ['name'] index was typed as Python, and its strings are left as written, escapes included. Any other line that Python parses keeps the reading it has on develop, where a single-quoted string is a MATLAB string, so EEGLAB history with a Windows folder such as 'C:\data\new' keeps its backslashes. Limit: a Python line with neither, such as print('a\nb'), is still read as on develop, with the backslash kept as a character.
  • Blocking, fixed. After File > History scripts > Run script on a session with no dataset, the session held {} and not the empty dataset. The session now treats EEG = [], {} or an empty array as no dataset, wherever it comes from.
  • Important, fixed. A Python # comment was dropped, and its text could stop the conversion (x = 1 # [1:0:5]). It is now split off and written back as it is, as a MATLAB % comment is.
  • Important, fixed in 38ad63f. LASTCOM kept the blank at the end of the pop_newset line.
  • Important, left as a limit. A whole script pasted as one cell in the console and ending with the redraw line is recorded by the console as one command, as any cell that assigns EEG is on develop. Running the file with pop_runscript, with Run script or with Python is not concerned.
  • Tests. The new test now sets a study before the replay and checks that it is reset, and runs the empty session through Run script. The converter test has the # comment and the escaped backslash.
  • Nit, fixed. The documentation no longer says that a double-quoted string is copied as written, since Python rewrites its quotes.
Both ALLCOM lists

The session in EEGLAB before saving (oldest first):

[ALLEEG EEG CURRENTSET ALLCOM] = eeglab;
EEG = pop_loadset('filename','eeglab_data.set','filepath','/Users/arno/GitHub/core_eeg/eeglab/sample_data/');
[ALLEEG, EEG, CURRENTSET] = eeg_store( ALLEEG, EEG, 0 );
EEG = pop_reref( EEG, []);
[ALLEEG EEG CURRENTSET] = pop_newset(ALLEEG, EEG, 1,'gui','off'); 
EEG = pop_resample( EEG, 64);
[ALLEEG EEG CURRENTSET] = pop_newset(ALLEEG, EEG, 2,'gui','off'); 

ALLCOM in EEGLAB after running the saved file: empty (0 entries).

ALLCOM in EEGPrep after running the saved .py file (6 entries):

EEG = pop_loadset('filename','eeglab_data.set','filepath','/Users/arno/GitHub/core_eeg/eeglab/sample_data/');
[ALLEEG, EEG, CURRENTSET] = eeg_store( ALLEEG, EEG, 0 );
EEG = pop_reref( EEG, []);
[ALLEEG EEG CURRENTSET] = pop_newset(ALLEEG, EEG, 1,'gui','off'); 
EEG = pop_resample( EEG, 64);
[ALLEEG EEG CURRENTSET] = pop_newset(ALLEEG, EEG, 2,'gui','off'); 

The first line of the EEGLAB session, [ALLEEG EEG CURRENTSET ALLCOM] = eeglab;, is the one EEGPrep writes itself at the top of a .m file and replaces by the empty workspace line in a .py file.

The saved dataset history of the sample file

On develop a .py file held MATLAB text. Now:

# EEGPrep history file generated on 2026-11-29
# ------------------------------------------------
import eegprep
from eegprep import *

EEG = pop_loadset(filename='eeglab_data.set', filepath='/data/common/matlab/eeglab/sample_data/')
EEG = eeg_checkset(EEG)
EEG = pop_loadset(filename='eeglab_data.set', filepath='/Users/arno/eeglab/sample_data/')
EEG = eeg_checkset(EEG)
EEG['etc']['eeglabvers'] = 'development head'  # this tracks which version of EEGLAB is being used, you may ignore it
EEG = pop_loadset(filename='eeglab_data.set', filepath='/data/matlab/eeglab/sample_data/')
EEG = eeg_checkset(EEG)
EEG = pop_chanedit(chans=EEG, lookup='/data/matlab/eeglab/plugins/dipfit/standard_BESA/standard-10-5-cap385.elp', load=['/data/matlab/eeglab/sample_data/eeglab_chan32.locs', 'filetype', 'autodetect'])
EEG = eeg_checkset(EEG)

The dataset .m file is byte for byte the file develop writes.

Verification
  • On afb9f3c, 1,837 tests passed and 130 were skipped on the Mac (every test file that uses the converter, pop_saveh, pop_runscript, eegh or eeglab(). On the final head 8c83da5, the 1,107 tests of the GUI, console, history, dataset and study files passed and 10 were skipped. The skips need the MATLAB Engine for Python. tests/test_pop_runica_pamica.py was left out because the pamica module is not installed there. Ruff and pre-commit.py pass.
  • test_session_script_run_again_redraws_the_open_window_and_keeps_allcom is new: it runs a session .py file, runs it again alone and through Run script, and checks one window, no command twice in ALLCOM, and the empty dataset after an empty session. It fails without today's commits.
  • test_saved_session_and_dataset_history_name_their_source_and_replay now runs the whole session .py file, last line included, and checks the data, that ALLCOM equals the recorded commands and that the window shows the 3 channels of the replayed dataset.
  • test_console_python_command_tells_matlab_history_from_python_input holds the five lines of findings 4 and 5, and now the double-quoted string, the escaped quote, the escaped backslash, the # comment and the Windows folder.
  • The window in EEGLAB shows "Filename: none" and 2.3 Mb, EEGPrep shows the file name and 2.2 Mb. Both differences exist on develop and do not come from this pull request.
EEGLAB reference run (rule of pull request #860)

The limits left for later are in issue #877.

Part of #785

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor Author

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.

…ipts

The GUI joined ALLCOM into one string, so pop_saveh recorded EEG.history as
the source of session history. pop_saveh now translates commands for .py files,
and pop_loadset accepts filename/filepath keywords so translated history replays.

Part of #785
@claude

claude Bot commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor Author

PR #797 was updated after the trigger (652b580 -> fdb703a). Push again or mention Claude to run on the latest version.

@arnodelorme arnodelorme left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This review was written by an AI assistant during a nightly check, not by Arno.

Code review

  • Overall assessment: Needs changes.
  • Highest-risk area: pop_saveh session versus dataset history framing and source detection (src/eegprep/functions/popfunc/pop_saveh.py, src/eegprep/functions/guifunc/menu_actions.py).
  • Merge recommendation: Needs changes.

Blocking

  1. Blocking (src/eegprep/functions/guifunc/menu_actions.py, src/eegprep/functions/popfunc/pop_saveh.py): MATLAB .m session history files drop EEGLAB startup/redraw lines and emit Python syntax, breaking CI.

    • References:
      • history = (
        self.session.EEG.get("history", "")
        if variant == "dataset" and isinstance(self.session.EEG, dict)
        else self.session.ALLCOM
        )
        command = pop_saveh(history, path.name, path.parent)
        self._add_history_from_gui(command)
        self._refresh()
      • SESSION_REDRAW = "eegprep.eeglab();"
        PYTHON_IMPORTS = ["import eegprep", "from eegprep import *"]
        PYTHON_EMPTY_WORKSPACE = "ALLEEG, EEG, CURRENTSET, ALLCOM = [], {}, 0, []"
      • session_commands = _history_commands(allcoms)
        is_session = session_commands is not None
        commands = [*session_commands, SESSION_REDRAW] if is_session else str(allcoms).splitlines()
        is_python = path.suffix.lower() == ".py"
        comment = "#" if is_python else "%"
        lines = [
        f"{comment} EEGPrep history file generated on {date.today().isoformat()}",
        f"{comment} ------------------------------------------------",
        ]
        if is_python:
        lines += PYTHON_IMPORTS
        if is_session:
        lines.append(PYTHON_EMPTY_WORKSPACE)
        lines += [_python_line(command) for command in commands]
        else:
        lines += commands
        path.write_text("".join(f"{line}\n" for line in lines), encoding="utf-8")
      • assert session_text.index("pop_reref") < session_text.index("pop_select")
        assert "eegprep.eeglab()" in session_text
        assert "eegprep.eeglab()" not in dataset_text
        if suffix == ".m":
        return
    • Why it matters: Removing the MATLAB session wrapper in menu_actions._save_history while keeping SESSION_REDRAW = "eegprep.eeglab();" in pop_saveh causes .m session history scripts to omit [ALLEEG EEG CURRENTSET ALLCOM] = eeglab; and end with Python's eegprep.eeglab(); instead of EEGLAB's eeglab redraw; (pop_saveh.m line 77). eegprep.eeglab(); is invalid in MATLAB, and this directly breaks tests/test_stream11_datasets.py::test_f27_exported_session_history_is_matlab_script across CI.
    • Suggested fix: Separate the Python and MATLAB session wrappers inside pop_saveh. When is_session and is_python, emit PYTHON_IMPORTS, PYTHON_EMPTY_WORKSPACE, translated session_commands, and "eegprep.eeglab()". When is_session and not is_python, emit "[ALLEEG EEG CURRENTSET ALLCOM] = eeglab;", raw session_commands, and "eeglab redraw;". Update the .m assertion in tests/test_file_menu_audit_673.py, src/eegprep/resources/help/pop_saveh.md, and docs/source/user_guide/gui_console_session.rst accordingly.
  2. Blocking (src/eegprep/functions/popfunc/pop_saveh.py, src/eegprep/functions/popfunc/pop_loadset.py): Empty or character-array EEG["history"] is misclassified as ALLCOM session history.

    • References:
      • A list, MATLAB cell, or character array is session history (``ALLCOM``),
        written one command per line in order and followed by a GUI redraw. A
        string is dataset history (``EEG.history``). A ``.py`` filename translates
        each command to Python; other suffixes keep the recorded MATLAB syntax.
        """
        path = Path(filepath) / filename
        path.parent.mkdir(parents=True, exist_ok=True)
        session_commands = _history_commands(allcoms)
        is_session = session_commands is not None
        commands = [*session_commands, SESSION_REDRAW] if is_session else str(allcoms).splitlines()
      • path.write_text("".join(f"{line}\n" for line in lines), encoding="utf-8")
        target = "ALLCOM" if is_session else "EEG.history"
        return f"pop_saveh({target}, {format_history_value(path.name)}, {format_history_value(str(path.parent))});"
        def _python_line(command: str) -> str:
        text = command.strip()
        if text.startswith("%"):
        return "#" + text[1:]
        return _console_python_command(text)
        def _history_commands(allcoms: Any) -> list[str] | None:
        if is_cell(allcoms):
        return [str(item) for item in cell_items(allcoms)]
        if isinstance(allcoms, np.ndarray):
        if allcoms.size == 0:
        return []
        if allcoms.dtype.kind in "SU":
        return [str(item) for item in allcoms.reshape(-1)]
        return None
        if isinstance(allcoms, list):
        return [str(item) for item in allcoms]
        return None
      • # Text fields that eeg_emptyset.m initializes to ''.
        TEXT_FIELDS = ("setname", "subject", "group", "condition", "comments")
    • Why it matters: In EEGLAB (pop_saveh.m lines 72 and 84), only iscell(allcoms) is session history (ALLCOM), while MATLAB character arrays ('' or char matrices) are EEG.history. Because pop_loadset omits "history" from TEXT_FIELDS, loading a .set file with an empty EEG.history produces np.empty((0, 0), dtype="<U1") (and eeg_hist skips pop_loadset on load). _history_commands returns [] for allcoms.size == 0 and a list for allcoms.dtype.kind in "SU", so is_session becomes True for dataset history. Saving dataset history on such a dataset records pop_saveh(ALLCOM, ...), writes ALLEEG, EEG, CURRENTSET, ALLCOM = [], {}, 0, [] (overwriting the caller's starting EEG with {} on replay), and appends the session redraw.
    • Suggested fix: Restrict _history_commands to list and is_cell(allcoms) only, convert non-session inputs with _history_text from eegprep.functions.adminfunc.eeg_hist (so empty arrays and 2D char matrices become clean text rather than "[]"), and include "history" in pop_loadset.TEXT_FIELDS.

Important

  1. Important (src/eegprep/functions/popfunc/pop_saveh.py): _python_line leaves trailing MATLAB % comments untranslated, producing invalid Python on sample_data/eeglab_data.set.

    • References:
      • def _python_line(command: str) -> str:
        text = command.strip()
        if text.startswith("%"):
        return "#" + text[1:]
        return _console_python_command(text)
      • loaded = pop_loadset(str(SAMPLE))
        loaded["history"] = ""
        session.store_current(loaded, new=True)
        session.add_history(f"EEG = pop_loadset('filename', {SAMPLE.name!r}, 'filepath', {str(SAMPLE.parent) + '/'!r});")
        session.add_history("[ALLEEG EEG CURRENTSET] = pop_newset(ALLEEG, EEG, 0, 'gui', 'off');")
        session.add_history("EEG = pop_reref( EEG, []);")
        session.add_history("EEG = pop_select( EEG, 'channel', [1 2 3]);")
        current = session.EEG
        current["history"] = "EEG = pop_reref( EEG, []);\nEEG = pop_select( EEG, 'channel', [1 2 3]);"
    • Why it matters: _python_line only checks text.startswith("%"). When a history line has a trailing comment after a semicolon, such as EEG.etc.eeglabvers = 'development head'; % this tracks... in sample_data/eeglab_data.set, _console_python_command splits on ; and leaves ; % ... in the output. Saving dataset history of sample_data/eeglab_data.set to .py fails ast.parse with SyntaxError (masked in the new test because line 238 clears loaded["history"] = "").
    • Suggested fix: In _python_line, split any % comment outside quoted strings before calling _console_python_command on the code part, then append # ... (or return # ... alone when the translated code part is empty).
  2. Important (src/eegprep/functions/popfunc/pop_loadset.py): Pre-merge MATLAB reference suite run is still required.

    • Reference:
      • elif isinstance(file_path, str) and file_path.lower() in known_keys:
        options = parse_key_value_args((file_path, *args), kwargs, lowercase_keys=True, lowercase_kwargs=True)
        filename = options.pop("filename", None)
        else:
        # pop_loadset.m old calling format: pop_loadset(filename, filepath).
        # An even tail is name/value pairs after the filename.
        filename = file_path
        positional = list(args)
        legacy_filepath = positional.pop(0) if len(positional) % 2 == 1 else None
        options = parse_key_value_args(tuple(positional), kwargs, lowercase_keys=True, lowercase_kwargs=True)
    • Why it matters: Per AGENTS.md, PRs modifying core pop_* implementations must run .github/workflows/eeglab-reference.yml (or the local --eeglab-backend=matlab reference suite) on the final branch and record the results in the PR description before merge, as noted in the PR body.
    • Suggested fix: Run the MATLAB reference workflow once the blocking fixes above land and add the run summary to the PR body.

Nits

None.

Test gaps

  • tests/test_file_menu_audit_673.py (test_saved_session_and_dataset_history_name_their_source_and_replay):
    • Assert that .m session history contains [ALLEEG EEG CURRENTSET ALLCOM] = eeglab; and eeglab redraw; and does not contain eegprep.eeglab().
    • Add coverage for saving dataset history immediately after loading a .set file whose EEG.history is empty ('' in MATLAB), verifying pop_saveh(EEG.history, ...) is recorded and no session workspace reset or redraw is written.
    • Add coverage for saving .py history containing an inline MATLAB % comment after ; (or directly saving sample_data/eeglab_data.set's loaded EEG["history"] to .py and parsing with ast.parse).
  • tests/test_pop_loadset.py:
    • Add a direct unit test calling pop_loadset(filename=..., filepath=...) with keyword arguments only.

EEGLAB parity notes

  • In EEGLAB (pop_saveh.m lines 72 through 88), ALLCOM is distinguished strictly by iscell(allcoms) and ends .m session scripts with eeglab redraw;, whereas EEG.history is a character array written without a redraw line.

Tests run

Ran in a detached worktree at fdb703a854f18190634db497ce7c160a46a887d6:

  • pytest tests/test_file_menu_audit_673.py -k "saveh or saved_session or runscript" tests/test_pop_loadset.py tests/test_stream11_datasets.py -k "saveh or saved_session or runscript or loadset or f27": 37 passed, 1 failed (tests/test_stream11_datasets.py::test_f27_exported_session_history_is_matlab_script).
  • pytest tests/test_eegh.py tests/test_gui_main_window.py -k "saveh or history or runscript": all selected non-ICLabel tests passed (16 passed in test_eegh.py, 5 passed in test_gui_main_window.py).

arnodelorme and others added 2 commits November 28, 2026 11:55
…-785

# Conflicts:
#	docs/source/changelog.rst
…ataset history

A session .m script starts with the eeglab call and ends with eeglab redraw;
only a session .py script ends with eegprep.eeglab(). Only a list or a cell
is session history (iscell in pop_saveh.m), so an empty or character-array
EEG.history is saved as dataset history.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@arnodelorme

Copy link
Copy Markdown
Collaborator

This comment was written by an AI assistant (Claude Fable) at Arno's request, not by Arno.

Summary. The two blocking bugs of the review above are fixed in commit dd8e3b5, and develop is merged into the branch (the only conflict was the changelog, both entries are kept). I reviewed the whole pull request again and did not merge it: one finding of the first review is still true, and the MATLAB reference run is not finished.

What changed

  1. A .m session file now holds MATLAB only. It starts with [ALLEEG EEG CURRENTSET ALLCOM] = eeglab; and ends with eeglab redraw;, as on develop. Only a session .py file ends with eegprep.eeglab().
  2. An empty history is no longer a session. Only a Python list or a MATLAB cell is session history, which is the iscell(allcoms) test of pop_saveh.m. An empty or character-array EEG.history is saved as dataset history, with no workspace reset and no redraw line, and the recorded command is pop_saveh(EEG.history, ...).

The change is 15 lines added and 11 removed in pop_saveh.py, plus the wording of the help page and of the user guide. pop_loadset.py was not touched again.

What remains before a merge

  1. A dataset .py history does not always parse. A history line with a MATLAB comment after the semicolon keeps its % ... text. Saving the dataset history of sample_data/eeglab_data.set to a .py file gives EEG.etc.eeglabvers = 'development head'; % this tracks ..., which is a Python syntax error. EEGLAB writes that line into most datasets, so this will be common. This is "Important 1" of the first review. I left it alone because my order was to fix the two blocking bugs only. The fix is small (split the comment in _python_line).
  2. The MATLAB reference run. pop_loadset and pop_saveh are core functions, so AGENTS.md asks for one EEGLAB reference run and a human approval before the merge. I started it on this branch: https://github.com/sccn/eegprep/actions/runs/46183971548
  3. The test workflow was restarted by the push and takes about one hour.
Tests run on the Mac, and details of the second review

Run in a separate worktree at dd8e3b5, Python 3.11:

  • pytest tests/test_file_menu_audit_673.py tests/test_stream11_datasets.py -k "saveh or saved_session or f27": 9 passed. This includes test_f27_exported_session_history_is_matlab_script, the test that failed in CI.
  • pytest tests/test_file_menu_audit_673.py tests/test_pop_loadset.py tests/test_stream11_datasets.py tests/test_sample_data_pop_functions.py tests/test_eegh.py tests/test_console_workspace.py -k "not iclabel": 259 passed, 2 failed. The two failures need defusedxml and onnxruntime, which are not installed in that environment, and do not touch this change.
  • pytest tests/test_gui_main_window.py -k "saveh or history or runscript": 7 passed.
  • ruff check and ruff format --check on the two changed Python files: clean.

Tests changed, only to prove the two fixes:

  • test_saved_session_and_dataset_history_name_their_source_and_replay now checks that the .m session file starts with the eeglab line, ends with eeglab redraw; and has no eegprep.eeglab, and that the .py session file ends with eegprep.eeglab().
  • New test_pop_saveh_empty_loaded_history_is_dataset_history: a dataset saved with an empty history and loaded again gives an empty character array. Saving it records pop_saveh(EEG.history, ...) and writes no session line, for .m and for .py.

Second review, other points checked:

  • pop_loadset(filename=..., filepath=...) and pop_loadset('filename', ..., 'filepath', ...) both load the sample file, and pop_loadset() still raises "file_path argument is required".
  • A character array of several commands is written one command per line as dataset history.
  • An empty MATLAB cell is still a session, as in EEGLAB.
  • The documentation example plot_history_to_script.py prints the saved .m file and asserts nothing about it. Its output now shows the two EEGLAB lines.
  • Not changed by this pull request and left as it is: EEGLAB reads ALLCOM backwards when it writes the file, because it keeps the newest command first. EEGPrep keeps the oldest command first and writes it in order.

— orchestrator

@arnodelorme

Copy link
Copy Markdown
Collaborator

Review (Claude Fable): needs more work

  • One defect remains, and it is common. The dataset history of sample_data/eeglab_data.set saved as .py is not valid Python. The line EEG.etc.eeglabvers = 'development head'; % this tracks ... keeps its MATLAB comment. EEGLAB writes that line into most datasets, and issue pop_saveh (File > History scripts > Save dataset or session history script): graphical and numerical parity with EEGLAB #785 asks that the .py files parse.
  • The cause is in shared code. _console_python_command (adminfunc/console.py) does not handle a % comment after the semicolon. The same line also stops File > History scripts > Run script on a .m file, on develop too. Fix it once in the converter, not in pop_saveh.
  • The pull request body is out of date. It still says the MATLAB reference run is needed. The run is finished and its result must be in the body (AGENTS.md), with two short "before and after" file listings so the change can be accepted from the pull request alone.
  • The rest is sound. Session and dataset are told apart as in pop_saveh.m (iscell), the .m files hold MATLAB only, the change is small, and the only merge conflict is the changelog.
Details

What I ran (head dd8e3b51, Mac, Python 3.11, worktree sources)

  • pytest tests/test_file_menu_audit_673.py tests/test_pop_loadset.py tests/test_stream11_datasets.py: 118 passed, 1 failed. The failure is test_real_testmff_matches_eeglab_epochs, which needs an MNE soft dependency missing on this machine. It passes in CI and does not touch this change.
  • pop_saveh(EEG.history, 'dataset.py') on the sample dataset, then ast.parse: SyntaxError on line 10 (the eeglabvers line above). The new test does not see it because it sets loaded["history"] = "" first.
  • pop_loadset(filename=..., filepath=...) and pop_loadset('filename', ..., 'filepath', ...) both load the sample file. pop_loadset() still raises "file_path argument is required".
  • Session .py file replayed in an empty namespace: 2 datasets, 3 channels, as expected.

What is needed

  1. In _console_python_command, split a % comment that sits outside quotes before translating, and write it back as # .... Add one test that saves the loaded history of the sample dataset to .py and parses it, without clearing the history. This also repairs Run script on .m dataset histories.
  2. Update the pull request body: the reference run https://github.com/sccn/eegprep/actions/runs/46183971548 with the EEGLAB and eeglab_tests commits, the counts, and the reason for the failures. Add the content of the four saved files before and after (session and dataset, .m and .py), visible without a click. No capture or histogram is needed, since no window and no numerical output change.
  3. Merge develop again (conflict in docs/source/changelog.rst only).

CI and reference run

Parity with pop_saveh.m

  • Lines 72 to 88: a cell is session history and ends with eeglab redraw;, anything else is EEG.history. The Python code now follows this. The recorded command names ALLCOM or EEG.history accordingly.
  • EEGLAB writes ALLCOM backwards because it stores the newest command first. EEGPrep stores the oldest first and writes in order. The result is the same.

Not blocking, for a later issue

  • A session .py file ends with eegprep.eeglab(). That call opens a new, empty main window, not the datasets the script just built, so it is not the equivalent of eeglab redraw. The line was already written on develop, but the test removes it before running the script, and the help page now says it "reopens the GUI after running the history script". The right Python equivalent is a design choice for Arno.
  • Once it parses, EEG.etc.eeglabvers = '...' still fails at run time, because EEG is a dict. This is a converter gap, outside this pull request.
  • A session .m file saved by EEGPrep cannot be run by EEGPrep's own Run script (eeglab redraw; is refused). Same on develop.
  • Nits: _save_history_from_menu imports patch inside the function (AGENTS.md asks for imports at the top). SESSION_REDRAW carries a ; that only the converter removes.

Other open pull requests

No code conflict with #857, #848, #841, #836, #835, #850 or #858, which touch the same files. Each shows only the changelog conflict that comes from develop.

— orchestrator review

@arnodelorme

Copy link
Copy Markdown
Collaborator

Code review

Independent review by OpenAI Codex (model gpt-6.1-terra, high reasoning effort, read-only sandbox), asked for by Arno, on commit 67436b1. Its verdict was "needs changes". The one blocking finding is fixed in c85b689. Four important findings are left open on purpose and explained below.

What this push changed. Develop is merged into the branch (the changelog keeps both entries). It is a merge and not a rebase, because a rebase of a pushed branch needs a forced push and the pull request is squash merged anyway. The shared converter _console_python_command in console.py now turns a MATLAB comment that follows a command into a Python comment, so EEG.etc.eeglabvers = 'development head'; % this tracks ... is saved in a .py history as EEG['etc']['eeglabvers'] = 'development head' # this tracks .... A .m history keeps the line as EEGLAB wrote it.

Findings of Codex and what was done

  1. Blocking, fixed. The saved line compiled but did not run, because EEG is a dictionary in EEGPrep and EEG.etc raised AttributeError. The converter now writes EEG.a.b as EEG['a']['b'] (method calls such as EEG.get(...) are left alone), and the test runs the saved line.
  2. Important, left open: session replay empties ALLCOM. A session .py script starts with ALLCOM = [] and the replayed commands do not fill it again. This is the design of the earlier commits of this pull request, not of this fix, and it needs a decision on what a replayed session history should hold.
  3. Important, left open: the last line eegprep.eeglab() opens a new empty session, so the window does not show the datasets the script loaded. Same reason as point 2. I read the signature (session=None by default) and did not run it.
  4. Important, left open on purpose: a comment with no semicolon before it (x = 1 % note) is not translated. % is also Python's modulo, and the converter receives Python commands too, so only a % at the start of a line or right after a ; is taken as a comment. EEGLAB writes its history commands with a semicolon.
  5. Important, left open: a MATLAB transpose (x = A'; % note) hides the comment, because the existing splitter reads every quote as the start of a string. This limit was there before, and history commands of pop_ functions do not use transposes.
  6. Nit, fixed. The patch import of the test file is now at the top.
  7. Test gaps, partly done. The test now runs the saved line. I did not add the longer list of cases Codex asked for (AGENTS.md asks for minimal tests). I checked them by hand instead, see below.

Codex also noted that a session .m file now starts with the eeglab line and ends with eeglab redraw;. That comes from commit dd8e3b5, where it was done on purpose.

Tests and checks
  • pytest tests/test_file_menu_audit_673.py tests/test_console_workspace.py tests/test_pop_loadset.py tests/test_stream11_datasets.py tests/test_eegh.py tests/test_gui_pop_subcomp.py tests/test_dipfit_workflows.py tests/test_package_help.py tests/test_gui_main_window.py -k "not iclabel": 315 selected, all pass on c85b689 (Mac, Python from uv sync).
  • The two new tests fail when the fix is taken out.
  • ruff check, ruff format --check and ./pre-commit.py: clean.
  • Converter by hand: '50%; % done' inside a string is kept, x = 7 % 3 is kept, a; b; % note gives a; b # note, % note gives # note, figure; % note gives # note, EEG.get('etc') and EEG.update(a=1) are unchanged, n = EEG.nbchan; gives n = EEG['nbchan'].
  • Not translated, as before: EEG.data(1,:) = 0 and other MATLAB indexing of fields.
EEGLAB reference run (rule of pull request #860)

The commits 5547eee and c85b689 carry a Co-Authored-By line, which AGENTS.md forbids. I saw the rule after the push and cannot remove the line without a forced push. The squash merge drops it, as long as the line is not kept in the squash message.

— orchestrator

# Conflicts:
#	docs/source/changelog.rst
A session .py script sets ALLCOM to the recorded commands and ends with
eegprep.eeglab('redraw', workspace=globals()). The history converter reads
a line Python cannot parse as MATLAB: % starts a comment and a quote after
a name, a closing bracket, a dot or a transpose is a transpose.
A session .py script updates the main window on screen and opens a new one
only when there is none, sets LASTCOM to its last command so File > Run
script adds no duplicate to ALLCOM, and defines STUDY and CURRENTSTUDY.
The history converter copies double-quoted strings as written, reads a
backslash in a MATLAB string as an ordinary character and leaves Python
comments alone.
EEGLAB records the pop_newset line with a blank at its end. The session
compared it with the stripped LASTCOM in several places, so a replayed
session could add that command to ALLCOM a second time.
A line with a keyword argument or a ['name'] index was typed as Python:
its strings are left as written, escapes included. A # comment is split
off and kept, as a MATLAB % comment is. An empty EEG ({} or []) given to
the session, by the redraw line or by Run script, leaves eeg_emptyset().
# Conflicts:
#	docs/source/changelog.rst
A # comment on the header of an if or for block is no longer split off,
which left a header Python cannot parse alone. An empty NumPy array of any
shape counts as no dataset.
@arnodelorme

arnodelorme commented Nov 29, 2026 •

Copy link
Copy Markdown
Collaborator

🤖 ## Code review

Independent review by Google Gemini (model Gemini 4 Carbon, medium effort, through agy, with no right to write), in four passes on today's change. Its last verdict, on the final head 52a5ecc, is "good to merge", with nothing blocking and nothing else found. The first pass, on commit afb9f3c, said "needs changes" with three blocking findings. The second, on commit b23ecba, said "needs changes" with two blocking findings, one of them caused by my first answer. All five are fixed. What is left concerns Python typed by hand in the console, not the history that EEGLAB or the pop_ functions write, and is listed in the new issue History converter: Python console lines with escapes or triple quotes, left from #797.

First pass, on afb9f3c (the fix of findings 2 to 5 of the earlier review)

  1. Blocking, fixed. It existed on develop. A valid Python line with an apostrophe in a double-quoted string, EEG["setname"] = "don't", came out as broken Python. A double-quoted string now keeps its text.
  2. Blocking, fixed. File > History scripts > Run script on a session .py file added the last pop_newset line to ALLCOM a second time. The script now sets LASTCOM = ALLCOM[-1] before the redraw line, and the session keeps LASTCOM without the blank that EEGLAB records at the end of that line.
  3. Blocking, fixed. With a main window already open, the redraw line did not update it, and in the console it opened a second window. It now updates the window on screen and returns it. A new window opens only when there is none.
  4. Important, fixed. It existed on develop. A Windows folder that ends in a backslash, 'C:\data\', hid the semicolon and the comment after it. In a line read as MATLAB a backslash is now an ordinary character.
  5. Important, fixed. A session .py file did not define STUDY and CURRENTSTUDY. It does now, and the redraw reads them.
  6. Important, left as a limit. It existed on develop. x = r' * s';, two transposes of which the first follows a variable named r, b, f or u, is also a valid Python prefixed string and is read as Python. No EEGLAB history line has this form.
  7. Important, fixed. Replaying a session with no dataset left {} in place of the empty dataset of eeg_emptyset.
  8. Nit, moot. The redraw now returns the window, so the docstring is right.
  9. Test gaps, filled. test_session_script_run_again_redraws_the_open_window_and_keeps_allcom is new, and the converter test has the new lines.

Second pass, on b23ecba

  1. Blocking, fixed. My first answer to finding 1 broke a valid Python string that ends with an escaped backslash, filepath='C:\\'. The rule is now: a line that Python parses and that has a keyword argument or a ['name'] index was typed as Python, and its strings are left as written. Any other line that Python parses keeps the reading of develop, where a single-quoted string is a MATLAB string. Limit: print('a\nb'), a Python line with neither, is still read as on develop.
  2. Blocking, fixed. After Run script on a session with no dataset, the session held {}. The session now treats EEG = [], {} or an empty array as no dataset, wherever it comes from.
  3. Important, fixed. A Python # comment was dropped, and its text could stop the conversion. It is now split off and written back as it is.
  4. Important, fixed. LASTCOM kept the blank at the end of the pop_newset line (commit 38ad63f).
  5. Important, left as a limit. A whole script pasted as one cell in the console and ending with the redraw line is recorded by the console as one command, as any cell that assigns EEG is on develop. Running the file with pop_runscript, with Run script or with Python gives one window and no command twice, which I checked by hand in each of the three ways.
  6. Important, tests filled. The new test sets a study before the replay and checks it is reset, and runs the empty session through Run script. The converter test has the # comment and the escaped backslash.
  7. Nit, fixed. The documentation no longer says a double-quoted string is copied as written.

Third pass, on 8c83da5: "good to merge", nothing blocking

  1. Important, fixed in 52a5ecc. My handling of # comments broke a Python cell of several lines with a comment on its first line, if EEG['nbchan'] % 2 == 0: # even, which worked on develop. A cell of several lines is now kept in one piece, and the converter test has this cell.
  2. Important, left for issue History converter: Python console lines with escapes or triple quotes, left from #797 #877. As on develop. An escaped quote in a Python line with no keyword argument and no ['name'] index, EEG.update({'setname': 'don\'t'}), comes out as broken Python.
  3. Important, left for issue History converter: Python console lines with escapes or triple quotes, left from #797 #877. As on develop. A triple-quoted string that holds a quote followed by ;, # or a bracket.
  4. Nit, fixed in 52a5ecc. An empty NumPy array of any shape now counts as no dataset.
  5. Nit, left for issue History converter: Python console lines with escapes or triple quotes, left from #797 #877. LASTCOM after eegh(-1) keeps the blank at the end of a pop_newset line.
  6. Nit, fixed. The comment of the converter test said what it no longer tests.

Fourth pass, on the final head 52a5ecc (the last commit only): "good to merge", no finding

Gemini ran its own inputs of the third pass again. The cell of several lines with a comment on its first line gives the same result as on develop, a comment on one line and a # inside a string are kept, and an empty NumPy array of any shape, {}, [] and None all count as no dataset. It found nothing blocking, nothing important and no nit.

Checks run today

— orchestrator

@arnodelorme
arnodelorme merged commit 967a429 into develop Nov 29, 2026
20 checks passed
@arnodelorme

Copy link
Copy Markdown
Collaborator

🤖 I merged this pull request into develop, at Arno's request.

Why. Arno answered the review of November 29 with "Yes, fix", "2. Do not empty ALLCOM", "3. Fix", "4. Fix" and "5. Fix", under his standing instruction to merge once the fixes are in and another AI has checked them.

Why it was good to merge.

  • The four findings are fixed in the shared converter and in pop_saveh, and shown in the description: both ALLCOM lists, the capture of the window after the replay, the saved files before and now.
  • A .m history file is written exactly as before, and no number moves.
  • Gemini 4 Carbon (medium effort, through agy) reviewed today's change in four passes. Its last verdict, on the final head, is "good to merge" with nothing found, and its five blocking findings of the first two passes are fixed: its review.
  • The EEGLAB reference run on the final head 52a5ecc passed in all seven jobs: 5,089 tests passed, 0 failed, 58 skipped (run 46287490073).
  • Every check of the final head passed.

One difference from EEGLAB, which Arno asked for. After running a saved session file, EEGLAB ends with an empty ALLCOM (MATLAB R2025b, on a real session). EEGPrep now keeps the commands of the session. This concerns the history list only.

What stays open. The limits of the converter for Python typed by hand in the console are in History converter: Python console lines with escapes or triple quotes, left from #797. The issue of this function, pop_saveh (File > History scripts > Save dataset or session history script): graphical and numerical parity with EEGLAB, stays open by its own rule until Arno finds the window and the saved files close enough, and has a note on what this pull request did.

— orchestrator

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.

1 participant