MATLAB Documentation

esnr(chanSignal, chanNoise)

esnr - Calculate the Evoke Signal-to-Noise Ratio (eSNR) between a channel signal and channel noise.

Syntax: evokeSnr = esnr(chanSignal, chanNoise)

Inputs:

chanSignal - Matrix of channel signal samples (rows represent observations, columns represent features) chanNoise - Matrix of channel noise samples (rows represent observations, columns represent features)

Output:

evokeSnr - Scalar value representing the eSNR in decibels (dB)

Example:

chanSignal = [1 2 3; 4 5 6; 7 8 9]; chanNoise = [0.5 1 1.5; 2 2.5 3; 3.5 4 4.5]; evokeSnr = esnr(chanSignal, chanNoise);

cov1para(x, shrink)

function sigma=cov1para(x) x (t*n): t iid observations on n random variables sigma (n*n): invertible covariance matrix estimator

Shrinks towards one-parameter matrix:

all variances are the same all covariances are zero

if shrink is specified, then this value is used for shrinkage

factoranupdate(X, m, varargin)

FACTORAN Maximum Likelihood Common Factor Analysis. LAMBDA = FACTORAN(X, M) returns maximum likelihood estimates of the factor loadings, LAMBDA, in a common factor analysis model with M factors. Rows of the N-by-D data matrix X correspond to observations, columns correspond to variables. The (i,j)th element of the D-by-M factor loadings matrix LAMBDA is the estimated coefficient, or loading, of the jth factor for the ith variable. By default, FACTORAN rotates LAMBDA using the varimax criterion (see below).

[LAMBDA, PSI] = FACTORAN(X, M) returns maximum likelihood estimates of the specific variances in the D-by-1 vector PSI.

[LAMBDA, PSI, T] = FACTORAN(X, M) returns the M-by-M rotation matrix T used to rotate LAMBDA.

[LAMBDA, PSI, T, STATS] = FACTORAN(X, M) returns a structure containing information relating to the null hypothesis that the number of common factors is M. STATS contains the fields

loglike - the maximized log-likelihood value

dfe - the error degrees of freedom, ((D-M)^2 - (D+M))/2

chisq - the approximate chi-squared statistic for the null hypothesis

p - the right-tail significance level for the null hypothesis

FACTORAN does not return STATS.chisq and STATS.p unless STATS.dfe is positive and all the specific variance estimates in PSI are positive. FACTORAN does not return STATS.chisq and STATS.p if X is a covariance matrix, unless you use the optional ‘Nobs’ parameter (see below).

[LAMBDA, PSI, T, STATS, F] = FACTORAN(X, M) returns predictions of the common factors, also known as factor scores, in the N-by-M matrix F. Rows of F correspond to predictions, columns correspond to factors. FACTORAN cannot compute F if X is a covariance matrix. FACTORAN rotates F using the same criterion as for LAMBDA.

[ … ] = FACTORAN(…, ‘PARAM1’,val1, ‘PARAM2’,val2, …) allows you to specify optional parameter name/value pairs to define the inputs, control the numerical optimization used to fit the model, and specify details of the outputs. Parameters are:

‘Xtype’ - Type of input in X [ {‘data’} | ‘covariance’ ] ‘Start’ - Method to select the starting point(s) for PSI in the

optimization. Choices are:
‘random’ - Choose D independent Uniform(0,1)

values

{‘Rsquared’} - Choose starting vector as a scale

factor times DIAG(INV(CORRCOEF(X)))

positive integer - The number of optimizations to

perform, each initialized as with ‘random’

matrix - A D-by-R matrix of explicit starting

points. Each column is one starting vector, and FACTORAN performs R optimizations.

‘Delta’ - Lower bound for the PSI during the maximum likelihood

optimization [ 0 <= positive scalar < 1 | {0.005} ]

‘OptimOpts’ - Options for the maximum likelihood optimization,

as created by STATSET. See STATSET(‘factoran’) for parameter names and default values.

‘Nobs’ - Number of observations that went into estimating

X, when X is a covariance matrix [ positive integer ]

‘Scores’ - Method to be used for predicting F

[ {‘wls’} | ‘Bartlett’ | ‘regression’ | ‘Thomson’ ]

‘Rotate’ - Method to use to rotate factor loadings and scores

[ ‘none’ | {‘varimax’} | ‘quartimax’ | ‘equamax’ | ‘parsimax’ | ‘orthomax’ | ‘promax’ | ‘procrustes’ | ‘pattern’ | function ]

If ‘Rotate’ is one of the above strings recognized by ROTATEFACTORS as a valid value of its ‘method’ parameter, then you may also specify any of the other parameter name/value pairs accepted by ROTATEFACTORS.

A rotation function can be specified using @, for example @ROTATEFUN, and must be of the form

function [B, T] = ROTATEFUN(A, P1, P2, …),

taking as arguments a D-by-M matrix A of unrotated loadings, plus zero or more additional problem-dependent arguments P1, P2, …, and returning a D-by-M matrix B of rotated loadings and the corresponding D-by-D rotation matrix T.

[ … ] = FACTORAN(…, ‘Rotate’, ROTATEFUN, ‘UserArgs’, P1, P2, …) passes the arguments P1, P2, … directly to the function ROTATEFUN.

Examples:

load carbig; X = [Acceleration Displacement Horsepower MPG Weight]; X = X(all(~isnan(X),2),:); [Lambda, Psi, T, stats, F] = factoran(X, 2, ‘scores’, ‘regr’)

% Same estimates, but computed from an estimated covariance matrix [Lambda, Psi, T] = factoran(cov(X), 2, ‘Xtype’, ‘cov’)

% Use promax rotation [Lambda, Psi, T] = factoran(X, 2, ‘rotate’,’promax’, ‘power’,2)

% Passing args to a rotation function [Lambda Psi T] = …

factoran(X, 2, ‘rotate’, @myrotation, ‘userargs’, 1, ‘two’)

See also BIPLOT, OPTIMSET, PROCRUSTES, PCA, PCACOV, ROTATEFACTORS.

chi2pval(x, v)

FPVAL Chi-square distribution p-value function. P = CHI2PVAL(X,V) returns the upper tail of the chi-square cumulative distribution function with V degrees of freedom at the values in X. If X is the observed value of a chi-square test statistic, then P is its p-value.

The size of P is the common size of the input arguments. A scalar input functions as a constant matrix of the same size as the other inputs.

See also CHI2CDF, CHI2INV.

mahalUpdate(noise, signal, sigma)

mahalUpdate - Calculate Mahalanobis distance between signal and noise.

Syntax: dist = mahalUpdate(noise, signal, sigma)

Inputs:

noise - Matrix of noise samples (rows represent trials, columns represent features) signal - Matrix of signal samples (rows represent trials, columns represent features) sigma - Covariance matrix (assumed to be positive definite)

Output:

dist - Row vector of Mahalanobis distances for each trial

Example:

noise = [1 2; 3 4; 5 6]; signal = [2 3; 4 5; 6 7]; sigma = [1 0.5; 0.5 1]; dist = mahalUpdate(noise, signal, sigma);

covCor(x, shrink)

x (t*n): t iid observations on n random variables sigma (n*n): invertible covariance matrix estimator

Shrinks towards constant correlation matrix if shrink is specified, then this constant is used for shrinkage

extractHGDataWithROI(Subject, options)

extractHGDataWithROI - Extracts high-gamma (HG) band data with region of interest (ROI) selection

Usage:

ieegHGAll = extractHGDataWithROI(Subject, options)

Inputs:
  • Subject: struct subject output of populated task

  • options: struct, optional (default values in brackets) - Epoch: string [‘ResponseStart’]

    Epoch information; e.g., ‘Auditory’, ‘Go’, ‘ResponseStart’

    • Time: double array (1x2) [-1 1] Epoch time window

    • roi: string [‘’] Anatomical extraction; e.g., ‘precentral’, ‘superiortemporal’

    • normFactor: [] Normalization factors for HG power normalization

    • normType: integer [1] Normalization type: 1 - z-score, 2 - mean normalization

    • fDown: double [200] Down-sampling frequency

    • baseTimeRange: double array (1x2) [-0.5 0] Time range for baseline extraction

    • baseName: string [‘Start’] Epoch name for baseline extraction

    • respTimeThresh: double [-1] Response time threshold to remove trials with faster responses

    • subsetElec: cell [‘’] Subset of electrodes to select from statistics

    • remNoiseTrials: logical [true] Remove all noisy trials

    • remNoResponseTrials: logical [true] Remove all no-response trials

    • remWMchannels: logical [true] Remove white matter channels

Outputs:
  • ieegHGAll: struct array Extracted high-gamma data for each subject - ieegHGNorm: struct

    Normalized HG band data

    • channelName: cell Channel names for selected channels

    • normFactor: double array Normalization factors for each channel

    • trialInfo: struct Information about selected trials

class ieegStructMicro

The ieegStructMicro is a subclass of ieegStructClass specialized for micro-scale iEEG data. It extends the functionality of ieegStructClass by adding additional methods for spatial smoothing and spatial averaging specific to micro-scale data.

Constructor Summary
ieegStructMicro(data, fs, tw, fBand, name, chanMap)

Class constructor

Property Summary
chanMap

Channel map for micro-scale iEEG data

Method Summary
extractHiGammaNorm(obj1, obj2, fDown, gtw1, gtw2)

Extract normalized high-gamma from micro-scale iEEG data

spatialAverage(window, isOverlap)

Spatial averaging of micro-scale iEEG data

spatialSmoothMicro(window)

Spatial smoothing of micro-scale iEEG data

class phonemeDecoderClass
Constructor Summary
phonemeDecoderClass(numFold, varExplained)
Property Summary
numFold
varExplained
Method Summary
baseClassify(ieegStruct, phonemeStruct, name, d_time_window, sigChannel, isauc)
baseRegress(ieegStruct, phonemeStruct, name, d_time_window, sigChannel, rTrials)
indChanClassify(ieegStruct, phonemeStruct, name, d_time_window)
tempGenClassify(ieegStruct, phonemeStruct, name, timeRes, timeWin, sigChannel)
tempGenRegress1D(ieegStruct, phonemeStruct, name, timeRes, timeWin, sigChannel, rTrials)
tempGenRegress2D(ieegStruct, phonemeStruct, name, timeRes, timeWin, sigChannel, rTrials)
tsneDecompose(ieegStruct, phonemeStruct, name, d_time_window, nElec, nIter)
class phonemeSequenceTrialParser

The phonemeSequenceTrialParser class parses phoneme sequence trial information.

Constructor Summary
phonemeSequenceTrialParser(trialInfo)

Class constructor

Property Summary
phonemeClass

low, high, labial, dorsal)

Type:

Phoneme class (1 - 4

phonemeUnit

a, ae, i, u, b, p, v, g, k)

Type:

