-
Notifications
You must be signed in to change notification settings - Fork 46
[DRAFT] Redesign/datasets ICA addition #56
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
Merged
bruAristimunha
merged 38 commits into
speechbrain:develop-eeg
from
vmcru:redesign/datasets
Apr 1, 2025
Merged
Changes from 17 commits
Commits
Show all changes
38 commits
Select commit
Hold shift + click to select a range
66faeaa
initial test for ica dynamic item inclusion
vmcru 4b62e60
exposed method for ica, used mne BIDSPath, path needs checking for pr…
vmcru c3ec3dc
Apply suggestions from code review
bruAristimunha 77a8c59
Apply suggestions from code review
bruAristimunha a222c7c
Merge branch 'redesign/datasets' into redesign/datasets
vmcru 3a78e1d
modifications to ica and validate to pass merge
vmcru 86af6be
removed unused imports from all files and added credits
vmcru f29636c
updated validate_ica.py
vmcru 30ff4be
Apply suggestions from code review
bruAristimunha f3330d9
support for ica as process added.
vmcru 4e8bb55
Added hashing, setting check, and fixed caching bug.
vmcru b592c60
precommit mods
vmcru e2973aa
formatting fix
vmcru 3f8b646
optional filtering added
vmcru 73d1e93
added hashing to description name.
vmcru ade6b8d
added python-picard dependency in extra-requirements.txt for ica pica…
vmcru 8b6633e
format fix extra-requirements.txt
vmcru a1031d2
Update benchmarks/MOABB/dataio/ica.py
vmcru 282c016
Update benchmarks/MOABB/dataio/ica.py
vmcru ad2e39d
Update benchmarks/MOABB/dataio/datasets.py
vmcru 822dc46
renamic critical to base and removing unnecessary comments
vmcru c524d11
tests upgrading pytest to see if it fixes breaks
vmcru a6fb933
added docstrings to process andn dynamic items functions.
vmcru 544e638
formatting fixes
vmcru 77daeeb
docstring fix
vmcru 84e09dc
docstring adaptations for validate_ica.py
vmcru 96e2546
precommit fixes
vmcru 87ef955
Merge branch 'develop-eeg' into redesign/datasets
vmcru 6e22fe5
rework of the metadata checking and storing
vmcru ab42aa9
metadata changes
vmcru 2652128
precommit fixes
vmcru f2263e4
updates to the test files and minor tqeat to ica parameters.
vmcru 210dd9e
adapted hashing for consistency and reproducibility. removed optional…
vmcru d787c0b
shpeechbrain changes.
vmcru 4b03501
removed validate_ica.py from tracked files
vmcru 06f873a
changed folder from derivaties to processor
vmcru ead65b3
precommit action error fix
vmcru 82cdd90
precommit action error fix 2
vmcru 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
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,183 @@ | ||||||||||||||||||||||||
| """Module for handling ICA computation and application for EEG data. | ||||||||||||||||||||||||
| Author | ||||||||||||||||||||||||
| ------ | ||||||||||||||||||||||||
| Victor Cruz, 2025 | ||||||||||||||||||||||||
| """ | ||||||||||||||||||||||||
| from pathlib import Path | ||||||||||||||||||||||||
| from typing import Union, Optional, Dict, Any | ||||||||||||||||||||||||
| import json | ||||||||||||||||||||||||
| import hashlib | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| import mne | ||||||||||||||||||||||||
| from mne.preprocessing import ICA | ||||||||||||||||||||||||
| from mne_bids import get_bids_path_from_fname | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| from speechbrain.utils.data_pipeline import provides, takes | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| class ICAProcessor: | ||||||||||||||||||||||||
| """Handles ICA computation and application for EEG data. | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| Arguments | ||||||||||||||||||||||||
| --------- | ||||||||||||||||||||||||
| n_components : int | float | None | ||||||||||||||||||||||||
| Number of components to keep during ICA decomposition | ||||||||||||||||||||||||
| method : str | ||||||||||||||||||||||||
| The ICA method to use. Can be 'fastica', 'infomax' or 'picard'. | ||||||||||||||||||||||||
| Defaults to 'fastica'. | ||||||||||||||||||||||||
| random_state : int | None | ||||||||||||||||||||||||
| Random state for reproducibility | ||||||||||||||||||||||||
| fit_params : dict | None | ||||||||||||||||||||||||
| Additional parameters to pass to the ICA fit method. | ||||||||||||||||||||||||
| See mne.preprocessing.ICA for details. | ||||||||||||||||||||||||
| filter_params : dict | None | ||||||||||||||||||||||||
| Parameters for the high-pass filter applied before ICA. | ||||||||||||||||||||||||
| Set to None to skip filtering if data is already filtered. | ||||||||||||||||||||||||
| Defaults to {'l_freq': 1.0, 'h_freq': None} | ||||||||||||||||||||||||
| """ | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| def __init__( | ||||||||||||||||||||||||
| self, | ||||||||||||||||||||||||
| n_components=None, | ||||||||||||||||||||||||
| method="fastica", | ||||||||||||||||||||||||
| random_state=42, | ||||||||||||||||||||||||
| fit_params: Optional[Dict[str, Any]] = None, | ||||||||||||||||||||||||
| filter_params: Optional[Dict[str, Any]] = None, | ||||||||||||||||||||||||
| use_hash: bool = True, | ||||||||||||||||||||||||
| ): | ||||||||||||||||||||||||
| self.n_components = n_components | ||||||||||||||||||||||||
| self.method = method | ||||||||||||||||||||||||
| self.random_state = random_state | ||||||||||||||||||||||||
| self.fit_params = fit_params or {} | ||||||||||||||||||||||||
| self.filter_params = filter_params or {"l_freq": 1.0, "h_freq": None} | ||||||||||||||||||||||||
| self.use_hash = use_hash | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| def _get_params_hash(self) -> str: | ||||||||||||||||||||||||
| """Generate a short hash of the ICA parameters.""" | ||||||||||||||||||||||||
| # Select critical parameters that affect the ICA computation | ||||||||||||||||||||||||
| # not accessible from ICA object for standarization | ||||||||||||||||||||||||
| critical_params = { | ||||||||||||||||||||||||
|
vmcru marked this conversation as resolved.
Outdated
|
||||||||||||||||||||||||
| "n_components": self.n_components, | ||||||||||||||||||||||||
| "method": self.method, | ||||||||||||||||||||||||
| "filter_params": self.filter_params, | ||||||||||||||||||||||||
| } | ||||||||||||||||||||||||
| # Create a deterministic string representation and hash it | ||||||||||||||||||||||||
| param_str = json.dumps(critical_params, sort_keys=True) | ||||||||||||||||||||||||
|
vmcru marked this conversation as resolved.
Outdated
|
||||||||||||||||||||||||
| return hashlib.md5(param_str.encode()).hexdigest()[ | ||||||||||||||||||||||||
| :8 | ||||||||||||||||||||||||
| ] # First 8 chars are enough | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| def get_ica_metadata(self) -> Dict: | ||||||||||||||||||||||||
| """ Generate metadata dictionary for the ICA parameters. """ | ||||||||||||||||||||||||
| return { | ||||||||||||||||||||||||
| "n_components": self.n_components, | ||||||||||||||||||||||||
| "method": self.method, | ||||||||||||||||||||||||
| "random_state": self.random_state, | ||||||||||||||||||||||||
| "filter_params": self.filter_params, | ||||||||||||||||||||||||
| "fit_params": self.fit_params, | ||||||||||||||||||||||||
| } | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| def get_ica_path(self, raw_path: Union[str, Path]) -> tuple[Path, Path]: | ||||||||||||||||||||||||
| """Generate path where ICA solution should be stored. | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| Creates a derivatives folder to store ICA solutions, following BIDS conventions. | ||||||||||||||||||||||||
| Returns | ||||||||||||||||||||||||
| ------- | ||||||||||||||||||||||||
| tuple[Path, Path] | ||||||||||||||||||||||||
| Returns (ica_path, metadata_path) | ||||||||||||||||||||||||
| """ | ||||||||||||||||||||||||
| bids_path = get_bids_path_from_fname(raw_path) | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| if self.use_hash: | ||||||||||||||||||||||||
| param_hash = self._get_params_hash() | ||||||||||||||||||||||||
| folder_name = f"ica-{self.method}-{param_hash}" | ||||||||||||||||||||||||
| desc = f"ica{param_hash}" | ||||||||||||||||||||||||
| else: | ||||||||||||||||||||||||
| folder_name = f"ica{self.method}" | ||||||||||||||||||||||||
| desc = f"ica" | ||||||||||||||||||||||||
|
vmcru marked this conversation as resolved.
Outdated
|
||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| # For derivatives, you can put them in a derivatives folder: | ||||||||||||||||||||||||
| bids_path.root = bids_path.root / ".." / "derivatives" / folder_name | ||||||||||||||||||||||||
| # Keep the same base entities: | ||||||||||||||||||||||||
| bids_path.update( | ||||||||||||||||||||||||
| suffix="eeg", # override or confirm suffix | ||||||||||||||||||||||||
| extension=".fif", | ||||||||||||||||||||||||
| description=desc, # <-- This sets a desc=ica entity | ||||||||||||||||||||||||
| check=True, # If you do not want BIDSPath to fail on derivative checks | ||||||||||||||||||||||||
| ) | ||||||||||||||||||||||||
|
Collaborator
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
|
||||||||||||||||||||||||
| # Make sure the folder is created | ||||||||||||||||||||||||
| bids_path.fpath.parent.mkdir(parents=True, exist_ok=True) | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| ica_path = bids_path.fpath | ||||||||||||||||||||||||
| metadata_path = ica_path.with_suffix(".json") | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| return ica_path, metadata_path | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| def save_ica(self, ica: ICA, ica_path: Path, metadata_path: Path): | ||||||||||||||||||||||||
| """Save ICA solution and metadata to disk.""" | ||||||||||||||||||||||||
| # Save ICA solution | ||||||||||||||||||||||||
| ica.save(ica_path, overwrite=True) | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| # Save metadata | ||||||||||||||||||||||||
| with metadata_path.open("w") as f: | ||||||||||||||||||||||||
| json.dump(self.get_ica_metadata(), f) | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| def check_ica_metadata(self, metadata_path: Path) -> bool: | ||||||||||||||||||||||||
| """Check if existing ICA metadata matches current parameters.""" | ||||||||||||||||||||||||
| if not metadata_path.exists(): | ||||||||||||||||||||||||
| return False | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| with metadata_path.open() as f: | ||||||||||||||||||||||||
| saved_metadata = json.load(f) | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| current_metadata = self.get_ica_metadata() | ||||||||||||||||||||||||
| return saved_metadata == current_metadata | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| def compute_ica(self, raw: mne.io.RawArray, ica_path: Path) -> ICA: | ||||||||||||||||||||||||
| """Compute ICA solution and save to disk. | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| If filter_params is provided, applies a high-pass filter before ICA computation. | ||||||||||||||||||||||||
| This step can be skipped if the data is already filtered by setting | ||||||||||||||||||||||||
| filter_params to None during ICAProcessor initialization. | ||||||||||||||||||||||||
| """ | ||||||||||||||||||||||||
| if self.filter_params is not None: | ||||||||||||||||||||||||
| # Apply high-pass filter only if filter parameters are provided | ||||||||||||||||||||||||
| raw_filtered = raw.copy() | ||||||||||||||||||||||||
| raw_filtered.filter(**self.filter_params) | ||||||||||||||||||||||||
| else: | ||||||||||||||||||||||||
| # Use raw data directly if no filtering is needed | ||||||||||||||||||||||||
| raw_filtered = raw | ||||||||||||||||||||||||
|
vmcru marked this conversation as resolved.
Outdated
|
||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| ica = ICA( | ||||||||||||||||||||||||
| n_components=self.n_components, | ||||||||||||||||||||||||
| method=self.method, | ||||||||||||||||||||||||
| random_state=self.random_state, | ||||||||||||||||||||||||
| **self.fit_params, | ||||||||||||||||||||||||
|
vmcru marked this conversation as resolved.
Outdated
|
||||||||||||||||||||||||
| ) | ||||||||||||||||||||||||
| ica.fit(raw_filtered) | ||||||||||||||||||||||||
| ica.save(ica_path) | ||||||||||||||||||||||||
| return ica | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| @property | ||||||||||||||||||||||||
| def dynamic_item(self): | ||||||||||||||||||||||||
| @takes("raw", "fpath") | ||||||||||||||||||||||||
| @provides("raw", "ica_path") | ||||||||||||||||||||||||
| def process(raw: mne.io.RawArray, fpath: Union[str, Path]): | ||||||||||||||||||||||||
| """Process raw data with ICA, computing or loading from cache.""" | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| ica_path, metadata_path = self.get_ica_path(fpath) | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| if ica_path.exists() and self.check_ica_metadata(metadata_path): | ||||||||||||||||||||||||
| ica = mne.preprocessing.read_ica(ica_path, verbose="ERROR") | ||||||||||||||||||||||||
| else: | ||||||||||||||||||||||||
| ica = self.compute_ica(raw, ica_path) | ||||||||||||||||||||||||
| self.save_ica(ica, ica_path, metadata_path) | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| # Create a copy of the raw data before applying ICA | ||||||||||||||||||||||||
| raw_ica = raw.copy() | ||||||||||||||||||||||||
| ica.apply(raw_ica) | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| yield raw_ica | ||||||||||||||||||||||||
| yield ica_path | ||||||||||||||||||||||||
|
|
||||||||||||||||||||||||
| return process | ||||||||||||||||||||||||
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 |
|---|---|---|
| @@ -1,4 +1,5 @@ | ||
| git+https://github.com/braindecode/braindecode | ||
| moabb | ||
| orion[profet] | ||
| python-picard | ||
| scikit-learn |
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.
Uh oh!
There was an error while loading. Please reload this page.