Skip to content

Phase 5: Large-dataset storage and storedisk semantics #162

Closed

Description

@suraj-ranganath

🤖 Phase 5 designs and implements Python-native large-dataset storage semantics instead of porting MATLAB memory classes directly.

Summary

EEGLAB's @memmapdata, @mmo, and storedisk behavior are not stale for large EEG datasets, but a one-for-one MATLAB class port would be poor Python. This phase builds an explicit EEGPrep storage backend that preserves EEGLAB user semantics from GUI, pop_newset, ALLEEG, STUDY, and eegprep-console.

Scope

  • Define and implement Python-native lazy/on-disk dataset storage for large EEG arrays where useful.
  • Make pop_newset, eeg_store, eeg_retrieve, EEGPrepSession, STUDY workflows, and save/load paths honest about memory residency.
  • Support sample and synthetic large-data tests without committing large files.
  • Preserve EEGLAB-facing storedisk semantics where they matter: saved flags, dataset retrieval, overwrite/new dataset, STUDY caches, and history.
  • Do not port MATLAB @memmapdata / @mmo methods one-for-one unless a direct behavior is required.

Acceptance Criteria

  • Users can work with large continuous/epoched datasets without surprising full-memory copies where the backend promises lazy storage.
  • GUI and console always see the same dataset state.
  • Save/load/retrieve/delete operations are deterministic and tested.
  • Unsupported storage modes fail clearly instead of pretending data is unloaded.
  • Performance tests or benchmarks demonstrate no obvious UI lockups for representative large arrays.

Required References

  • AGENTS.md
  • src/eegprep/eeglab/functions/@memmapdata/
  • src/eegprep/eeglab/functions/@mmo/
  • src/eegprep/functions/adminfunc/eeg_store.py
  • src/eegprep/functions/adminfunc/eeg_retrieve.py
  • src/eegprep/functions/guifunc/session.py
  • src/eegprep/functions/popfunc/pop_newset.py
  • .agents/skills/eegprep-feature-development/SKILL.md

/goal

/goal Implement EEGPrep's Python-native large-dataset storage and storedisk semantics for the final parity epic. Use EEGLAB memory classes as user-semantics references, not as one-for-one design, and build a maintainable backend that keeps EEG/ALLEEG/CURRENTSET/STUDY/eegprep-console synchronized. Verify with synthetic large-data integration tests, pop_newset/eeg_store/eeg_retrieve/save-load tests, GUI/console mixed workflows, performance smoke tests, ruff/format/ty, non-slow pytest, and pre-commit. Do not fake unloaded data or introduce hidden global state.