Phoneme unit (1 - 9

phonoTactic

Phonotactic probabilities

syllableUnit

Syllable unit (1 - Consonant, 2 - Vowel)

tokenIdentity

TrialInfo trigger

tokenName

Token names

extractRawDataWithROI(Subject, options)

Extracts raw data based on specified options for each subject in the Subject structure and returns the extracted data in the ieegStructAll structure.

Arguments:
Subject: struct

Subject structure containing data for each subject

options: struct (optional)

Optional arguments for data extraction - Epoch: string (default: ‘Start’)

Epoch information; e.g., ‘Auditory’, ‘Go’, ‘ResponseStart’

  • Time: double array (default: [-1 1])

    Epoch time window

  • roi: string (default: ‘’)

    Anatomical extraction; e.g., {‘precentral’, ‘superiortemporal’}

  • subsetElec: cell (default: ‘’)

    Subset of electrodes to select from stats

  • isCAR: logical (default: true)

    True to perform common average referencing (CAR)

  • remNoiseTrials: logical (default: true)

    True to remove all noisy trials

  • remNoResponseTrials: logical (default: true)

    True to remove all no-response trials

  • remFastResponseTimeTrials: double (default: -1)

    Response time threshold to remove faster response trials

  • remWMchannels: logical (default: true)

    True to remove white matter channels

Returns:
ieegStructAll: struct

Extracted raw data for each subject

poolChannelWithMinTrial(ieegHGStruct, trialInfoStruct)

Combines channels with minimum trials for a specific token across subjects.

Arguments: - ieegHGStruct: Array of structures containing ephys data for each subject. - trialInfoStruct: Array of structures containing trial information for each subject.

Returns: - ieegStructAll: Combined ephys data structure with pooled channels. - phonemeTrialAll: Combined trial information for all tokens. - channelNameAll: Cell array of channel names from all subjects.

extractBandPassDataWithROI(Subject, options)

Extracts band-pass filtered data with specified region of interest (ROI) and other optional parameters.

Arguments:
Subject: struct

Subject output of populated task

options: struct (optional)

Optional arguments for extraction - Epoch: string (default: ‘ResponseStart’)

Epoch information; e.g., ‘Auditory’, ‘Go’, ‘ResponseStart’

  • Time: (1x2) double array (default: [-1 1])

    Epoch time window

  • roi: string (default: ‘’)

    Anatomical extraction; e.g., ‘precentral’, ‘superiortemporal’

  • fBand: double array (default: [15 30])

    Frequency band for band-pass filtering

  • fDown: double (default: 200)

    Downsampling frequency

  • respTimeThresh: double (default: -1)

    Threshold for removing trials with fast response times

  • subsetElec: cell (default: ‘’)

    Subset of electrodes to select from stats

  • remNoiseTrials: logical (default: true)

    True to remove all noisy trials

  • remNoResponseTrials: logical (default: true)

    True to remove all no-response trials

  • remWMchannels: logical (default: true)

    True to remove working memory channels

Returns:
ieegBandPass: struct

Band-pass filtered data with extracted features

extractTrialInfo(Subject, options)

Extracts trial information based on specified options for each subject in the Subject structure. Returns the trial information in two outputs: trialInfos and trialInfoStruct.

Arguments:
Subject: struct

Subject structure containing data for each subject

options: struct (optional)

Optional arguments for trial information extraction - remNoiseTrials: logical (default: true)

True to remove all noisy trials

  • remNoResponseTrials: logical (default: true)

    True to remove all no-response trials

  • remFastResponseTimeTrials: double (default: -1)

    Threshold to remove trials with negative response time

Returns:
trialInfos: cell array

Extracted trial information for each subject

trialInfoStruct: struct

Structured trial information for each subject

class decoderClass

Class for decoder operations

Constructor Summary
decoderClass(numFold, varExplained, nIter)

Class constructor Creates an instance of the decoderClass

numFold: Number of folds for cross-validation varExplained: Variance explained threshold nIter: Number of iterations

Property Summary
nIter

Number of iterations

numFold

Number of folds for cross-validation

varExplained

Variance explained threshold

Method Summary
baseClassify(ieegStruct, decoderUnit, options)

Performs base classification obj: decoderClass object ieegStruct: ieegStructClass object decoderUnit: Decoder labels options: Optional arguments for classification

options.d_time_window: Decoder time window (defaults to epoch time-window) options.selectChannel: Select number of electrodes for analysis (defaults to all) options.selectTrial: Select number of trials for analysis (defaults to all) options.isAuc: Select for AUC metric (defaults to 0)

Returns decodeResultStruct with classification results

baseRegress(ieegStruct, decoderUnit, d_time_window, selectChannel, selectTrial)

Performs base regression obj: decoderClass object ieegStruct: ieegStructClass object decoderUnit: Decoder labels d_time_window: Decoder time window (defaults to epoch time-window) selectChannel: Select number of electrodes for analysis (defaults to all) selectTrial: Select number of trials for analysis (defaults to all) Returns decodeResultStruct with regression results

tempGenClassify1D(ieegStruct, decoderUnit, options)

Generates temporal classification results obj: decoderClass object ieegStruct: ieegStructClass object decoderUnit: Decoder labels options.timeRes: Decoder time resolution (defaults to 0.02) options.timeWin: Time window size for analysis options.selectChannels: Select number of electrodes for analysis (defaults to all) options.selectTrials: Select number of trials for analysis (defaults to all) Returns decodeTimeStruct with temporal classification results

tempGenClassify2D(ieegStruct, decoderUnit, options)

Generates 2D temporal classification results obj: decoderClass object ieegStruct: ieegStructClass object decoderUnit: Decoder labels options.timeRes: Decoder time resolution (defaults to 0.02) options.timeWin: Time window size for analysis (defaults to 0.2) options.selectChannels: Select number of electrodes for analysis (defaults to all) options.selectTrials: Select number of trials for analysis (defaults to all) Returns decodeTimeStruct with 2D temporal classification results

tempGenRegress1D(ieegStruct, decoderUnit, options)

Generates 1D temporal regression results obj: decoderClass object ieegStruct: ieegStructClass object decoderUnit: Decoder labels options.timeRes: Decoder time resolution (defaults to 0.02) options.timeWin: Time window size for analysis (defaults to 0.2) options.selectChannels: Select number of electrodes for analysis (defaults to all) options.selectTrials: Select number of trials for analysis (defaults to all) Returns decodeTimeStruct with 1D temporal regression results

tempGenRegress2D(ieegStruct, decoderUnit, options)
tsneDecompose(ieegStruct, decoderUnit, chanMap, d_time_window, nElec, nIter)

Performs t-SNE decomposition ieegStruct: iEEG class object decoderUnit: Decoder labels chanMap: 2D channel map d_time_window: Decoder time window nElec: Number of electrodes for analysis nIter: Number of iterations for t-SNE Returns decompStruct with t-SNE scores and ratios

poolChannelWithMaxTrial(ieegHGStruct, trialInfoStruct)

Combines channels with maximum trials for a specific token across subjects.

Arguments: - ieegHGStruct: Array of structures containing ephys data for each subject. - trialInfoStruct: Array of structures containing trial information for each subject.

Returns: - ieegStructAll: Combined ephys data structure with pooled channels. - phonemeTrialAll: Combined trial information for all tokens. - channelNameAll: Cell array of channel names from all subjects.

class ieegStructClass

The ieegStructClass is a class for handling iEEG data with various operations. It provides methods for common average referencing, band-pass filtering, high-gamma extraction, normalization, permutation cluster analysis, and more.

Constructor Summary
ieegStructClass(data, fs, tw, fBand, name)

Class constructor

Property Summary
data

channels x trials x timepoints

fBand

frequency window

fs

sampling frequency

name

Epoch name

tw

time-epoch

Method Summary
extractBandPassFilter(fBand, fDown, gtw)

Extract band-pass filtered signal

extractCar(badChannels)

Common average referencing Extracts CAR-filtered data by subtracting the common average across channels

extractHGnormFactor()

Extract normalization factors for ieeg (mean & standard deviation)

extractHiGamma(fDown, gtw, normFactor, normType)

Extract high-gamma signal

extractHiGammaNorm(obj1, obj2, fDown, gtw1, gtw2)

Extract normalized high-gamma

extractTimePermCluster(obj1, obj2)

Time Series permutation cluster

normHiGamma(obj1, normFactor, normType)

Normalize high-gamma

correctTriggerOnsetExtractor(trigOns, timitPath, audioPathUsed, micSplit, fsMic)

correctTriggerOnsetExtractor - Correct trigger onset extraction using audio alignment.

Syntax: [trigOnsUpdate, micSplitNew] = correctTriggerOnsetExtractor(trigOns, timitPath, audioPathUsed, micSplit, fsMic)

Inputs:

trigOns - Extracted trigger onsets (1 x #triggers) in seconds timitPath - File path to TIMIT database audioPathUsed - Cell matrix {1 x #triggers} - File path to individual trials micSplit - Microphone split signals (matrix with size #triggers x samples) fsMic - Sampling frequency of the microphone split signals

Outputs:

trigOnsUpdate - Updated trigger onsets after correction micSplitNew - Corrected microphone split signals after alignment

Example:

trigOns = [0.5, 1.2, 2.8]; timitPath = ‘path/to/timit’; audioPathUsed = {‘trial1.wav’, ‘trial2.wav’, ‘trial3.wav’}; micSplit = [mic1; mic2; mic3]; % matrix of microphone split signals fsMic = 44100; [trigOnsUpdate, micSplitNew] = correctTriggerOnsetExtractor(trigOns, timitPath, audioPathUsed, micSplit, fsMic);

timitAudioExtract(timitPath, audioPathUsed, tw, fsMic)

timitAudioExtract - Extracts audio data from TIMIT dataset and splits it into specified time windows.

Syntax: [micSplitNew, micSplitCell] = timitAudioExtract(timitPath, audioPathUsed, tw, fsMic)

Inputs:

timitPath - Path to the TIMIT dataset audioPathUsed - Cell array of audio file paths within the TIMIT dataset tw - Time window for each audio segment (in seconds) fsMic - Sampling frequency of the microphone (in Hz)

Outputs:

micSplitNew - Extracted and split audio data (Trials x Samples) micSplitCell - Cell array of the extracted audio data for each segment

Example:

timitPath = ‘C:TIMIT'; % Example path to the TIMIT dataset audioPathUsed = {‘DR1FAKS0SA1.WAV’, ‘DR2FCJF0SA2.WAV’}; % Example audio file paths tw = [-0.5 1.5]; % Example time window of -0.5 to 1.5 seconds for each segment fsMic = 20000; % Example sampling frequency of the microphone [micSplitNew, micSplitCell] = timitAudioExtract(timitPath, audioPathUsed, tw, fsMic); % Extract and split the audio data

dataProcessorStrfNoLag(WMel, SMellog, ieeg)

dataProcessorStrfNoLag - Process data for STRF analysis without time lag.

Syntax: [XMatrix, YMatrix, XMatCell, YMatCell, YMatChanCell] = dataProcessorStrfNoLag(WMel, SMellog, ieeg)

Inputs:

WMel - Modulation spectrogram matrix (trial x frequency x time) SMellog - Log-scale spectrogram matrix (trial x frequency x time) ieeg - Intracranial EEG data (channels x trial x time)

Outputs:

XMatrix - Input matrix for STRF analysis (samples x frequency) YMatrix - Output matrix for STRF analysis (samples x channels) XMatCell - Cell array of input matrices for each trial (1 x #trials) YMatCell - Cell array of output matrices for each trial (1 x #trials) YMatChanCell- Cell array of output matrices for each channel within each trial (#trials x #channels)

splitIeeg(ieeg, trigOnset, tw, fs)

splitIeeg - Splits the iEEG data into individual trials based on trigger onsets.

Syntax: ieegSplit = splitIeeg(ieeg, trigOnset, tw, fs)

Inputs:

ieeg - iEEG data (Channels x Samples) trigOnset - Trigger onsets indicating the start of each trial (in seconds) tw - Time window for each trial (in seconds) fs - Sampling frequency (in Hz)

Outputs:

ieegSplit - Split iEEG data into individual trials (Channels x Trials x Samples)

spatialSmooth(ieeg, chanMap, window)

spatialSmooth - Applies spatial smoothing to the iEEG data based on a channel map.

Syntax: ieegSpaceSmooth = spatialSmooth(ieeg, chanMap, window)

Inputs:

ieeg - iEEG data (Channels x Trials x Samples) chanMap - Channel map indicating the spatial arrangement of channels window - Window size for spatial smoothing (e.g., [3 3] for a 3x3 window)

Outputs:

ieegSpaceSmooth - Spatially smoothed iEEG data

stereoChanLabelExtract(labels)
extractTriggerOnset(trigger, fs)

extractTriggerOnset - Extracts trigger onset locations from a signal.

Syntax: locs = extractTriggerOnset(trigger, fs)

Inputs:

trigger - Signal containing the trigger information fs - Sampling frequency of the trigger signal (in Hz)

Output:

locs - Array of trigger onset locations (in seconds)

timitPhonemeTimeExtractor(audioPathUsed, micAudio, ieeg, etw, pSpan)

timitPhonemeTimeExtractor - Extracts phoneme-related features and time windows from the TIMIT dataset.

Syntax: [phonMet, ieegAll, pLabel] = timitPhonemeTimeExtractor(audioPathUsed, micAudio, ieeg, etw, pSpan)

Inputs:

audioPathUsed - Cell array of audio file paths within the TIMIT dataset micAudio - Microphone audio data (Channels x Samples) ieeg - Intracranial EEG data (Channels x Trials x Samples) etw - Time window for the EEG data (in seconds) pSpan - Time span around each phoneme for feature extraction (in seconds)

Outputs:

phonMet - Structure containing phoneme-related features and time windows ieegAll - Concatenated gamma band EEG data across all phonemes (Channels x Trials x Samples) pLabel - Cell array of phoneme labels

Example:

audioPathUsed = {‘DR1FAKS0SA1.WAV’, ‘DR2FCJF0SA2.WAV’}; % Example audio file paths micAudio = randn(2, 1000); % Example microphone audio data ieeg = randn(16, 10, 1000); % Example intracranial EEG data etw = [0.5 1.5]; % Example time window for EEG data pSpan = [0.1 0.3]; % Example time span around each phoneme for feature extraction [phonMet, ieegAll, pLabel] = timitPhonemeTimeExtractor(audioPathUsed, micAudio, ieeg, etw, pSpan); % Extract phoneme-related features

extractCommonTrials(goodTrials)

extractCommonTrials - Extracts the common trials from multiple sets of good trials.

Syntax: goodTrialsCommon = extractCommonTrials(goodTrials)

Inputs:

goodTrials - Cell array containing multiple sets of good trials

Output:

goodTrialsCommon- Array of common trials present in all sets

Example:

goodTrials1 = [1, 2, 3, 4, 5]; goodTrials2 = [3, 4, 5, 6, 7]; goodTrials3 = [4, 5, 6, 7, 8]; goodTrials = {goodTrials1, goodTrials2, goodTrials3}; goodTrialsCommon = extractCommonTrials(goodTrials);

Initialize the common trials with the first set of good trials

remove_bad_trials(data, threshold)

remove_bad_trials - Removes bad trials based on a threshold detection.

Syntax: [NumTrials, goodtrials] = remove_bad_trials(data, threshold)

Inputs:

data - Electrodes x Trials x Samples matrix threshold - Threshold of standard deviation to remove noisy trials

Outputs:

NumTrials - Number of good trials in each channel goodtrials - Trial indices after removing bad trials

Example:

data = randn(10, 100, 500); % Example data with 10 electrodes, 100 trials, and 500 samples threshold = 3; % Threshold of 3 standard deviations [NumTrials, goodtrials] = remove_bad_trials(data, threshold); % Remove bad trials

spatialMap(ieeg, chanMap)

spatialMap - Rearranges the iEEG data based on a channel map.

Syntax: ieegSpaceArrange = spatialMap(ieeg, chanMap)

Inputs:

ieeg - iEEG data (Channels x Trials x Samples) chanMap - Channel map indicating the spatial arrangement of channels

Outputs:

ieegSpaceArrange - Rearranged iEEG data based on the channel map

filtHarmInd(ieeg, fs, fFilt)

filtHarmInd - Apply a bandstop filter to remove a specific frequency component from an IEEG signal.

Syntax: ieegfilt = filtHarmInd(ieeg, fs, fFilt)

Inputs:

ieeg - Input IEEG signal (channels x samples) fs - Sampling frequency of the EEG signal (in Hz) fFilt - Frequency component to filter (in Hz)

Output:

ieegfilt- Filtered EEG signal with the specified frequency component removed

Example:

ieegSignal = randn(8, 1000); % IEEG signal with 8 channels and 1000 samples fs = 1000; % Sampling frequency of 1000 Hz fFilt = 60; % Frequency component to filter (in Hz) filteredSignal = filtHarmInd(ieegSignal, fs, fFilt);

filt60(ieeg, fs)

filt60 - Apply a notch filter at 60 Hz to remove power line interference.

Syntax: ieegfilt = filt60(ieeg, fs)

Inputs:

ieeg - Input EEG signal (channels x samples) fs - Sampling frequency of the IEEG signal (in Hz)

Output:

ieegfilt- Filtered EEG signal with power line interference removed

Example:

ieegSignal = randn(8, 1000); % IEEG signal with 8 channels and 1000 samples fs = 1000; % Sampling frequency of 1000 Hz filteredSignal = filt60(ieegSignal, fs);

dataProcessorStrf(SMel, ieeg, fsIeeg, lag)

dataProcessorStrf - Process data for spectrotemporal receptive field (STRF) analysis.

Syntax: [XMatrix, YMatrix] = dataProcessorStrf(SMel, ieeg, fsIeeg, lag)

Inputs:

SMel - Spectrogram matrix (trial x frequency x time) ieeg - Intracranial EEG data (channels x trial x time) fsIeeg - Sampling frequency of the intracranial EEG data lag - Time lag in seconds

Outputs:

XMatrix - Input matrix for STRF analysis (samples x frequency x lag) YMatrix - Output matrix for STRF analysis (samples x channels)

microphoneMergeTask(micAudPath, micEphysRecord)

microphoneMergeTask - Merge microphone audio with audio channel from ephys recording.

Syntax: [micClean, fsMic] = microphoneMergeTask(micAudPath, micEphysRecord)

Inputs:

micAudPath - Path to the directory containing microphone audio files micEphysRecord - microphone from the ephys recording

Outputs:

micClean - Merged audio signal of the microphone and ephys recording fsMic - Sampling frequency of the microphone audio

matrixSubSample(chanMap, window, isOverlap)

matrixSubSample - Subsample a matrix by dividing it into smaller windowed segments.

Syntax: matrixPoints = matrixSubSample(chanMap, window, isOverlap)

Inputs:

chanMap - Input matrix (m x n) to be subsampled window - Window size [mWindow, nWindow] for the subsampling (in number of elements) isOverlap - Flag indicating whether to use overlapping windows (1) or non-overlapping windows (0)

Output:

matrixPoints- Subsampled matrix points where each row represents a windowed segment

Example:

chanMatrix = randn(100, 100); % Input matrix of size 100x100 windowSize = [10, 10]; % Window size of 10x10 overlap = 1; % Use overlapping windows subsampledMatrix = matrixSubSample(chanMatrix, windowSize, overlap);

permtest(sample1, sample2, numperm)

permtest - Perform one-sided permutation test to compare the means of two samples.

Syntax: p = permtest(sample1, sample2, numperm)

Inputs:

sample1 - First sample data (1 x n1) array sample2 - Second sample data (1 x n2) array numperm - Number of permutations to perform

Outputs:

p - p-value indicating the significance of the difference between the means

Example:

sample1 = [1, 2, 3, 4, 5]; % Example first sample sample2 = [6, 7, 8, 9, 10]; % Example second sample p = permtest(sample1, sample2, 1000); % Perform one-sided permutation test with 1000 permutations

minmaxscaler(x)

minmaxscaler - Perform min-max scaling on the input data.

Syntax: minmaxx = minmaxscaler(x)

Inputs:

x - Input data to be scaled (1 x n) array

Outputs:

minmaxx - Min-max scaled data (1 x n) array

Example:

data = [10, 20, 30, 40, 50]; % Example input data scaledData = minmaxscaler(data);

energyop(sig, gr)

%calculates the energy operator of a signal

extractPower(ieegSplit, fs, Frange, tw, etw)
cluster_correction(p, alpha)

p: 2D connected matrix of p-values alpha: significance level for multiple comparisons correction h: binary matrix indicating significant clusters crit_p: cluster-corrected p-value threshold adj_p: adjusted p-values for each data point

cluster_correction_method(p, alpha, method)

p: 2D connected matrix of p-values alpha: significance level for multiple comparisons correction method: established correction method (e.g. ‘fdr’, ‘bonferroni’) h: binary matrix indicating significant clusters crit_p: cluster-corrected p-value threshold adj_p: adjusted p-values for each data point

carSegment(ieeg)

carSegment - Applies the Common Average Reference (CAR) segmentation to intracranial EEG data.

Syntax: car = carSegment(ieeg)

Inputs:

ieeg - Intracranial EEG data (channels x trials x time)

Outputs:

car - CAR segmented EEG data (channels x trials x time)

Example:

ieeg = randn(16, 10, 1000); % Example intracranial EEG data car = carSegment(ieeg); % Apply the CAR segmentation

carFilter(ieeg)

carFilter - Common Average Reference (CAR) filter for intracranial EEG data.

Syntax: ieegFilt = carFilter(ieeg)

Inputs:

ieeg - Intracranial EEG data (channels x trials x time)

Outputs:

ieegFilt - Intracranial EEG data after applying the CAR filter

Example:

ieeg = randn(16, 10, 1000); % Example intracranial EEG data ieegFilt = carFilter(ieeg); % Apply the CAR filter

carFilterImpedance(ieeg, badChan)

carFilterImpedance - Common Average Reference (CAR) filter with impedance handling for intracranial EEG data.

Syntax: [ieegFilt, meanIeeg] = carFilterImpedance(ieeg, badChan)

Inputs:

ieeg - Intracranial EEG data (channels x trials x time) badChan - Indices of bad channels to be excluded from the CAR filter (1 x nBadChan)

Outputs:

ieegFilt - Intracranial EEG data after applying the CAR filter meanIeeg - Mean of the filtered EEG data across good channels

Example:

ieeg = randn(16, 10, 1000); % Example intracranial EEG data badChan = [3, 7]; % Indices of bad channels [ieegFilt, meanIeeg] = carFilterImpedance(ieeg, badChan); % Apply the CAR filter with impedance handling

lrrSegment(ieeg)

lrrSegment - Performs linear regression referencing (LRR) on ECoG data with multiple channels.

Reference: Young, D., et al. “Signal processing methods for reducing artifacts in microelectrode brain recordings caused by functional electrical stimulation.” Journal of neural engineering 15.2 (2018): 026014.

Created by Kumar Duraivel for Viventi and Cogan lab.

Inputs:

ieeg - Input signal with ‘n’ channels and ‘t’ timepoints (n x trials x time)

Outputs:

S - Linear regression referenced signal (n x t) w - Least square weights (n x trial x n-1)

Example:

ieeg = randn(16, 10, 1000); % Example ECoG data [S, w] = lrrSegment(ieeg); % Apply linear regression referencing

getWaveletScalogram(ieeg, fs, params)

getWaveletScalogram - Extracts wavelet scalogram using basewave5.

Inputs:

ieeg - ECoG data (channels x trials x time) fs - Sampling frequency in Hz params - Optional parameters (struct):

  • params.fLow: Low frequency range in Hz (default: 2)

  • params.fHigh: High frequency range in Hz (default: 500)

  • params.k0: The mother wavelet parameter (wavenumber) (default: 6)

  • params.waitc: Flag indicating whether to display a waitbar (default: 0)

Output:
waveSpec - Structure containing the wavelet scalogram and parameters:
  • waveSpec.spec: Wavelet scalogram for each channel (cell array of size [1 x channels])

  • waveSpec.fscale: Frequency scale of the wavelet scalogram (1./period)

  • waveSpec.params: Parameters used for the wavelet scalogram

Example:

ieeg = rand(10, 100, 1000); % Example ECoG data fs = 1000; % Sampling frequency params.fLow = 2; % Low frequency range params.fHigh = 500; % High frequency range params.k0 = 6; % Mother wavelet parameter params.waitc = 0; % Do not display waitbar waveSpec = getWaveletScalogram(ieeg, fs, params); % Extract wavelet scalogram

extractSpecNorm(spec, tw, etw)

extractSpecNorm - Extracts the normalized mean frequency from spectrograms.

Inputs:

spec - Spectrograms (cell array of size [1 x nChannels]) tw - Time window of interest [start_time, end_time] etw - Extraction time window [start_time, end_time]

Output:

meanFreqChanOut - Normalized mean frequency (nChannels x nFrequencies)

Example:

spec = cell(10, 1); % Example spectrograms (cell array) tw = [0, 10]; % Time window of interest etw = [2, 8]; % Extraction time window meanFreqChanOut = extractSpecNorm(spec, tw, etw); % Extract normalized mean frequency

getSpectrograms(ieeg, goodtrials, tw, etw, efw, prtw, pertw, intF, fs, ispermTest)

getSpectrograms - Extracts spectrograms and performs statistical tests on ECoG data.

Inputs:

ieeg - ECoG data (channels x trials x time) goodtrials - Good trials for each channel (cell array of size [1 x channels]) tw - Time window of interest [start_time, end_time] in seconds etw - Spectrogram time window [start_time, end_time] in seconds efw - Spectrogram frequency window [start_frequency, stop_frequency] in Hz prtw - Pre-onset time window [start_time, end_time] to get significant channels pertw - Post-onset time window [start_time, end_time] to get significant channels intF - Frequency range of interest for statistical tests [start_frequency, stop_frequency] in Hz fs - Sampling frequency in Hz ispermTest - Flag (0/1) indicating whether to perform a permutation test to determine channel significance

Outputs:

spec - Spectrograms of each trial for each channel (cell array of size [1 x channels]) pPerc - P-values from the permutation test to check channel significance (1 x channels)

Example:

ieeg = rand(10, 100, 1000); % Example ECoG data goodtrials = cell(1, 10); % Example good trials (cell array) tw = [0, 10]; % Time window of interest etw = [2, 8]; % Spectrogram time window efw = [30, 80]; % Spectrogram frequency window prtw = [0, 2]; % Pre-onset time window pertw = [2, 4]; % Post-onset time window intF = [30, 50]; % Frequency range of interest for statistical tests fs = 1000; % Sampling frequency ispermTest = 1; % Perform permutation test [spec, pPerc] = getSpectrograms(ieeg, goodtrials, tw, etw, efw, prtw, pertw, intF, fs, ispermTest); % Extract spectrograms and perform statistical tests

extract_spectrograms_channel(ieeg, AnaParams, ~)

extract_spectrograms_channel - Extracts the Multitaper spectrograms of the input signal.

Inputs:

ieeg - Input signal (trials x time) AnaParams - Analysis parameters

Outputs:

spec - Output spectrograms (trials x time x frequency) F - Frequency vector

Example:

ieeg = randn(10, 1000); % Example input signal AnaParams.Fs = 1000; % Sample rate AnaParams.Tapers = [1 1]; % Taper parameters AnaParams.fk = [0 100]; % Frequency range AnaParams.dn = 0.5; % Taper size in seconds [spec, F] = extract_spectrograms_channel(ieeg, AnaParams); % Extract spectrograms

specChanMap(spec, chanMap, selectedChannels, sigChannel, tw, entw, etw, efw, gammaF, cval, isIndView, meanFreqChanIn)

specChanMap - Plot spectrograms and calculate mean power for each channel.

Inputs:

spec - Spectrograms for each channel (cell array) chanMap - Channel mapping (optional, used for arranging subplots) selectedChannels - Selected channels for visualization sigChannel - Significant channels tw - Time window for spectrograms (start and end time in seconds) entw - Time window for calculating mean frequency (start and end time in seconds) etw - Time window for displaying spectrograms (start and end time in seconds) efw - Frequency window for displaying spectrograms (start and end frequency in Hz) gammaF - Frequency range for mean power calculation (start and end frequency in Hz) cval - Color axis limits for spectrograms (optional) isIndView - Flag indicating whether to plot individual channels or all channels meanFreqChanIn - Mean frequency for each channel (optional)

Outputs:

specMeanAll - Mean spectrogram for each channel (3D array: channels x time x frequency) specMeanPower - Mean power for each channel within the gamma frequency range meanFreqChanOut - Mean frequency for each channel

Note:

This function uses the subaxis function for arranging subplots. Make sure to have it in your MATLAB path.

specChanMapNoNorm(spec, chanMap, selectedChannels, tw, fw, etw, efw, cval, isIndView)

specChanMapNoNorm - Plot spectrograms without normalization

Inputs:

spec - Cell array of spectrograms chanMap - Channel mapping selectedChannels - Selected channels tw - Time window [start, end] fw - Frequency window [start, end] etw - Time window for extraction [start, end] efw - Frequency window for extraction [start, end] cval - Color axis limits [min, max] isIndView - Flag indicating whether to plot individual view

Note: This function plots spectrograms without normalization.

viz_ktensor_phonotactic(est_factors, channelsPooled, timeEpoch, phonemeTrial, disp)
viz_ktensor_freesurfer(est_factors, channelsPooled, timeEpoch, phonemeTrial, nDisp)
visTimeGenAcc2D(decodeStruct, options)

Visualizes the generalized accuracy over time for a decoding analysis.

Arguments:
  • decodeStruct: A structure containing decoding results.

  • options: A structure containing optional parameters for visualization. - perc2cutoff: The percentile value to determine the contour cutoff (default: 90). - pVal2Cutoff: The p-value threshold to determine significant regions (default: 0.01). - chanceVal: The value representing chance performance (default: 1). - timePad: The padding added to the time range (default: 0.1). - clabel: The label for the colorbar (default: “Output Value”). - axisLabel: The label for the x and y axes (default: “”). - clowLimit: The lower limit for the color axis (default: 0).

Note: The decodeStruct should contain the following fields:
  • timeRange: A vector specifying the time points for analysis.

  • accTime: A matrix of generalized accuracy values over time.

  • pValTime: A matrix of p-values over time.

Example usage:

decodeStruct.timeRange = [0:0.1:1]; decodeStruct.accTime = rand(11); decodeStruct.pValTime = rand(11); options = struct(); visTimeGenAcc2D(decodeStruct, options);

viz_ktensor_update(est_factors, chanMap, selectedChannels, timeTrial, trigLabelsSort, labels, nDisp)
visTimeGen2D(decodeStruct, options)

Plots the result from 2D temporal generalization

Significant time-points are marked by orange markers Input decodeStuct - result from 1D temporal generalization

viz_ktensor_phonotactic_v2(est_factors, channelsPooled, timeEpoch, phonemeTrial, disp)
chanView(val2disp, chanMap, options)

figure;

viz_nnmf_factors(chanMap, selectedChannels, timeGammaPerc, timeGammaProd, factorChan, factorTime, clusterScore1, clusterScore2)
visTimeGen1D(decodeStruct, options)

Plots the result from 1D temporal generalization Significant time-points are marked by orange markers Input decodeStuct - result after 1D temporal generalization

visTimePlot3_v2(timeEpoch, signal2plot, options)
VISTIMEPLOT Visualize channel averaged plot of the entire time series

Detailed explanation goes here

timeEpoch - 3 dimensions of time points

visTimeGenAcc1DCluster_v2(decodeStruct, decodeStructShuffle, timeEpoch, options)
VISTIMEPLOT Visualize channel averaged plot of the entire time series

This function generates a channel-averaged plot of the time series data. It visualizes the average accuracy values and significance clusters obtained from decoding analyses.

Arguments: - decodeStruct: Cell array containing decoding results for the actual data - decodeStructShuffle: Cell array containing decoding results for shuffled data - timeEpoch: 2D time values in seconds [start_time end_time] for each epoch - options: Structure with optional parameters

  • pVal2Cutoff: Cutoff value for p-values (default = 0.05)

  • timePad: Time padding value (default = 0)

  • clabel: Label for the output value (default = “Output Value”)

  • axisLabel: Label for the y-axis (default = “”)

  • clowLimit: Lower limit for the color (default = 0)

  • maxVal: Maximum value for scatter plot (default = 1)

  • chanceVal: Chance value for y-axis line (default = 0.1111)

  • colval: Color value for plots (default = [0 0 1])

  • labels: Labels for the three subplots (default = {‘Auditory’,’Go’,’ResponseOnset’})

  • tileaxis: Optional pre-defined tile axes (default = [])

Returns: - ax: Cell array of axes handles

Example usage:

decodeStruct = {…}; % Actual decoding results decodeStructShuffle = {…}; % Shuffled decoding results timeEpoch = [-0.5 2; -0.5 1; -1 1.5]; % Time epochs options = struct(‘pVal2Cutoff’, 0.05, ‘timePad’, 0, ‘clabel’, “Output Value”, …); ax = visTimeGenAcc1DCluster_v2(decodeStruct, decodeStructShuffle, timeEpoch, options);

viz_ktensor_update_timeSplit_compile2(est_factors, chanMap, selectedChannels, timeGammaPerc, timeGammaProd, trigLabelsSort, nDisp, factorChan, factorTime, clusterScore)
timeSeriesChanMap(sig2view, chanMap, selectedChannels, timeInterest, yval, etw, label)
viz_ktensor_update_timeSplit(est_factors, chanMap, selectedChannels, timeGammaPerc, timeGammaProd, trigLabelsSort, responseTime, labels, nDisp)
visTimePlot(timeEpoch, signal2plot, options)
VISTIMEPLOT Visualize channel averaged plot of the entire time series

Detailed explanation goes here

timeEpoch - 3 dimensions of time points

permutest(trial_group_1, trial_group_2, dependent_samples, p_threshold, num_permutations, two_sided, num_clusters)

Permutation test for dependent or independent measures of 1-D or 2-D data. Based on Maris & Oostenveld 2007 for 1-D and 2-D vectors. The test statistic is T-Sum - the total of t-values within a cluster of contingent above-threshold data points. See: Maris, E., & Oostenveld, R. (2007). Nonparametric statistical testing of EEG-and MEG-data. Journal of Neuroscience Methods, 164(1), 177�190. https://doi.org/10.1016/j.jneumeth.2007.03.024

Important notes: * Make sure you understand whether you should be using a test of dependent or independent samples (a within or between subjects test, respectively). Also make sure you know if you want a one-sided or two-sided test. * The number of permutation sets a minimal boundary for the resulting p-value. This boundary is 1/(nP+1). If a very low p-value is needed, e.g. to survive a multiple-comparisons correction, use a sufficiently high number of permutations (this is also necessary in order to estimate the p-value with sufficient accuracy unless there is a very small number of trials). * When runnning a two-sided test, there is no need to retroactively correct the p-value, as this more lenient assumption is already reflected in the way the null-hypothesis distribution is constructed.

Syntax: [clusters, p_values, t_sums, permutation_distribution ] = PERMUTEST(x,y) runs a cluster-based permutation based for dependent samples, testing for differences between x and y. x and y should be 2D or 3D matrices, where the last dimension is the dimension across which the test variance is defined (that is, trials or subjects). clusters is a cell array with each cell holding the vector/matrix indexes corresponding to a specific cluster (sorted by magnitude). p_values is the permutation p-value corresponding to each cluster. t_sums is the sum of t-values of all data points comprising each cluster. distribution is the T-Sum permutation distribution (note that it will include many zero values; these correspond to all the permutations where no above-threshold clusters were found). PERMUTEST(x,y,d), where d is set to true or false, determines whether the test is for dependent samples. If set to false, it is assumed that x and y are independent (non-paired) data sets. In this case, x and y can have a different number of trials (though all other dimensions should be equal in size). Default value is true. PERMUTEST(x,y,d,p) sets p as the p-value threshold below which a data point is part of a cluster. Lower values mean that the test is sensitive to narrow, stronger effects; higher values make the test sensitive to broad, weaker effects. The p-value is translated to a t-value for the purpose of this test. PERMUTEST(x,y,d,p,nP) sets nP as the number of permutations. The function will check whether this number can be supported for the given number of trials and test type. PERMUTEST(x,y,d,p,nP,t), where t is set to true or false, determines whther the test is a two-sided test. If set to true, negative differences will be detected as well. Default value is false (one-sided test). PERMUTEST(x,y,d,p,nP,t,nC) sets nC as the maximal number of significant clusters to be detected. Default value is inf (all existing clusters will be tested against the H0 distribution).

Written by Edden M. Gerber, lab of Leon Y. Deouell, 2014 Send bug reports and requests to edden.gerber@gmail.com

travellingWaveMovie(sig2Movie, chanMap, timeAll, options)
specview(t, f, S, titl)
visTimeGenAcc1DCluster(decodeStruct, decodeStructShuffle, options)

Plots the result from 1D temporal generalization Significant time-points are marked by orange markers Input decodeStuct - result after 1D temporal generalization

getPwelch(ieeg, fs, time, tw)

ieeg - data (channels X timepoints) fs - sampling frequency (Hz) time - time in seconds (same length as in ieeg) tw - time window in seconds to select for psd ([20 180])

viz_ktensor_update_timeSplit_mds(est_factors, chanMap, selectedChannels, timeGammaPerc, timeGammaProd, trigLabelsSort, responseTime, labels, nDisp)
formatTicks(gca)
visTimeGenContour2D(decodeStructArray, options)

Plots the result from 2D temporal generalization

Significant time-points are marked by orange markers Input decodeStuct - result from 1D temporal generalization

travelling_wave_analysis(ieeg, goodTrials, selectedChannels)

load(‘goodTrials.mat’);

visTimePlot3(timeEpoch, signal2plot, options)
VISTIMEPLOT Visualize channel averaged plot of the entire time series

Detailed explanation goes here

timeEpoch - 3 dimensions of time points

visTimeGenAcc1D(decodeStruct, options)

Plots the result from 1D temporal generalization Significant time-points are marked by orange markers Input decodeStuct - result after 1D temporal generalization

viz_ktensor_phonotactic_v3(est_factors, channelsPooled, timeEpoch, phonemeTrial, disp)
strfChanMap(strfModelFit, stimInfo, chanMap, selectedChannels, isIndView)
viz_ktensor_update_timeSplit_compile(est_factors, chanMap, selectedChannels, timeGammaPerc, timeGammaProd, trigLabelsSort, nDisp)
read_Intan_RHD2000_file_path_update(path, fileID, channel)

read_Intan_RHD2000_file_path_date Update made by Kumar to read specific channels

Original Version 2.01, 11 October 2017

Reads Intan Technologies RHD2000 data file generated by evaluation board GUI or Intan Recording Controller. Data are parsed and placed into variables that appear in the base MATLAB workspace. Therefore, it is recommended to execute a ‘clear’ command before running this program to clear all other variables from the base workspace.

Input path - directory path that contains rhd files fileID - file order number channel - channel IDs to load Example: >> clear >> path = ‘E:1024 channel2019-02-06 Human 1024ch IntraOp'; >> [amplifier_data,board_adc_data,t_amplifier] = read_Intan_RHD2000_file_path_update(path,3,10:12); >> plot(t_amplifier, amplifier_data(1,:))

convert_OpenE_rec2mat(fpath)

Converts Open Ephys recordings to MATLAB .mat format.

Arguments: - fpath: File path of the Open Ephys recordings folder.

load_open_ephys_data(filename)

[data, timestamps, info] = load_open_ephys_data(filename)

Loads continuous, event, or spike data files into Matlab.

Inputs:

filename: path to file

Outputs:

data: either an array continuous samples (in microvolts),

a matrix of spike waveforms (in microvolts), or an array of event channels (integers)

timestamps: in seconds

info: structure with header and other information

DISCLAIMER:

Both the Open Ephys data format and this m-file are works in progress. There’s no guarantee that they will preserve the integrity of your data. They will both be updated rather frequently, so try to use the most recent version of this file, if possible.

read_Intan_RHD2000_file_path_update_EDIT_ELIM_OVERHEAD(fullPathToRawDataFile, channel)

read_Intan_RHD2000_file_path_date Update made by Kumar to read specific channels

Original Version 2.01, 11 October 2017

Reads Intan Technologies RHD2000 data file generated by evaluation board GUI or Intan Recording Controller. Data are parsed and placed into variables that appear in the base MATLAB workspace. Therefore, it is recommended to execute a ‘clear’ command before running this program to clear all other variables from the base workspace.

Input fullPathToRawDataFile - full path to file containing raw data channel - channel IDs to load Example: >> clear >> path = ‘E:1024 channel2019-02-06 Human 1024ch IntraOp'; >> [amplifier_data,board_adc_data,t_amplifier] = read_Intan_RHD2000_file_path_update(path,10:12); >> plot(t_amplifier, amplifier_data(1,:))

intanWrap(path, channel, fileNum, isDecimate, isTask)

Reads Intan RHD2000 data files and returns the EEG, microphone, and trigger data.

Arguments: - path: File path of the Intan data files. - channel: Channel number to extract data from. - fileNum: File number to process. - isDecimate: Logical value indicating whether to decimate the data (default: false). - isTask: Logical value indicating whether to extract task-related data (default: false).

Returns: - ieegall: EEG data matrix. - microphone: Microphone data vector. - trigger: Trigger data vector.

ClearElementsWithLowOccurence(array, minimalFrequency)
scoreSelect(sig2analyzeAllFeature, labels, varVector, isKfold, numFold)

Hyperparameter optimization to extract optimal principal components

pcaLinearDecoderWrapTrainTestSplit(ieegSplitTrain, ieegSplitTest, labels, tw, etwTrain, etwTest, varVector, numFolds, isauc)

The function performs supervised PCA-LDA decoding on ephys time-series dataset; Step 1: Hyperparameter optimization through nested cross-validation to identify the optimal number of PC dimensions Step 2: Linear discriminant decoding

Input ieegSplit (channels x trials x time): Input dataset labels (trials): Input labels tw: epoch time-window etw: selected time-window for decoding numDim: Number of PCA dimensions to include numFolds: Number of folds for cross-validation Output accAll - overall accuracy (0 - 1) ytestAll - tested labels ypredall - predicted labels

pcaDecodeRegress(sigTrain, sigTest, YTrain, YTest, varPercent)
meanTrain = mean(sigTrain,1);

stdTrain = std(sigTrain,0,1);

sigTrainNorm = (sigTrain - meanTrain)./stdTrain;

phonemeDistanceError(CMatNorm, pOccur)
pcaDecode(sigTrain, sigTest, YTrain, YTest, nModes, isauc)
tsneScoreExtract(ieegSplit, labels, tw, chanMap, etw, varVal, nElec, nIter)

Extract tsne score after SVD decomposition Input arguments

linearDecoder(ieegSplit, labels, tw, etw, numFolds, isauc)
phonemeExtract(trialInfoMat, fs, wordPhonemeRaw, nonwordPhonemeRaw)

trialMetrics = [Trials.StartCode]; trialInfoMat = cell2mat(trialInfo);

pcaDecodeLogisticVariance(sigTrain, sigTest, YTrain, YTest, varPercent, isauc)
scoreSelectRegress(sig2analyzeAllFeature, labels, varVector, isKfold, numFold)

Hyperparameter optimization to extract optimal principal components

pcaLinearDecoderWrapTrainTest(ieegSplit, labels, tw, etwTrain, etwTest, varVector, numFolds, isauc)

The function performs supervised PCA-LDA decoding on ephys time-series dataset; Step 1: Hyperparameter optimization through nested cross-validation to identify the optimal number of PC dimensions Step 2: Linear discriminant decoding

Input ieegSplit (channels x trials x time): Input dataset labels (trials): Input labels tw: epoch time-window e.g [-1 1] etwTrain: selected time-window for Training e.g. [-0.5 0] etwTest: selected time-window for Testing e.g. [0 0.5] varVector: % variance of PCA dimensions to optimize e.g. [10:10:90] numFolds: Number of folds for cross-validation e.g. 20 (for 20-fold cross-validation) isauc: 0|1 to calculate AUC Output accAll - overall accuracy (0 - 1) ytestAll - tested labels ypredall - predicted labels

extractPcaLdaModelWeights(modelWeights, numClass, numChan, numTime)

Initialize variables to store model weights

scoreSelectLogistic(sig2analyzeAllFeature, labels, varVector, isKfold, numFold)

Hyperparameter optimization to extract optimal principal components

attributeSelectDiscrete(phonemePower, attributeId, pLabel)
pcaDecodeVariance(sigTrain, sigTest, YTrain, YTest, varPercent, isauc)
meanTrain = mean(sigTrain,1);

stdTrain = std(sigTrain,0,1);

sigTrainNorm = (sigTrain - meanTrain)./stdTrain;

phonemeEvoked(ieeg, micSamp, timeSamp, phBreak, phTime, atw, tw, ptw, fs, fsAudio)
phonemeSelective(phonemePower, pLabelId, pvalsMClean)
phonemeEncoder(phonLabel)
pcaLinearRegressDecoderWrapTrainTest(ieegSplit, predictors, tw, etwTrain, etwTest, varVector, numFolds)

The function performs supervised PCA-LDA decoding on ephys time-series dataset; Step 1: Hyperparameter optimization through nested cross-validation to identify the optimal number of PC dimensions Step 2: Linear discriminant decoding

Input ieegSplit (channels x trials x time): Input dataset labels (trials): Input labels tw: epoch time-window etw: selected time-window for decoding numDim: Number of PCA dimensions to include numFolds: Number of folds for cross-validation Output accAll - overall accuracy (0 - 1) ytestAll - tested labels ypredall - predicted labels

pcaLinearRegressDecoderWrap(ieegSplit, labels, tw, etw, varVector, numFolds)

The function performs supervised PCA-LDA decoding on ephys time-series dataset; Step 1: Hyperparameter optimization through nested cross-validation to identify the optimal number of PC dimensions Step 2: Linear discriminant decoding

Input ieegSplit (channels x trials x time): Input dataset labels (trials): Input labels tw: epoch time-window etw: selected time-window for decoding numDim: Number of PCA dimensions to include numFolds: Number of folds for cross-validation Output accAll - overall accuracy (0 - 1) ytestAll - tested labels ypredall - predicted labels

stmfDecodeWrap(ieegSplit, labels, tw, etw, numFolds, isauc)
pcaLinearDecoderWrap(ieegSplit, labels, tw, etw, varVector, numFolds, isauc)

The function performs supervised PCA-LDA decoding on ephys time-series dataset; Step 1: Hyperparameter optimization through nested cross-validation to identify the optimal number of PC dimensions Step 2: Linear discriminant decoding

Input ieegSplit (channels x trials x time): Input dataset labels (trials): Input labels tw: epoch time-window etw: selected time-window for decoding numDim: Number of PCA dimensions to include numFolds: Number of folds for cross-validation Output accAll - overall accuracy (0 - 1) ytestAll - tested labels ypredall - predicted labels

matrixSubSample(chanMap, window, isOverlap)
attributeSelection(phonemePower, pLabel)
phonemeDecoder(phonemeSequence)
pcaLogisticDecoderWrap(ieegSplit, labels, tw, etw, varVector, numFolds, isauc)

The function performs supervised PCA-LDA decoding on ephys time-series dataset; Step 1: Hyperparameter optimization through nested cross-validation to identify the optimal number of PC dimensions Step 2: Linear discriminant decoding

Input ieegSplit (channels x trials x time): Input dataset labels (trials): Input labels tw: epoch time-window etw: selected time-window for decoding numDim: Number of PCA dimensions to include numFolds: Number of folds for cross-validation Output accAll - overall accuracy (0 - 1) ytestAll - tested labels ypredall - predicted labels