-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
FIX: add recover_epochs fallback for EGI .mff epoch metadata mismatch #13992
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
kveni12
wants to merge
4
commits into
mne-tools:main
Choose a base branch
from
kveni12:fix/egi-mff-recover-epochs-13951
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+86
−7
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
478a1c4
FIX: add recover_epochs fallback for EGI .mff epoch metadata mismatch…
kveni12 e87d2a6
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 94e36a9
STY/DOC: fix line length, add changelog entry and author name
kveni12 b91080e
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| Add ``recover_epochs`` parameter to :func:`~mne.io.read_raw_egi` to gracefully recover epoch structure from binary signal data when ``epochs.xml`` metadata is inconsistent (e.g., improperly closed or interrupted EGI recordings), by :newcontrib:`Krishnaveni Parvataneni`. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
|
|
@@ -35,7 +35,7 @@ | |||||
| REFERENCE_NAMES = ("VREF", "Vertex Reference") | ||||||
|
|
||||||
|
|
||||||
| def _read_mff_header(filepath): | ||||||
| def _read_mff_header(filepath, recover_epochs=False): | ||||||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
| """Read mff header.""" | ||||||
| _soft_import("mffpy", "reading EGI MFF data") | ||||||
| from mffpy.xml_files import XML | ||||||
|
|
@@ -96,10 +96,29 @@ def _read_mff_header(filepath): | |||||
| or not (epochs["first_samps"][1:] >= epochs["last_samps"][:-1]).all() | ||||||
| ) | ||||||
| if bad: | ||||||
| raise RuntimeError( | ||||||
| "EGI epoch first/last samps could not be parsed:\n" | ||||||
| f"{list(epochs['first_samps'])}\n{list(epochs['last_samps'])}" | ||||||
| if not recover_epochs: | ||||||
| raise RuntimeError( | ||||||
| "EGI epoch first/last samps could not be parsed:\n" | ||||||
| f"{list(epochs['first_samps'])}\n{list(epochs['last_samps'])}" | ||||||
| ) | ||||||
| warn( | ||||||
| "EGI epoch metadata mismatch; recovering epoch structure from binary data", | ||||||
| RuntimeWarning, | ||||||
| stacklevel=2, | ||||||
| ) | ||||||
| # Rebuild epoch boundaries from the actual binary block sizes | ||||||
| block_sizes = signal_blocks["samples_block"] | ||||||
| total_samps = int(block_sizes.sum()) | ||||||
| n_epochs = len(epochs["first_samps"]) | ||||||
| samps_per_epoch = total_samps // n_epochs | ||||||
| epochs["first_samps"] = np.array( | ||||||
| [i * samps_per_epoch for i in range(n_epochs)], dtype=np.int64 | ||||||
| ) | ||||||
| epochs["last_samps"] = np.array( | ||||||
| [min((i + 1) * samps_per_epoch, total_samps) for i in range(n_epochs)], | ||||||
| dtype=np.int64, | ||||||
| ) | ||||||
| n_samps_epochs = (epochs["last_samps"] - epochs["first_samps"]).sum() | ||||||
| summaryinfo.update(epochs) | ||||||
|
|
||||||
| disk_samps = np.full(epochs["last_samps"][-1], -1) | ||||||
|
|
@@ -193,21 +212,23 @@ def _read_mff_header(filepath): | |||||
| return summaryinfo | ||||||
|
|
||||||
|
|
||||||
| def _read_header(input_fname): | ||||||
| def _read_header(input_fname, recover_epochs=False): | ||||||
| """Obtain the headers from the file package mff. | ||||||
|
|
||||||
| Parameters | ||||||
| ---------- | ||||||
| input_fname : path-like | ||||||
| Path for the file | ||||||
| recover_epochs : bool | ||||||
| If True, recover epoch structure from binary data when metadata is inconsistent. | ||||||
|
|
||||||
| Returns | ||||||
| ------- | ||||||
| info : dict | ||||||
| Main headers set. | ||||||
| """ | ||||||
| input_fname = str(input_fname) # cast to str any Paths | ||||||
| mff_hdr = _read_mff_header(input_fname) | ||||||
| mff_hdr = _read_mff_header(input_fname, recover_epochs=recover_epochs) | ||||||
| with open(input_fname + "/signal1.bin", "rb") as fid: | ||||||
| version = np.fromfile(fid, np.int32, 1)[0] | ||||||
| """ | ||||||
|
|
@@ -346,6 +367,7 @@ def _read_raw_egi_mff( | |||||
| preload=False, | ||||||
| channel_naming="E%d", | ||||||
| *, | ||||||
| recover_epochs=False, | ||||||
| events_as_annotations=True, | ||||||
| verbose=None, | ||||||
| ): | ||||||
|
|
@@ -358,6 +380,7 @@ def _read_raw_egi_mff( | |||||
| exclude, | ||||||
| preload, | ||||||
| channel_naming, | ||||||
| recover_epochs=recover_epochs, | ||||||
| events_as_annotations=events_as_annotations, | ||||||
| verbose=verbose, | ||||||
| ) | ||||||
|
|
@@ -379,6 +402,7 @@ def __init__( | |||||
| preload=False, | ||||||
| channel_naming="E%d", | ||||||
| *, | ||||||
| recover_epochs=False, | ||||||
| events_as_annotations=True, | ||||||
| verbose=None, | ||||||
| ): | ||||||
|
|
@@ -393,7 +417,7 @@ def __init__( | |||||
| ) | ||||||
| ) | ||||||
| logger.info(f"Reading EGI MFF Header from {input_fname}...") | ||||||
| egi_info = _read_header(input_fname) | ||||||
| egi_info = _read_header(input_fname, recover_epochs=recover_epochs) | ||||||
| if eog is None: | ||||||
| eog = [] | ||||||
| if misc is None: | ||||||
|
|
||||||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -598,3 +598,45 @@ def test_egi_mff_bad_xml(tmp_path): | |
| raw = read_raw_egi(mff_fname) | ||
| # little check that the bad XML doesn't affect the parsing of other xml files | ||
| assert "DIN1" in raw.annotations.description | ||
|
|
||
|
|
||
| @requires_testing_data | ||
| def test_recover_epochs_raises_by_default(tmp_path): | ||
| """Test that mismatched epoch metadata raises RuntimeError by default.""" | ||
| import re as _re | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. No need to nest this import |
||
|
|
||
| mff_fname = copytree_rw(egi_mff_fname, tmp_path / "test_egi_bad_epochs.mff") | ||
| epochs_xml = mff_fname / "epochs.xml" | ||
| content = epochs_xml.read_text(encoding="utf-8") | ||
|
|
||
| def _corrupt_end(m): | ||
| val = int(m.group(1)) | ||
| return f"<endTime>{val * 100}</endTime>" | ||
|
|
||
| bad_content = _re.sub(r"<endTime>(\d+)</endTime>", _corrupt_end, content) | ||
| epochs_xml.write_text(bad_content, encoding="utf-8") | ||
| with pytest.raises( | ||
| RuntimeError, match="EGI epoch first/last samps could not be parsed" | ||
| ): | ||
| read_raw_egi(mff_fname, recover_epochs=False) | ||
|
|
||
|
|
||
| @requires_testing_data | ||
| def test_recover_epochs_succeeds_with_flag(tmp_path): | ||
| """Test that recover_epochs=True loads a file with mismatched epoch metadata.""" | ||
| import re as _re | ||
|
|
||
| mff_fname = copytree_rw(egi_mff_fname, tmp_path / "test_egi_recover_epochs.mff") | ||
| epochs_xml = mff_fname / "epochs.xml" | ||
| content = epochs_xml.read_text(encoding="utf-8") | ||
|
|
||
| def _corrupt_end(m): | ||
| val = int(m.group(1)) | ||
| return f"<endTime>{val * 100}</endTime>" | ||
|
|
||
| bad_content = _re.sub(r"<endTime>(\d+)</endTime>", _corrupt_end, content) | ||
| epochs_xml.write_text(bad_content, encoding="utf-8") | ||
| with pytest.warns(RuntimeWarning, match="EGI epoch metadata mismatch"): | ||
| raw = read_raw_egi(mff_fname, recover_epochs=True) | ||
| assert raw is not None | ||
| assert raw.n_times > 0 | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Style CIs will complain about these extra newlines