Activity

  1. added
    phase
    on Jun 7, 2026
  2. claude commented on Jun 7, 2026

    @claude
    Contributor

    🤖 Plan:

    • Read issue and confirm scope
    • Duplicate-work preflight (no overlapping PRs/issues)
    • Survey current storage surface
    • Post Research + Proposed Approach

    This is a phase-epic spanning storage, session, save/load, STUDY, and GUI/console — far above the 100-line cap. Posting design for human review instead of a PR.

    Research

    The option_storedisk / option_memmapdata flags are declared in eeg_options.py but no runtime path honors them: eeg_store always deepcopys the full dict, eeg_retrieve returns a deep copy, pop_saveset writes one MAT file with data inline, and pop_loadset materializes the full array into EEG["data"]. The vendored src/eegprep/eeglab/ tree is empty in CI, so any design must specify EEGPrep-native semantics rather than importing MATLAB class behavior at runtime. The saved field is already wired through (justloaded/yes/no) and EEGPrepSession already centralizes ALLEEG/CURRENTSET/history mutations, so a backend swap can land without touching pop_* call sites if EEG["data"] keeps a numpy-array-like interface.

    Relevant code

    • src/eegprep/functions/adminfunc/eeg_options.py#L15-L23 — option_storedisk/option_memmapdata flags, currently unread
    • src/eegprep/functions/adminfunc/eeg_store.py#L40-L48 — unconditional deepcopy, ignores option_storedisk
    • src/eegprep/functions/adminfunc/eeg_retrieve.py#L17-L21 — unconditional deepcopy on retrieve
    • src/eegprep/functions/popfunc/pop_saveset.py#L332-L378 — single .set MAT path, no .fdt sidecar branch
    • src/eegprep/functions/guifunc/session.py#L153-L303 — store_current / mark_current_saved / notify_changed choke point
    • src/eegprep/functions/sigprocfunc/epoch.py#L58-L59 — explicit TODO acknowledging option_memmapdata is unimplemented

    Proposed Design

    Goals (in priority order)

    1. Datasets with option_storedisk=1 keep at most one EEG fully in memory; the rest live on disk and round-trip through eeg_retrieve / eeg_store without losing saved/history/STUDY state.
    2. Datasets with option_memmapdata=1 expose EEG["data"] as a numpy-compatible lazy array that pop_* functions can read like ndarray without code changes for the read-only path.
    3. GUI menu actions and eegprep-console commands see identical residency state; the GUI never shows a dataset that the console thinks is unloaded.
    4. Save/load of .set files matches EEGLAB on disk: when option_savetwofiles=1 (already declared, unimplemented) the float data goes to a .fdt sidecar and the .set MAT carries datfile instead of data.
    5. No new dependency. numpy.memmap covers the contiguous (nbchan, pnts[, trials]) case; h5py is already a dependency and covers the streaming/random-access case if needed for STUDY caches.

    Non-Goals

    • One-for-one port of @memmapdata / @mmo MATLAB classes. Their public surface is method-dispatch wrapping memmapfile; the Python equivalent is numpy.memmap directly, and exposing it through a thin wrapper class is the only fidelity that matters.
    • Lazy ICA activations (icaact) — out of scope; they are derived caches, not primary data.
    • Multi-process write coordination. Single-process EEGPrep only.

    Architecture

    Introduce src/eegprep/functions/adminfunc/storage.py with three concrete data-handle types and a single resolver:

    • InMemoryData — wraps an np.ndarray; the current default; identity semantics unchanged.
    • MemmapData — wraps numpy.memmap over an EEGLAB-shaped .fdt (column-major float32 (nbchan, pnts*trials)). Implements __array__, __array_interface__, shape, dtype, slicing, and __getitem__ so existing numpy consumers (data[:, :100], np.mean(data, axis=1), etc.) work unmodified.
    • OffloadedData — placeholder that holds the .set/.fdt path of an evicted dataset; EEG["data"] returns this when option_storedisk=1 evicts a non-current set. Materializing requires going through eeg_retrieve, which lazily rehydrates from disk and updates the saved flag (yes stays yes; no is impossible because eviction requires saved state).

    EEG["data"] keeps duck-typing as a numpy array for read paths via np.asarray(EEG["data"]). Pop_* functions that mutate data already assign a new array (EEG["data"] = ...), which transparently swaps the handle back to InMemoryData.

    Session and ALLEEG semantics

    eeg_store learns one new branch: when option_storedisk=1 and the dataset being stored is not the current selection, and the existing ALLEEG entry has saved == "yes" and a known on-disk path, replace its data with an OffloadedData handle and drop the in-memory array. eeg_retrieve mirrors this: if the retrieved dataset has OffloadedData, call pop_loadset to rehydrate, then re-store using normal in-memory rules. EEGPrepSession.store_current is the single mutation point and already calls notify_changed, so GUI/console refresh comes for free.

    Eviction is refused (not silently retained) when saved != "yes": an explicit RuntimeError("Cannot evict unsaved dataset N; save it first."). This is the EEGLAB-equivalent of the "save before switching" prompt; the GUI dialog can catch it and reuse the existing pop_saveset flow.

    Save / load

    pop_saveset grows a two_files: bool branch keyed off option_savetwofiles. When true, write the float data to <base>.fdt as column-major float32 and emit datfile=<base>.fdt in the MAT instead of data. pop_loadset grows a symmetric branch: when the loaded MAT has datfile and no data, mmap the sidecar with numpy.memmap(dtype="<f4", shape=(nbchan, pnts*trials), order="F") and wrap in MemmapData. Existing single-file .set files keep working unchanged.

    pop_loadset_h5.py is left alone — it is for HDF5-saved sessions, not the EEGLAB .fdt format.

    STUDY caches

    STUDY does not need a separate storage layer for Phase 5. STUDY entries reference datasets by filename/filepath; with option_storedisk=1 the cache is implicit because only the current dataset is materialized. STUDY-level precomputed measures (spectra, ERSP) keep using whatever per-dataset cache already exists; flag explicitly in Phase 4/6 if a separate STUDY-cache eviction policy is needed.

    Tests

    • tests/test_storage.py (new): synthetic 64 ch x 60s float32 array; round-trip pop_saveset(two_files=True) -> pop_loadset -> assert MemmapData and np.allclose against original.
    • tests/test_eeg_store_storedisk.py (new): with option_storedisk=1, store two sets, switch current, assert non-current data is OffloadedData, assert eeg_retrieve rehydrates correctly, assert eviction without saved=="yes" raises.
    • tests/test_console_workspace.py (extend): after a GUI-level dataset switch under option_storedisk=1, console ALLEEG[1]["data"] is still numpy-array-readable (lazy) and EEG is the current set.
    • tests/test_pop_saveset.py (extend): assert option_savetwofiles=0 keeps the legacy single-file layout (no behavioral regression).
    • Performance smoke (skipped under slow marker): allocate a 256 ch x 600s synthetic float32, save, reload as memmap, assert resident memory grows by <50% of the dataset size during pop_loadset (RSS check via psutil if available, else tracemalloc).

    No MATLAB parity gate is required since @memmapdata/@mmo are not user-visible field types in the .set file — only data vs datfile is.

    Open Questions

    1. Should EEG["data"] always expose the handle, or should pop_* writers see a raw ndarray (forcing a .materialize() call before the first read)? Recommended: duck-typed handle. Lowest-friction path for the dozens of existing np.asarray(EEG["data"]) / direct-slice sites.
    2. For epoched data, EEGLAB writes .fdt as 2-D (nbchan, pnts*trials) column-major and reshapes on load. Confirm we want to preserve that on-disk layout (yes, recommended — round-trips with MATLAB EEGLAB) or switch to 3-D (nbchan, pnts, trials) C-order on disk (cleaner Python; breaks parity).
    3. Eviction policy: strict LRU vs strict single-resident (only the current set)? EEGLAB is single-resident under option_storedisk=1; recommend matching that and deferring LRU.
    4. Failure mode when a .fdt sidecar is missing on load: hard error vs synthesize zeros vs prompt. Recommend hard error to match EEGLAB.
    5. Does Phase 5 need to touch pop_delset to remove the .fdt alongside the .set? (Probably yes — short hook.)

    Rough Size Estimate

    • storage.py (new): ~180 lines (3 handle classes + resolver + numpy protocol glue).
    • eeg_store.py / eeg_retrieve.py: ~30 lines added each for the offload/rehydrate branches.
    • pop_saveset.py / pop_loadset.py: ~60 lines added each for the .fdt sidecar branches.
    • EEGPrepSession: ~20 lines for the option_storedisk-aware path through store_current.
    • Tests: ~250 lines.

    Total ~800 lines net new — confirming the "no PR, design comment first" call.

    Requesting human review on the five open questions before any branch is cut.

  3. suraj-ranganath commented on Jun 7, 2026

    @suraj-ranganath
    MemberAuthor

    🤖 Phase PR for this issue has merged into feature/eeglab-full-standalone-completion and integration checks are passing on the epic branch. Closing this phase issue as completed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    phase

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions