### Complete TESA Pipeline for TMS-EEG Analysis Source: https://context7.com/nigelrogasch/tesa/llms.txt This script executes the full TESA pipeline, starting from data loading and preprocessing, through artifact removal using ICA, to TEP extraction and peak analysis. It requires EEGLAB and the TESA toolbox to be installed. ```matlab clear; close all; clc; filepath = 'C:\tmseeg\data\'; fileprefix = 'subject01'; % --- Launch EEGLAB --- [ALLEEG, EEG, CURRENTSET, ALLCOM] = eeglab; % 1. Load data and channel locations EEG = pop_loadset('filename', [fileprefix, '.set'], 'filepath', filepath); EEG = pop_chanedit(EEG, 'lookup', 'C:\Program Files\MATLAB\eeglab\plugins\dipfit\standard_BESA\standard-10-5-cap385.elp'); % 2. Remove unused electrodes; save full channel list for later interpolation EEG = pop_select(EEG, 'nochannel', {'31', '32'}); EEG.allchan = EEG.chanlocs; % 3. Detect bad channels (ignore TMS artifact window) [EEG, ~] = tesa_detectbadchannels(EEG, ... 'detectionMethod', 'TESA_DDWiener_IgnoreArtifactTime', 'artifactTimespan', [-5, 50]); % 4. Epoch (-1000 to 1000 ms around TMS trigger) EEG = pop_epoch(EEG, {'R128'}, [-1, 1], 'epochinfo', 'yes'); EEG = pop_rmbase(EEG, [-1000, 1000]); % 5. First removal pass: blank TMS pulse artifact (-2 to 10 ms) → cubic interpolation EEG = tesa_removedata(EEG, [-2, 10]); EEG = tesa_interpdata(EEG, 'cubic', [1, 1]); % 6. Downsample and remove bad trials EEG = pop_resample(EEG, 1000); EEG = pop_jointprob(EEG, 1, 1:size(EEG.data,1), 5, 5, 0, 0); % 7. First ICA: remove TMS-evoked muscle activity only EEG = tesa_removedata(EEG, [-2, 10]); EEG = tesa_fastica(EEG, 'approach', 'symm', 'g', 'tanh'); EEG = tesa_compselect(EEG, ... 'tmsMuscle', 'on', 'tmsMuscleThresh', 8, 'tmsMuscleWin', [11, 30], ... 'blink', 'off', 'move', 'off', 'muscle', 'off', 'elecNoise', 'off'); % 8. Extend blank window (-2 to 15 ms) → interpolate → filter EEG = tesa_removedata(EEG, [-2, 15]); EEG = tesa_interpdata(EEG, 'cubic', [5, 5]); EEG = tesa_filtbutter(EEG, 1, 100, 4, 'bandpass'); EEG = tesa_filtbutter(EEG, 48, 52, 4, 'bandstop'); % 9. Second ICA: remove all remaining artifacts EEG = tesa_removedata(EEG, [-2, 15]); EEG = tesa_fastica(EEG, 'approach', 'symm', 'g', 'tanh'); EEG = tesa_compselect(EEG, ... 'figSize', 'small', 'plotTimeX', [-200, 500], 'plotFreqX', [1, 100], ... 'tmsMuscle', 'on', 'tmsMuscleThresh', 8, 'tmsMuscleWin', [11, 30], ... 'blink', 'on', 'blinkThresh', 2.5, 'blinkElecs', {'Fp1', 'Fp2'}, 'move', 'on', 'moveThresh', 2, 'moveElecs', {'F7', 'F8'}, 'muscle', 'on', 'muscleThresh', -0.31, ... 'elecNoise', 'on', 'elecNoiseThresh', 4); % 10. Final interpolation, channel restoration, re-reference EEG = tesa_interpdata(EEG, 'cubic', [5, 5]); EEG = pop_interp(EEG, EEG.allchan, 'spherical'); EEG = pop_reref(EEG, []); EEG = pop_saveset(EEG, 'filename', [fileprefix, '_cleaned.set'], 'filepath', filepath); % 11. TEP extraction: parietal ROI EEG = tesa_tepextract(EEG, 'ROI', ... 'elecs', {'P3', 'CP1', 'P1', 'CP3'}, 'tepName', 'Parietal'); % 12. Peak analysis: positive and negative peaks EEG = tesa_peakanalysis(EEG, 'ROI', 'positive', [40, 80, 200], [30, 50; 70, 90; 180, 220], 'method', 'largest', 'tepName', 'Parietal'); EEG = tesa_peakanalysis(EEG, 'ROI', 'negative', [20, 60, 100], [10, 30; 50, 70; 90, 110], 'method', 'largest', 'tepName', 'Parietal'); % 13. Export results table and plot output = tesa_peakoutput(EEG, 'tepName', 'Parietal', ... 'calcType', 'amplitude', 'winType', 'individual', 'tablePlot', 'on'); pop_tesa_plot(EEG, 'tepType', 'ROI', 'tepName', 'Parietal', ... 'xlim', [-100, 500], 'plotPeak', 'on'); EEG = pop_saveset(EEG, 'filename', [fileprefix, '_cleaned_analysed.set'], 'filepath', filepath); ``` -------------------------------- ### Run FastICA with tesa_fastica Source: https://context7.com/nigelrogasch/tesa/llms.txt Runs FastICA using settings optimized for TMS-EEG, typically the symmetric approach and 'tanh' contrast function. Saves the random-number generator state for reproducibility and automatically runs tesa_sortcomps. ```matlab EEG = tesa_fastica(EEG); ``` ```matlab EEG = tesa_fastica(EEG, 'g', 'gauss', 'stabilization', 'on'); ``` ```matlab EEG = tesa_fastica(EEG, 'approach', 'defl', 'g', 'tanh'); ``` -------------------------------- ### Median Filter for Spike Artifact Removal with tesa_filtmedian Source: https://context7.com/nigelrogasch/tesa/llms.txt Applies a 1-D median filter within a specified time window around a given event label. Useful for removing sharp spike artifacts. Can target specific manually labelled artifact events. ```matlab EEG = tesa_filtmedian(EEG, [-2, 2], 3, 'spike'); ``` ```matlab EEG = tesa_filtmedian(EEG, [-5, 5], 10, 'TMS'); ``` ```matlab EEG = tesa_filtmedian(EEG, [-1, 1], 3, 'spike'); ``` -------------------------------- ### Export TEP peak data using tesa_peakoutput Source: https://context7.com/nigelrogasch/tesa/llms.txt Exports peak amplitudes and latencies to a MATLAB table. Supports absolute amplitude, windowed average amplitude, and area under the curve. Optionally plots a summary table figure. ```matlab output = tesa_peakoutput(EEG); ``` ```matlab output = tesa_peakoutput(EEG, 'averageWin', 5); ``` ```matlab output = tesa_peakoutput(EEG, ... 'calcType', 'area', ... 'averageWin', 10, ... 'tepName', 'parietal'); ``` ```matlab output = tesa_peakoutput(EEG, ... 'winType', 'fixed', ... 'fixedPeak', [30, 60, 100, 180], ... 'averageWin', 5, ... 'tablePlot', 'on'); ``` -------------------------------- ### tesa_fastica Source: https://context7.com/nigelrogasch/tesa/llms.txt Runs FastICA via EEGLAB's `pop_runica` using settings optimised for TMS-EEG. Saves the random-number generator state for reproducibility. ```APIDOC ## tesa_fastica — Run FastICA on TMS-EEG data ### Description Runs FastICA via EEGLAB's `pop_runica` using settings optimised for TMS-EEG. The symmetric approach and `tanh` contrast function are the recommended defaults based on published benchmarks. Saves the random-number generator state for reproducibility. After decomposition, automatically runs `tesa_sortcomps` to rank components by variance. ### Method Signature `EEG = tesa_fastica(EEG, 'approach', approach_type, 'g', contrast_function, 'stabilization', stabilization_setting)` ### Parameters - **EEG**: Input EEG data structure. - **'approach'** (Optional): The ICA approach. Options include 'symm' (symmetric, default) and 'defl' (deflation). - **'g'** (Optional): The contrast function. Options include 'tanh' (default) and 'gauss'. - **'stabilization'** (Optional): Enables stabilization for the ICA algorithm. Accepts 'on' or 'off'. ### Examples ```matlab % Default: symmetric approach, tanh contrast function EEG = tesa_fastica(EEG); % Gaussian contrast function with stabilization enabled EEG = tesa_fastica(EEG, 'g', 'gauss', 'stabilization', 'on'); % Deflation approach with tanh contrast function EEG = tesa_fastica(EEG, 'approach', 'defl', 'g', 'tanh'); ``` ``` -------------------------------- ### tesa_detectbadchannels Source: https://context7.com/nigelrogasch/tesa/llms.txt Identifies bad channels using PREP-style robust deviation, data-driven Wiener noise estimates, or artifact-aware variants. Can interpolate, remove, replace with NaN, or simply flag bad channels. ```APIDOC ## tesa_detectbadchannels ### Description Identifies bad channels using PREP-style robust deviation, data-driven Wiener noise estimates, or artifact-aware variants. Can interpolate, remove, replace with NaN, or simply flag bad channels. Saves the original channel locations in `EEG.chansAll` for later interpolation. ### Usage ```matlab % Default: PREP_deviation method, interpolate bad channels [EEG, misc] = tesa_detectbadchannels(EEG); % DDWiener with TMS artifact window excluded from detection [EEG, misc] = tesa_detectbadchannels(EEG, ... 'detectionMethod', 'TESA_DDWiener_IgnoreArtifactTime', ... 'artifactTimespan', [-5, 50], ... 'replaceMethod', 'interpolate'); % Detect only (do not modify data), custom threshold [EEG, misc] = tesa_detectbadchannels(EEG, ... 'detectionMethod', 'PREP_deviation', ... 'threshold', 7, ... 'replaceMethod', 'none'); % Remove (delete) bad channels, per-trial DDWiener [EEG, misc] = tesa_detectbadchannels(EEG, ... 'detectionMethod', 'TESA_DDWiener_PerTrial', ... 'replaceMethod', 'remove'); ``` ``` -------------------------------- ### Detect and Replace Bad EEG Channels with tesa_detectbadchannels Source: https://context7.com/nigelrogasch/tesa/llms.txt Identifies bad channels using various methods and can interpolate, remove, replace with NaN, or flag them. Saves original channel locations in EEG.chansAll. Use 'replaceMethod', 'none' to detect only. ```matlab [EEG, misc] = tesa_detectbadchannels(EEG); ``` ```matlab [EEG, misc] = tesa_detectbadchannels(EEG, ... 'detectionMethod', 'TESA_DDWiener_IgnoreArtifactTime', ... 'artifactTimespan', [-5, 50], ... 'replaceMethod', 'interpolate'); ``` ```matlab [EEG, misc] = tesa_detectbadchannels(EEG, ... 'detectionMethod', 'PREP_deviation', ... 'threshold', 7, ... 'replaceMethod', 'none'); ``` ```matlab [EEG, misc] = tesa_detectbadchannels(EEG, ... 'detectionMethod', 'TESA_DDWiener_PerTrial', ... 'replaceMethod', 'remove'); ``` -------------------------------- ### Interpolate Blanked Regions with tesa_interpdata Source: https://context7.com/nigelrogasch/tesa/llms.txt Fills blanked regions in EEG data using linear or cubic polynomial interpolation. Must follow tesa_removedata in the pipeline. Cubic interpolation uses a fitting window around the blank. ```matlab EEG = tesa_interpdata(EEG, 'linear'); ``` ```matlab EEG = tesa_interpdata(EEG, 'cubic'); ``` ```matlab EEG = tesa_interpdata(EEG, 'cubic', [1, 1]); ``` ```matlab EEG = tesa_interpdata(EEG, 'cubic', [50, 50]); ``` -------------------------------- ### Classify and Remove ICA Components with tesa_compselect Source: https://context7.com/nigelrogasch/tesa/llms.txt Applies heuristic rules to classify ICA components and allows for manual override. Results are stored in EEG.icaCompClass. Use 'remove', 'off' to classify only. ```matlab EEG = tesa_compselect(EEG); ``` ```matlab EEG = tesa_compselect(EEG, ... 'tmsMuscle', 'on', 'tmsMuscleThresh', 8, 'tmsMuscleWin', [11, 30], ... 'blink', 'off', ... 'move', 'off', ... 'muscle', 'off', ... 'elecNoise', 'off'); ``` ```matlab EEG = tesa_compselect(EEG, ... 'figSize', 'medium', ... 'plotTimeX', [-200, 500], ... 'plotFreqX', [1, 100], ... 'tmsMuscle', 'on', 'tmsMuscleThresh', 8, 'tmsMuscleWin', [11, 30], ... 'blink', 'on', 'blinkThresh', 2.5, 'blinkElecs', {'Fp1', 'Fp2'}, ... 'move', 'on', 'moveThresh', 2, 'moveElecs', {'F7', 'F8'}, ... 'muscle', 'on', 'muscleThresh', -0.31, ... 'elecNoise', 'on', 'elecNoiseThresh', 4); ``` ```matlab EEG = tesa_compselect(EEG, 'remove', 'off'); ``` -------------------------------- ### Remove Slow Drifts with tesa_detrend Source: https://context7.com/nigelrogasch/tesa/llms.txt Removes low-frequency drift by fitting and subtracting a linear, exponential, or double-exponential function from each channel. Requires the MATLAB Curve Fitting Toolbox for exponential modes. ```matlab EEG = tesa_detrend(EEG, 'linear', [11, 500]); ``` ```matlab EEG = tesa_detrend(EEG, 'exponential', [11, 500]); ``` ```matlab EEG = tesa_detrend(EEG, 'double', [11, 500]); ``` -------------------------------- ### Apply Zero-Phase Butterworth Filter with tesa_filtbutter Source: https://context7.com/nigelrogasch/tesa/llms.txt Applies a forward–backward (zero-phase) Butterworth filter. Supports bandpass, bandstop, highpass, and lowpass configurations. Processes all channels across concatenated trials to minimize edge artifacts. ```matlab EEG = tesa_filtbutter(EEG, 1, 100, 4, 'bandpass'); ``` ```matlab EEG = tesa_filtbutter(EEG, 48, 52, 4, 'bandstop'); ``` ```matlab EEG = tesa_filtbutter(EEG, 1, [], 4, 'highpass'); ``` ```matlab EEG = tesa_filtbutter(EEG, [], 45, 4, 'lowpass'); ``` -------------------------------- ### tesa_peakoutput Source: https://context7.com/nigelrogasch/tesa/llms.txt Exports TEP peak amplitudes and latencies to a table. Supports various calculation types and optional plotting. ```APIDOC ## tesa_peakoutput ### Description Returns peak amplitudes and latencies detected by `tesa_peakanalysis` (or user-supplied fixed latencies) as a MATLAB table. Supports absolute peak amplitude, windowed average amplitude, and area under the curve (GMFA). Optionally plots a summary table figure. ### Parameters * `EEG` - Input EEG data structure. * `calcType` - (Optional) Type of calculation: 'amplitude' (default), 'average', or 'area'. * `averageWin` - (Optional) Window size (ms) for 'average' or 'area' calculation. * `tepName` - (Optional) Name of the TEP to process, if multiple ROIs are present. * `winType` - (Optional) Type of windowing: 'detected' (uses latencies from `tesa_peakanalysis`) or 'fixed'. * `fixedPeak` - (Optional, for `winType` 'fixed') Array of fixed peak latencies (ms). * `tablePlot` - (Optional) 'on' to display a summary table figure. ### Examples ```matlab % Absolute amplitude at individually detected peak latencies, all TEPs output = tesa_peakoutput(EEG); % Average amplitude ±5 ms around each individual peak output = tesa_peakoutput(EEG, 'averageWin', 5); % Area under GMFA curve ±10 ms around peaks in the 'parietal' ROI output = tesa_peakoutput(EEG, ... 'calcType', 'area', 'averageWin', 10, 'tepName', 'parietal'); % Fixed latencies (no prior tesa_peakanalysis needed), with table plot output = tesa_peakoutput(EEG, ... 'winType', 'fixed', 'fixedPeak', [30, 60, 100, 180], 'averageWin', 5, 'tablePlot', 'on'); ``` ``` -------------------------------- ### Extract TEPs by ROI or GMFA using tesa_tepextract Source: https://context7.com/nigelrogasch/tesa/llms.txt Averages cleaned, epoched data to generate TEP waveforms. Supports region-of-interest (ROI) averaging and global mean field amplitude (GMFA). Handles paired-pulse correction by subtracting a single-pulse reference TEP. ```matlab EEG = tesa_tepextract(EEG, 'ROI', 'elecs', {'FC1', 'FC3', 'C1', 'C3'}); ``` ```matlab EEG = tesa_tepextract(EEG, 'ROI', 'elecs', {'C1', 'C3'}, 'tepName', 'motor'); ``` ```matlab EEG = tesa_tepextract(EEG, 'GMFA'); ``` ```matlab EEG = tesa_tepextract(EEG, 'ROI', 'elecs', 'C3', ... 'pairCorrect', 'on', 'ISI', 100, ... 'fileName', 'C:\tmseeg\single_pulse_TEP.set'); ``` -------------------------------- ### tesa_interpdata Source: https://context7.com/nigelrogasch/tesa/llms.txt Fills blanked regions using linear or cubic polynomial interpolation. Must follow `tesa_removedata` in the pipeline. ```APIDOC ## tesa_interpdata — Interpolate blanked TMS artifact window ### Description Fills blanked regions (created by `tesa_removedata`) using linear or cubic polynomial interpolation. For cubic, a fitting window around the blank is used to estimate the polynomial. Must follow `tesa_removedata` in the pipeline. ### Method Signature `EEG = tesa_interpdata(EEG, interpolation_type, [window_ms])` ### Parameters - **EEG**: Input EEG data structure. - **interpolation_type**: Type of interpolation, either 'linear' or 'cubic'. - **window_ms** (Optional): For 'cubic' interpolation, a two-element vector `[left_ms, right_ms]` specifying the fitting window in milliseconds on each side of the blank. Defaults to `[20, 20]`. ### Examples ```matlab % Linear interpolation EEG = tesa_interpdata(EEG, 'linear'); % Cubic interpolation with default window EEG = tesa_interpdata(EEG, 'cubic'); % Cubic with a tighter fitting window (1 ms either side) EEG = tesa_interpdata(EEG, 'cubic', [1, 1]); % Cubic with wider fitting window (50 ms) EEG = tesa_interpdata(EEG, 'cubic', [50, 50]); ``` ``` -------------------------------- ### PCA Dimensionality Reduction with tesa_pcacompress Source: https://context7.com/nigelrogasch/tesa/llms.txt Compresses EEG data to a user-defined number of principal components before running ICA. Displays a variance-explained summary plot by default. The summary plot can be suppressed. ```matlab EEG = tesa_pcacompress(EEG); ``` ```matlab EEG = tesa_pcacompress(EEG, 'compVal', 20); ``` ```matlab EEG = tesa_pcacompress(EEG, 'compVal', 30, 'plot', 'off'); ``` -------------------------------- ### tesa_compselect Source: https://context7.com/nigelrogasch/tesa/llms.txt Applies heuristic rules to classify ICA components as TMS-evoked muscle activity, eye blinks, lateral eye movements, persistent muscle activity, electrode noise, or to keep. Presents each component interactively for manual override. ```APIDOC ## tesa_compselect ### Description Applies heuristic rules to classify ICA components as TMS-evoked muscle activity, eye blinks, lateral eye movements, persistent muscle activity, electrode noise, or to keep. Presents each component interactively (topoplot, time course, power spectrum) for manual override. Classification results are stored in `EEG.icaCompClass`. ### Usage ```matlab % Default: all artifact detectors on, interactive review enabled EEG = tesa_compselect(EEG); % First ICA pass: only remove TMS-evoked muscle components automatically EEG = tesa_compselect(EEG, ... 'tmsMuscle', 'on', 'tmsMuscleThresh', 8, 'tmsMuscleWin', [11, 30], ... 'blink', 'off', ... 'move', 'off', ... 'muscle', 'off', ... 'elecNoise', 'off'); % Second ICA pass: full artifact classification with custom blink electrodes EEG = tesa_compselect(EEG, ... 'figSize', 'medium', ... 'plotTimeX', [-200, 500], ... 'plotFreqX', [1, 100], ... 'tmsMuscle', 'on', 'tmsMuscleThresh', 8, 'tmsMuscleWin', [11, 30], ... 'blink', 'on', 'blinkThresh', 2.5, 'blinkElecs', {'Fp1', 'Fp2'}, ... 'move', 'on', 'moveThresh', 2, 'moveElecs', {'F7', 'F8'}, ... 'muscle', 'on', 'muscleThresh', -0.31, ... 'elecNoise', 'on', 'elecNoiseThresh', 4); % Classify only, do not remove (inspect classifications first) EEG = tesa_compselect(EEG, 'remove', 'off'); ``` ``` -------------------------------- ### Detect TMS Pulses with tesa_findpulsepeak Source: https://context7.com/nigelrogasch/tesa/llms.txt Detects TMS pulses using peak thresholding, suitable for noisy data. Supports dynamic or manual thresholds, polarity selection, and interactive GUI. ```matlab EEG = tesa_findpulsepeak(EEG, 'Cz'); ``` ```matlab EEG = tesa_findpulsepeak(EEG, 'Cz', 'thrshtype', 'median', 'wpeaks', 'pos', 'plots', 'off', 'tmsLabel', 'TMS'); ``` ```matlab EEG = tesa_findpulsepeak(EEG, 'Cz', 'thrshtype', 1000, 'wpeaks', 'neg'); ``` ```matlab EEG = tesa_findpulsepeak(EEG, 'Cz', 'wpeaks', 'gui'); ``` ```matlab EEG = tesa_findpulsepeak(EEG, 'Cz', 'paired', 'yes', 'ISI', [3], 'pairLabel', {'SICI'}); ``` -------------------------------- ### tesa_detrend Source: https://context7.com/nigelrogasch/tesa/llms.txt Removes low-frequency drift by fitting and subtracting a linear, exponential, or double-exponential function from each channel. ```APIDOC ## tesa_detrend ### Description Removes low-frequency drift by fitting and subtracting a linear, exponential, or double-exponential function from each channel. The exponential fit is applied to the trial average and then subtracted from each trial. Requires the MATLAB Curve Fitting Toolbox for exponential modes. ### Usage ```matlab % Linear detrend from 11 to 500 ms EEG = tesa_detrend(EEG, 'linear', [11, 500]); % Single exponential fit (captures capacitor-like discharge) EEG = tesa_detrend(EEG, 'exponential', [11, 500]); % Double exponential (two-component decay) EEG = tesa_detrend(EEG, 'double', [11, 500]); ``` ``` -------------------------------- ### tesa_peakanalysis Source: https://context7.com/nigelrogasch/tesa/llms.txt Detects TEP peaks within user-defined windows for ROI or GMFA waveforms. Supports multi-peak searches and different peak-selection strategies. ```APIDOC ## tesa_peakanalysis ### Description Searches for positive or negative peaks within specified time windows for all ROI or GMFA waveforms stored in the EEG structure. Supports multi-peak searches, two peak-selection strategies (`largest` or `centre`), and a configurable peak definition (number of samples that must be exceeded on either side). Results are stored back in `EEG.ROI` or `EEG.GMFA`. ### Parameters * `EEG` - Input EEG data structure. * `type` - 'ROI' or 'GMFA'. * `polarity` - 'positive' or 'negative'. * `peakTimes` - Target peak times (ms). * `searchWindows` - Time windows (ms) for peak searching, can be a single window or a matrix for multiple peaks. * `method` - (Optional) Peak selection strategy: 'largest' (default) or 'centre'. * `samples` - (Optional) Number of adjacent samples that must be exceeded to define a peak. * `tepName` - (Optional) Name of the TEP to analyze, if multiple ROIs are present. ### Examples ```matlab % Find one negative peak near 100 ms (search 80–120 ms), all ROIs EEG = tesa_peakanalysis(EEG, 'ROI', 'negative', 100, [80, 120]); % Three positive GMFA peaks EEG = tesa_peakanalysis(EEG, 'GMFA', 'positive', ... [30, 60, 180], ... [20, 40; ... 50, 70; ... 170, 190]); % Positive peaks at 25 ms and 70 ms in the named 'motor' ROI % — pick peak closest to centre, define peak as > ±5 adjacent samples EEG = tesa_peakanalysis(EEG, 'ROI', 'positive', [25, 70], ... [15, 35; 60, 80], ... 'method', 'centre', 'samples', 5, 'tepName', 'motor'); ``` ``` -------------------------------- ### tesa_pcacompress Source: https://context7.com/nigelrogasch/tesa/llms.txt Compresses EEG data to a user-defined number of principal components before running ICA, as recommended to stabilise FastICA on TMS-EEG data with large artifacts. ```APIDOC ## tesa_pcacompress — PCA dimensionality reduction before ICA ### Description Compresses EEG data to a user-defined number of principal components before running ICA, as recommended to stabilise FastICA on TMS-EEG data with large artifacts. Displays a variance-explained summary plot by default. ### Method Signature `EEG = tesa_pcacompress(EEG, 'compVal', num_components, 'plot', plot_setting)` ### Parameters - **EEG**: Input EEG data structure. - **'compVal'** (Optional): Specifies the number of principal components to retain. Defaults to 30. - **'plot'** (Optional): Controls whether to display the variance-explained summary plot. Accepts 'on' or 'off'. Defaults to 'on'. ### Examples ```matlab % Default compression to top 30 PCs with variance plot EEG = tesa_pcacompress(EEG); % Compress to top 20 PCs EEG = tesa_pcacompress(EEG, 'compVal', 20); % Suppress the summary plot and compress to top 30 PCs EEG = tesa_pcacompress(EEG, 'compVal', 30, 'plot', 'off'); ``` ``` -------------------------------- ### Detect TMS Pulses with tesa_findpulse Source: https://context7.com/nigelrogasch/tesa/llms.txt Detects TMS pulses using derivative thresholding. Supports single, paired, and repetitive pulse paradigms. Configure refractory periods, rates, and labels. ```matlab EEG = tesa_findpulse(EEG, 'Cz'); ``` ```matlab EEG = tesa_findpulse(EEG, 'Fz', 'refract', 4, 'rate', 2e5, 'tmsLabel', 'single', 'plots', 'off'); ``` ```matlab EEG = tesa_findpulse(EEG, 'Cz', 'paired', 'yes', 'ISI', [100], 'pairLabel', {'LICI'}); ``` ```matlab EEG = tesa_findpulse(EEG, 'Cz', 'paired', 'yes', 'ISI', [3, 100], 'pairLabel', {'SICI', 'LICI'}); ``` ```matlab EEG = tesa_findpulse(EEG, 'Cz', 'repetitive', 'yes', 'ITI', 26000, 'pulseNum', 40); ``` -------------------------------- ### Detect TEP peaks using tesa_peakanalysis Source: https://context7.com/nigelrogasch/tesa/llms.txt Searches for positive or negative peaks within specified time windows for ROI or GMFA waveforms. Supports multi-peak searches and configurable peak definition. Results are stored back in EEG.ROI or EEG.GMFA. ```matlab EEG = tesa_peakanalysis(EEG, 'ROI', 'negative', 100, [80, 120]); ``` ```matlab EEG = tesa_peakanalysis(EEG, 'GMFA', 'positive', ... [30, 60, 180], ... [20, 40; ... 50, 70; ... 170, 190]); ``` ```matlab EEG = tesa_peakanalysis(EEG, 'ROI', 'positive', [25, 70], ... [15, 35; 60, 80], ... 'method', 'centre', 'samples', 5, 'tepName', 'motor'); ``` -------------------------------- ### tesa_removedata Source: https://context7.com/nigelrogasch/tesa/llms.txt Blanks TMS artifact window with zeros or baseline average. This function replaces data in a defined time window around each event with zeros or the mean of a specified baseline period. ```APIDOC ## tesa_removedata — Blank TMS artifact window with zeros or baseline average ### Description Replaces data in a defined time window around each event with zeros or the mean of a specified baseline period. Works on both continuous and epoched data. The cut parameters are stored in `EEG.tmscut` for use by `tesa_interpdata`. ### Method MATLAB function call ### Parameters - **EEG** (struct) - The EEGLAB EEG structure. - **window** (vector of two doubles) - The time window in ms around each event to blank. Format: `[startTime, endTime]`. - **baselineWindow** (vector of two doubles) - Optional. The time window in ms used to calculate the baseline average. Format: `[startTime, endTime]`. If empty, zeros are used. - **eventTypes** (cell array of strings) - Optional. A cell array of event type strings to apply the blanking to. If empty, all events are processed. ### Request Example ```matlab % Replace -10 to 10 ms around every event with zeros EEG = tesa_removedata(EEG, [-10, 10]); % Replace with average of baseline (-500 to -100 ms), only for 'TMS' events EEG = tesa_removedata(EEG, [-10, 10], [-500, -100], {'TMS'}); % Replace with zeros around a specific event type only EEG = tesa_removedata(EEG, [-2, 10], [], {'TMS'}); % Second pass to extend the blank window after ICA (common pipeline step) EEG = tesa_removedata(EEG, [-2, 15]); % Output: "TMS artifact data between -2 ms and 15 ms replaced with 0" ``` ``` -------------------------------- ### Suppress Artifacts with tesa_sspsir Source: https://context7.com/nigelrogasch/tesa/llms.txt Implements SSP-SIR to suppress TMS-evoked muscle artifacts or sensory responses. Operates in the signal subspace and can use a custom lead-field matrix. Use 'artScale', 'control' to remove sensory responses. ```matlab EEG = tesa_sspsir(EEG); ``` ```matlab EEG = tesa_sspsir(EEG, 'artScale', 'manual', 'timeRange', [5, 50], 'PC', 4); ``` ```matlab EEG = tesa_sspsir(EEG, 'artScale', 'manualConstant', 'timeRange', [0, 50], 'PC', 3); ``` ```matlab EEG = tesa_sspsir(EEG, 'artScale', 'control', ... 'EEG_control', ['/data/controlResponse.set'], 'PC', {'data', [90]}); ``` ```matlab EEG = tesa_sspsir(EEG, 'artScale', 'manual', ... 'timeRange', [5, 50], 'PC', {'data', [90]}); ``` -------------------------------- ### tesa_filtmedian Source: https://context7.com/nigelrogasch/tesa/llms.txt Applies a 1-D median filter within a specified time window around a given event label. Useful for removing sharp spike artifacts. ```APIDOC ## tesa_filtmedian — Median filter for spike artifact removal ### Description Applies a 1-D median filter within a specified time window around a given event label. Useful for removing sharp spike artifacts (e.g., electrode pops) that appear as isolated single-sample transients. ### Method Signature `EEG = tesa_filtmedian(EEG, time_window_ms, order, event_label)` ### Parameters - **EEG**: Input EEG data structure. - **time_window_ms**: A two-element vector `[start_ms, end_ms]` specifying the time window around the event label in milliseconds. - **order**: The order of the median filter. - **event_label**: A string specifying the type of event to target (e.g., 'spike', 'TMS'). ### Examples ```matlab % 3rd-order median filter ±2 ms around spike events EEG = tesa_filtmedian(EEG, [-2, 2], 3, 'spike'); % Higher-order filter for broader spike artifacts around TMS events EEG = tesa_filtmedian(EEG, [-5, 5], 10, 'TMS'); % Targeting specific manually labelled artifact events EEG = tesa_filtmedian(EEG, [-1, 1], 3, 'spike'); ``` ``` -------------------------------- ### tesa_sspsir Source: https://context7.com/nigelrogasch/tesa/llms.txt Implements the Signal Space Projection followed by Source-Informed Reconstruction (SSP-SIR) method to suppress TMS-evoked muscle artifacts or sensory (control) responses. ```APIDOC ## tesa_sspsir ### Description Implements the Signal Space Projection followed by Source-Informed Reconstruction (SSP-SIR) method to suppress TMS-evoked muscle artifacts or sensory (control) responses. Operates in the signal subspace and can use a custom lead-field matrix for physiologically informed reconstruction. ### Usage ```matlab % Default: automatic artifact scaling, interactive PC selection EEG = tesa_sspsir(EEG); % Manual window: estimate and remove muscle artifacts from 5–50 ms EEG = tesa_sspsir(EEG, 'artScale', 'manual', 'timeRange', [5, 50], 'PC', 4); % Constant projection: estimate from [0, 50] ms, project across all time EEG = tesa_sspsir(EEG, 'artScale', 'manualConstant', 'timeRange', [0, 50], 'PC', 3); % Remove control (sensory) response using a control dataset EEG = tesa_sspsir(EEG, 'artScale', 'control', ... 'EEG_control', ['/data/controlResponse.set'], 'PC', {'data', [90]}); % Remove PCs explaining >90% of variance in the artifact window EEG = tesa_sspsir(EEG, 'artScale', 'manual', ... 'timeRange', [5, 50], 'PC', {'data', [90]}); ``` ``` -------------------------------- ### tesa_tepextract Source: https://context7.com/nigelrogasch/tesa/llms.txt Extracts TMS-evoked potentials (TEP) by ROI or GMFA. Averages cleaned, epoched data to generate TEP waveforms. Supports region-of-interest (ROI) averaging across selected electrodes and global mean field amplitude (GMFA). Handles paired-pulse correction. ```APIDOC ## tesa_tepextract ### Description Averages cleaned, epoched data to generate TEP waveforms. Supports region-of-interest (ROI) averaging across selected electrodes and global mean field amplitude (GMFA, i.e., SD across all electrodes at each time point). Handles paired-pulse correction by subtracting a single-pulse reference TEP. Results are stored in `EEG.ROI` or `EEG.GMFA`. ### Parameters * `EEG` - Input EEG data structure. * `type` - 'ROI' or 'GMFA'. * `elecs` - (Optional, for 'ROI' type) Electrode labels for averaging. * `tepName` - (Optional) Name for the TEP, useful for downstream analysis. * `pairCorrect` - (Optional) 'on' to enable paired-pulse correction. * `ISI` - (Optional, for paired-pulse correction) Inter-stimulus interval in ms. * `fileName` - (Optional, for paired-pulse correction) File name of the single-pulse reference TEP. ### Examples ```matlab % Standard ROI: average over left motor cortex electrodes EEG = tesa_tepextract(EEG, 'ROI', 'elecs', {'FC1', 'FC3', 'C1', 'C3'}); % Named ROI for easier reference in downstream analysis EEG = tesa_tepextract(EEG, 'ROI', 'elecs', {'C1', 'C3'}, 'tepName', 'motor'); % Global mean field amplitude EEG = tesa_tepextract(EEG, 'GMFA'); % Paired-pulse correction: subtract conditioning-pulse TEP shifted by 100 ms EEG = tesa_tepextract(EEG, 'ROI', 'elecs', 'C3', ... 'pairCorrect', 'on', 'ISI', 100, ... 'fileName', 'C:\tmseeg\single_pulse_TEP.set'); ``` ``` -------------------------------- ### tesa_findpulsepeak Source: https://context7.com/nigelrogasch/tesa/llms.txt Detects TMS pulses via peak threshold, compatible with GUI. This function identifies peaks in a single-channel time series above a dynamically or manually set threshold and supports positive/negative peak polarity selection. ```APIDOC ## tesa_findpulsepeak — Detect TMS pulses via peak threshold (GUI-compatible) ### Description An alternative pulse detector that identifies peaks in a single-channel time series above a dynamically or manually set threshold. Supports positive/negative peak polarity selection and an interactive GUI for manual peak inclusion. Useful when the derivative-based `tesa_findpulse` is insufficient (e.g., noisy data with gradual artifact rise). ### Method MATLAB function call ### Parameters - **EEG** (struct) - The EEGLAB EEG structure. - **channel** (string) - The channel to analyze for pulse peaks (e.g., 'Cz'). - **'thrshtype'** (string or double) - Optional. Threshold type: 'median' for median-based dynamic threshold, 'mean' for mean-based, or a specific double value for a user-defined threshold. - **'wpeaks'** (string) - Optional. Polarity of peaks to detect: 'pos' for positive, 'neg' for negative, or 'gui' for interactive GUI selection. - **'plots'** (string) - Optional. Controls plotting ('on' or 'off'). - **'tmsLabel'** (string) - Optional. Label for detected TMS pulses. - **'paired'** (string) - Optional. Set to 'yes' to detect paired pulses. - **'ISI'** (vector of doubles) - Optional. Inter-stimulus interval in ms for paired pulses. - **'pairLabel'** (cell array of strings) - Optional. Label for the paired pulse condition. ### Request Example ```matlab % Default: dynamic threshold, positive peaks on Cz EEG = tesa_findpulsepeak(EEG, 'Cz'); % Median threshold, suppress plot, custom label EEG = tesa_findpulsepeak(EEG, 'Cz', 'thrshtype', 'median', ... 'wpeaks', 'pos', 'plots', 'off', 'tmsLabel', 'TMS'); % User-defined threshold of 1000 uV, use negative peaks EEG = tesa_findpulsepeak(EEG, 'Cz', 'thrshtype', 1000, 'wpeaks', 'neg'); % Interactive GUI selection (click and drag to box desired peaks) EEG = tesa_findpulsepeak(EEG, 'Cz', 'wpeaks', 'gui'); % Paired pulse with ISI = 3 ms (SICI) EEG = tesa_findpulsepeak(EEG, 'Cz', 'paired', 'yes', ... 'ISI', [3], 'pairLabel', {'SICI'}); ``` ``` -------------------------------- ### tesa_filtbutter Source: https://context7.com/nigelrogasch/tesa/llms.txt Applies a forward–backward (zero-phase) Butterworth filter of user-defined order. Supports bandpass, bandstop, highpass, and lowpass configurations. ```APIDOC ## tesa_filtbutter — Zero-phase Butterworth filter ### Description Applies a forward–backward (zero-phase) Butterworth filter of user-defined order. Supports bandpass, bandstop, highpass, and lowpass configurations. Uses MATLAB's `butter` and `filtfilt` functions and processes all channels across concatenated trials to minimise edge artifacts. ### Method Signature `EEG = tesa_filtbutter(EEG, low_freq, high_freq, order, filter_type)` ### Parameters - **EEG**: Input EEG data structure. - **low_freq**: Lower cutoff frequency in Hz. Use `[]` for highpass or lowpass filters. - **high_freq**: Upper cutoff frequency in Hz. Use `[]` for highpass or lowpass filters. - **order**: The order of the Butterworth filter. - **filter_type**: Type of filter: 'bandpass', 'bandstop', 'highpass', or 'lowpass'. ### Examples ```matlab % 4th-order bandpass 1–100 Hz EEG = tesa_filtbutter(EEG, 1, 100, 4, 'bandpass'); % 4th-order bandstop (notch) 48–52 Hz EEG = tesa_filtbutter(EEG, 48, 52, 4, 'bandstop'); % 4th-order high-pass above 1 Hz EEG = tesa_filtbutter(EEG, 1, [], 4, 'highpass'); % 4th-order low-pass below 45 Hz EEG = tesa_filtbutter(EEG, [], 45, 4, 'lowpass'); ``` ```