### Install pytep from repository Source: https://github.com/marciocamposjr/pytep-sound-ssp-sir/blob/master/README.md Install the pytep library from the repository root. Use the `.[notebooks]` extra for notebook-related functionalities. ```bash pip install -e . pip install -e ".[notebooks]" ``` -------------------------------- ### Start and Use MATLAB Engine for SOUND and SSP-SIR Source: https://context7.com/marciocamposjr/pytep-sound-ssp-sir/llms.txt Starts a MATLAB engine instance, applies SOUND and SSP-SIR processing to MNE objects, and then quits the engine. Ensure the MATLAB engine is installed and accessible. ```python import matlab.engine eng = matlab.engine.start_matlab() raw_clean = apply_sound(raw, eng=eng) # first pass: SOUND epochs_clean = apply_sspsir(epochs, eng=eng, pc=2) # second pass: SSP-SIR eng.quit() ``` -------------------------------- ### Share MATLAB Engine session with pytep functions Source: https://github.com/marciocamposjr/pytep-sound-ssp-sir/blob/master/README.md Start a MATLAB Engine session and share it with `apply_sound` and `apply_sspsir` for processing. Ensure to quit the session when done. ```python import matlab.engine from pytep import apply_sound, apply_sspsir eng = matlab.engine.start_matlab() raw_clean = apply_sound(raw, eng=eng) epochs_clean = apply_sspsir(epochs, eng=eng, pc=2) eng.quit() ``` -------------------------------- ### apply_sound Source: https://context7.com/marciocamposjr/pytep-sound-ssp-sir/llms.txt Runs the SOUND algorithm on MNE Raw or Epochs objects. Automatically starts MATLAB Engine if not provided, converts data, calls tesa_sound.m, and returns cleaned data. Requires a montage to be set on the input object. ```APIDOC ## apply_sound ### Description Applies the SOUND (Source-estimated Uncorrelated Noise Detection) algorithm to MNE `Raw` or `Epochs` objects. This function handles the conversion of MNE data to EEGLAB structures, calls the `tesa_sound.m` MATLAB script, and returns the cleaned data mapped back into MNE objects with an average reference applied. A montage must be set on the input object. ### Parameters - **raw_or_epochs** (mne.io.Raw or mne.Epochs) - The input EEG data. - **iter_num** (int, optional) - Number of iterations for the SOUND algorithm. Defaults to the value in `tesa_sound.m`. - **lambda_val** (float, optional) - Regularization parameter for the SOUND algorithm. Defaults to the value in `tesa_sound.m`. - **eng** (matlab.engine.MatlabEngine, optional) - An existing MATLAB Engine session to reuse. If not provided, a new session is started and closed automatically. ### Request Example ```python import mne from pytep import apply_sound # Load data and set montage raw = mne.io.read_raw_fif("sub01_raw.fif", preload=True) raw.set_montage("standard_1020") # Apply SOUND algorithm with default parameters raw_clean = apply_sound(raw) # Apply SOUND algorithm with custom parameters raw_clean_custom = apply_sound(raw, iter_num=10, lambda_val=0.05) # Using a pre-existing MATLAB engine session import matlab.engine eng = matlab.engine.start_matlab() try: raw_clean_eng = apply_sound(raw, eng=eng, iter_num=5, lambda_val=0.1) finally: eng.quit() # Applying to Epochs object epochs = mne.read_epochs("sub01-epo.fif", preload=True) epochs_clean = apply_sound(epochs, iter_num=5, lambda_val=0.1) ``` ### Response - **cleaned_raw_or_epochs** (mne.io.Raw or mne.Epochs) - A new MNE object containing the SOUND-cleaned EEG data, with an average reference applied. ``` -------------------------------- ### Apply SOUND algorithm for artifact cleaning Source: https://github.com/marciocamposjr/pytep-sound-ssp-sir/blob/master/README.md Load MNE-Python Raw data and apply the SOUND algorithm for artifact cleaning. Requires MNE-Python and a montage. ```python import mne from pytep import apply_sound # Load your data raw = mne.io.read_raw_edf("your_data.edf", preload=True) raw.set_montage("standard_1020") # Apply SOUND raw_clean = apply_sound(raw, iter_num=5, lambda_val=0.1) ``` -------------------------------- ### Apply SSP-SIR algorithm for artifact cleaning Source: https://github.com/marciocamposjr/pytep-sound-ssp-sir/blob/master/README.md Load epoched MNE-Python data and apply the SSP-SIR algorithm for artifact cleaning. Requires MNE-Python and a montage. ```python import mne from pytep import apply_sspsir # Load epoched data epochs = mne.read_epochs("your_epochs-epo.fif", preload=True) # Apply SSP-SIR epochs_clean = apply_sspsir(epochs, pc=2, art_scale='automatic') ``` -------------------------------- ### apply_sound Source: https://github.com/marciocamposjr/pytep-sound-ssp-sir/blob/master/README.md Applies the SOUND algorithm for artifact cleaning to MNE-Python Raw or Epochs objects. It can optionally use an existing MATLAB Engine session. ```APIDOC ## apply_sound(inst, eng=None, iter_num=5, lambda_val=0.1) ### Description Applies the SOUND algorithm for artifact cleaning to MNE-Python Raw or Epochs objects. It can optionally use an existing MATLAB Engine session. ### Parameters #### Path Parameters - **inst** (Raw/Epochs) - Required - MNE object with EEG data (montage required) - **eng** (MatlabEngine) - Optional - Existing MATLAB session - **iter_num** (int) - Optional - Number of SOUND iterations (default: 5) - **lambda_val** (float) - Optional - Regularization parameter (default: 0.1) ``` -------------------------------- ### Convert MNE Object to MATLAB Arguments using mne_to_eeglab_args Source: https://context7.com/marciocamposjr/pytep-sound-ssp-sir/llms.txt Converts MNE Raw data into MATLAB-compatible arrays and metadata. Requires a montage to be set on the MNE object. This function is a lower-level helper for direct MATLAB Engine calls. ```python import mne import numpy as np import matlab.engine from pytep import mne_to_eeglab_args raw = mne.io.read_raw_fif("sub01_raw.fif", preload=True) raw.set_montage("standard_1020") (data_mat, # matlab.double — shape (n_ch, n_times) labels, # list[str] — channel names coords_X, # matlab.double — X coordinates (mm) coords_Y, # matlab.double — Y coordinates (mm) coords_Z, # matlab.double — Z coordinates (mm) srate, # float — sampling rate in Hz picks, # np.ndarray — EEG channel indices is_epochs, # bool — False for Raw shape, # tuple — (n_ch, n_times) epoch_info # dict — {'n_times': ..., 'n_epochs': ...} ) = mne_to_eeglab_args(raw) print(f"Channels : {len(labels)}") # e.g. 64 print(f"Srate : {srate} Hz") # e.g. 1000.0 print(f"Is epochs: {is_epochs}") # False # Pass to a custom MATLAB function eng = matlab.engine.start_matlab() result = eng.my_custom_matlab_func(data_mat, labels, coords_X, coords_Y, coords_Z, srate) eng.quit() ``` -------------------------------- ### Apply SOUND Algorithm to Raw or Epoched EEG Source: https://context7.com/marciocamposjr/pytep-sound-ssp-sir/llms.txt Use `apply_sound` to clean MNE Raw or Epochs objects using the SOUND algorithm. It requires a montage and can automatically manage MATLAB Engine sessions or reuse an existing one. Custom parameters like `iter_num` and `lambda_val` can be adjusted. ```python import mne import numpy as np from pytep import apply_sound # ── 1. Load or create data ───────────────────────────────────────────────── raw = mne.io.read_raw_fif("sub01_raw.fif", preload=True) raw.set_montage("standard_1020") # montage is REQUIRED # ── 2. Basic usage (auto-starts & stops MATLAB Engine) ───────────────────── raw_clean = apply_sound(raw) # Output: Copy of raw with SOUND-cleaned EEG, average-referenced # Input shape: (64, 300000) # Output shape: (64, 300000) # ── 3. Custom parameters ─────────────────────────────────────────────────── raw_clean = apply_sound(raw, iter_num=10, lambda_val=0.05) # ── 4. Reuse an existing MATLAB Engine session (avoid restart overhead) ──── import matlab.engine eng = matlab.engine.start_matlab() raw_clean = apply_sound(raw, eng=eng, iter_num=5, lambda_val=0.1) # epochs_clean can follow — same eng session eng.quit() # ── 5. Works on Epochs too ───────────────────────────────────────────────── epochs = mne.read_epochs("sub01-epo.fif", preload=True) epochs_clean = apply_sound(epochs, iter_num=5, lambda_val=0.1) # ── 6. Synthetic data example (no real file needed) ─────────────────────── ch_names = ["Fz", "Cz", "Pz", "Oz", "C3", "C4"] info = mne.create_info(ch_names=ch_names, sfreq=1000, ch_types="eeg") info.set_montage(mne.channels.make_standard_montage("standard_1020")) data = np.random.randn(len(ch_names), 2000) * 1e-6 # 2 s of noise raw = mne.io.RawArray(data, info) raw_clean = apply_sound(raw, iter_num=5, lambda_val=0.1) print(f"Data changed: {not np.allclose(raw.get_data(), raw_clean.get_data())}") # Data changed: True ``` -------------------------------- ### apply_sspsir Source: https://github.com/marciocamposjr/pytep-sound-ssp-sir/blob/master/README.md Applies the SSP-SIR algorithm for artifact cleaning to MNE-Python Epochs objects. It can optionally use an existing MATLAB Engine session. ```APIDOC ## apply_sspsir(inst, eng=None, art_scale='automatic', time_range=None, pc=1, M=None) ### Description Applies the SSP-SIR algorithm for artifact cleaning to MNE-Python Epochs objects. It can optionally use an existing MATLAB Engine session. ### Parameters #### Path Parameters - **inst** (Epochs) - Required - Epoched MNE data (montage required) - **eng** (MatlabEngine) - Optional - Existing MATLAB session - **art_scale** (str) - Optional - `'automatic'`, `'manual'`, or `'manualConstant'` (default: 'automatic') - **time_range** (list[float]) - Optional - `[start_ms, end_ms]` artifact window - **pc** (int) - Optional - Number of artifact PCs to remove (default: 1) - **M** (int/None) - Optional - SIR truncation dimension ``` -------------------------------- ### Reconstruct MNE Object from MATLAB Output using eeglab_to_mne Source: https://context7.com/marciocamposjr/pytep-sound-ssp-sir/llms.txt Converts cleaned data from a MATLAB Engine call (as a `matlab.double` matrix) back into an MNE object. It handles both continuous and epoched data and automatically applies an average reference. ```python import numpy as np import matlab.engine from pytep import mne_to_eeglab_args, eeglab_to_mne # Assume `raw` is an mne.io.Raw with montage already set (data_mat, labels, cx, cy, cz, srate, picks, is_epochs, shape, epoch_info) = mne_to_eeglab_args(raw) eng = matlab.engine.start_matlab() eng.addpath("/path/to/matlab_scripts", nargout=0) # Call any MATLAB cleaning function that returns a data matrix cleaned_mat = eng.run_tesa_sound( data_mat, labels, cx, cy, cz, srate, 0.1, # lambda 5, # iterations epoch_info["n_times"], epoch_info["n_epochs"], ) eng.quit() # Convert back to MNE raw_clean = eeglab_to_mne(cleaned_mat, raw, picks, is_epochs, shape) print(type(raw_clean)) # print(raw_clean.get_data().shape) # (64, 300000) print(raw_clean.info["custom_ref_applied"]) # 1 (average ref set) ``` -------------------------------- ### Create Synthetic EEG Data with MNE Source: https://context7.com/marciocamposjr/pytep-sound-ssp-sir/llms.txt Generates synthetic EEG data using MNE-Python, including channel information, a standard montage, and epochs. This is useful for testing processing pipelines. ```python import mne import numpy as np ch_names = ["Fz", "Cz", "Pz", "Oz", "C3", "C4"] info = mne.create_info(ch_names=ch_names, sfreq=1000, ch_types="eeg") info.set_montage(mne.channels.make_standard_montage("standard_1020")) raw = mne.io.RawArray(np.random.randn(len(ch_names), 10000) * 1e-6, info) events = np.array([[i * 1000, 0, 1] for i in range(1, 9)]) epochs = mne.Epochs(raw, events, tmin=-0.2, tmax=0.5, baseline=None, preload=True) epochs_clean = apply_sspsir(epochs, pc=2, art_scale="automatic") print(f"Input shape: {epochs.get_data().shape}") # (8, 6, 701) print(f"Output shape: {epochs_clean.get_data().shape}") # (8, 6, 701) print(f"Data changed: {not np.allclose(epochs.get_data(), epochs_clean.get_data())}") # Data changed: True ``` -------------------------------- ### eeglab_to_mne Source: https://context7.com/marciocamposjr/pytep-sound-ssp-sir/llms.txt Reconstruct an MNE Object from MATLAB Output. Converts MATLAB processed data back into an MNE object, handling both continuous and epoched data and applying an average reference. ```APIDOC ## eeglab_to_mne — Reconstruct an MNE Object from MATLAB Output Converts a `matlab.double` cleaned data matrix (as returned by a MATLAB Engine call) back into a copy of the original MNE object. Handles both continuous (`Raw`) and epoched data by using the shape information returned by `mne_to_eeglab_args`. Automatically applies average reference to match SOUND/SSP-SIR output conventions. ```python import numpy as np import matlab.engine from pytep import mne_to_eeglab_args, eeglab_to_mne # Assume `raw` is an mne.io.Raw with montage already set (data_mat, labels, cx, cy, cz, srate, picks, is_epochs, shape, epoch_info) = mne_to_eeglab_args(raw) eng = matlab.engine.start_matlab() eng.addpath("/path/to/matlab_scripts", nargout=0) # Call any MATLAB cleaning function that returns a data matrix cleaned_mat = eng.run_tesa_sound( data_mat, labels, cx, cy, cz, srate, 0.1, # lambda 5, # iterations epoch_info["n_times"], epoch_info["n_epochs"], ) eng.quit() # Convert back to MNE raw_clean = eeglab_to_mne(cleaned_mat, raw, picks, is_epochs, shape) print(type(raw_clean)) # print(raw_clean.get_data().shape) # (64, 300000) print(raw_clean.info["custom_ref_applied"]) # 1 (average ref set) ``` ``` -------------------------------- ### Apply SSP-SIR Algorithm to Epoched EEG Source: https://context7.com/marciocamposjr/pytep-sound-ssp-sir/llms.txt Use `apply_sspsir` for cleaning MNE Epochs objects with the SSP-SIR algorithm, specifically for TMS-EEG data. The number of principal components (`pc`) must be provided. Options include automatic artifact scaling detection or manual specification of time ranges and SIR truncation dimensions. ```python import mne import numpy as np from pytep import apply_sspsir # ── 1. Prepare epoched data ──────────────────────────────────────────────── epochs = mne.read_epochs("sub01_tms-epo.fif", preload=True) epochs.set_montage("standard_1020") # montage is REQUIRED # ── 2. Automatic artifact-scale detection (simplest) ────────────────────── epochs_clean = apply_sspsir(epochs, pc=2) # art_scale='automatic' by default; pc MUST be provided # ── 3. Manual artifact window ───────────────────────────────────────────── epochs_clean = apply_sspsir( epochs, art_scale="manual", time_range=[5, 50], # ms: TMS pulse artefact window pc=3, ) # ── 4. manualConstant mode + SIR truncation ─────────────────────────────── epochs_clean = apply_sspsir( epochs, art_scale="manualConstant", time_range=[5, 50], pc=2, M=30, # SIR truncation dimension ) ``` -------------------------------- ### apply_sspsir Source: https://context7.com/marciocamposjr/pytep-sound-ssp-sir/llms.txt Runs the SSP-SIR algorithm on MNE Epochs objects. This function is specifically for epoched TMS-EEG data and requires the number of artifact principal components (`pc`) to be specified. It returns a cleaned copy of the input Epochs with an average reference applied. ```APIDOC ## apply_sspsir ### Description Applies the SSP-SIR (Signal Space Projection – Source Informed Reconstruction) algorithm to MNE `Epochs` objects. This algorithm is tailored for epoched TMS-EEG data. The number of artifact principal components (`pc`) must be explicitly provided. The function returns a cleaned copy of the input `Epochs` object with an average reference applied. ### Parameters - **epochs** (mne.Epochs) - The input epoched EEG data. - **art_scale** (str, optional) - Method for artifact scaling. Options include 'automatic' (default), 'manual', or 'manualConstant'. - **time_range** (list of float, optional) - The time window in milliseconds to consider for artifact detection when `art_scale` is 'manual' or 'manualConstant'. Example: `[5, 50]`. - **pc** (int) - Required. The number of artifact principal components to use for SSP-SIR. - **M** (int, optional) - The SIR truncation dimension. Used when `art_scale` is 'manualConstant'. - **eng** (matlab.engine.MatlabEngine, optional) - An existing MATLAB Engine session to reuse. If not provided, a new session is started and closed automatically. ### Request Example ```python import mne from pytep import apply_sspsir # Load epoched data and set montage epochs = mne.read_epochs("sub01_tms-epo.fif", preload=True) epochs.set_montage("standard_1020") # Apply SSP-SIR with automatic artifact scaling and specified pc epochs_clean_auto = apply_sspsir(epochs, pc=2) # Apply SSP-SIR with manual artifact scaling and time range epochs_clean_manual = apply_sspsir( epochs, art_scale="manual", time_range=[5, 50], pc=3, ) # Apply SSP-SIR with manualConstant mode and SIR truncation epochs_clean_manual_const = apply_sspsir( epochs, art_scale="manualConstant", time_range=[5, 50], pc=2, M=30, ) ``` ### Response - **cleaned_epochs** (mne.Epochs) - A new MNE `Epochs` object containing the SSP-SIR cleaned EEG data, with an average reference applied. ``` -------------------------------- ### mne_to_eeglab_args Source: https://context7.com/marciocamposjr/pytep-sound-ssp-sir/llms.txt Convert an MNE Object to MATLAB-Compatible Arguments. This helper function extracts EEG data and channel metadata from MNE objects (Raw, Epochs, Evoked) and prepares them for MATLAB Engine calls. ```APIDOC ## mne_to_eeglab_args — Convert an MNE Object to MATLAB-Compatible Arguments A lower-level helper that extracts EEG data and channel metadata from any MNE `Raw`, `Epochs`, or `Evoked` object and returns them as `matlab.double` arrays and Python lists suitable for passing directly to a MATLAB Engine call. Raises `ValueError` if the montage has not been set (all-zero coordinates). ```python import mne import numpy as np import matlab.engine from pytep import mne_to_eeglab_args raw = mne.io.read_raw_fif("sub01_raw.fif", preload=True) raw.set_montage("standard_1020") (data_mat, # matlab.double — shape (n_ch, n_times) labels, # list[str] — channel names coords_X, # matlab.double — X coordinates (mm) coords_Y, # matlab.double — Y coordinates (mm) coords_Z, # matlab.double — Z coordinates (mm) srate, # float — sampling rate in Hz picks, # np.ndarray — EEG channel indices is_epochs, # bool — False for Raw shape, # tuple — (n_ch, n_times) epoch_info # dict — {'n_times': ..., 'n_epochs': ...} ) = mne_to_eeglab_args(raw) print(f"Channels : {len(labels)}") # e.g. 64 print(f"Srate : {srate} Hz") # e.g. 1000.0 print(f"Is epochs: {is_epochs}") # False # Pass to a custom MATLAB function eng = matlab.engine.start_matlab() result = eng.my_custom_matlab_func(data_mat, labels, coords_X, coords_Y, coords_Z, srate) eng.quit() ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.