Signal Processing Functions#

This section documents the signal processing functions for spectral analysis, resampling, and baseline removal.

Spectral Analysis#

eegprep.eeg_autocorr(EEG, pct_data=None)

Compute autocorrelation of ICA components.

Parameters#

EEGdict

EEG data structure with icaact

pct_datafloat, optional

Percentage of data to use (default 100)

Returns#

acndarray

Autocorrelation array

eegprep.eeg_autocorr_welch(EEG, pct_data=100)

Compute autocorrelation of EEG ICA components using Welch method.

Parameters#

EEGdict

EEG data structure with ‘icaweights’, ‘icaact’, ‘pnts’, ‘srate’ fields.

pct_datafloat, optional

Percentage of data to use. Default 100.

Returns#

ndarray

Autocorrelation array.

eegprep.eeg_rpsd(EEG, nfreqs=None, pct_data=100)

Compute relative power spectral density for ICA components.

Parameters#

EEGdict

EEG data structure with ICA activations.

nfreqsint, optional

Number of frequency bins. Default is Nyquist frequency.

pct_datafloat, optional

Percentage of data to use. Default is 100.

Returns#

ndarray

Power spectral density in dB for each component.

Time-Frequency And Statistics#

eegprep.newtimef(data, frames, tlimits, srate, cycles=0, *, winsize=None, freqs=None, freqrange=None, nfreqs=None, freqscale=None, timesout=None, padratio=None, overlap=None, baseline=0, scale='log', basenorm='off', trialbase='off', powbase=None, alpha=None, pboot=None, rboot=None, erspboot=None, itcboot=None, naccu=200, boottype='shuffle', baseboot=1, mcorrect='none', itctype='phasecoher', type=None, subitc='off', plottype='image', plot='on', plotersp='on', plotitc='on', plotphase='off', title='Time-frequency', rng=None, detrend='off', causal='off', wletmethod='dftfilt3', timewarp=None, timewarpms=None, timewarpidx=None, vert=None, verbose='off')

Compute an EEGLAB-like ERSP/ITC time-frequency decomposition.

Parameters:
Return type:

TimeFrequencyResult

eegprep.newcrossf(x, y, frames, tlimits, srate, cycles=0, **kwargs)

Compute an EEGLAB-like event-related coherence decomposition.

Parameters:
Return type:

CrossFrequencyResult

eegprep.timefreq(data, srate, *, frames=None, cycles=0, wavelet=0, winsize=None, tlimits=None, detrend='off', causal='off', freqs=None, nfreqs=None, freqscale='linear', ffttaper='hanning', padratio=2, itctype='phasecoher', subitc='off', timesout=None, ntimesout=None, timestretch=None, wletmethod='dftfilt3', verbose='off')

Return EEGLAB-like spectral estimates for each trial.

Args mirror EEGLAB’s timefreq where practical. The optional frames keyword is an EEGPrep convenience for reshaping flat trial-concatenated input before applying the EEGLAB algorithm.

Parameters:
Return type:

TimeFrequencyDecomposition

eegprep.timef(data, frames, tlimits, srate, cycles=0, **kwargs)

Compute legacy timef outputs using EEGPrep’s newtimef core.

Parameters:
Return type:

TimeFrequencyResult

eegprep.crossf(x, y, frames, tlimits, srate, cycles=0, **kwargs)

Compute legacy crossf outputs using EEGPrep’s newcrossf core.

Parameters:
Return type:

CrossFrequencyResult

eegprep.pac(X, Y, srate, **kwargs)

Compute phase-amplitude coupling from epoched signals.

The output mirrors EEGLAB’s compute-only helper with named fields for the PAC matrix, output times, amplitude frequencies, phase frequencies, and single-trial spectral decompositions.

Parameters:
Return type:

PacResult

eegprep.pac_cont(X, Y, srate, **kwargs)

Compute sliding-window phase-amplitude coupling from continuous data.

Parameters:
Return type:

PacContResult

eegprep.dftfilt(length, maxfreq, cycle, oversmp, wavfact)

Return legacy discrete Fourier filters.

Parameters:
Return type:

ndarray

eegprep.dftfilt2(freqs, cycles, srate, cycleinc='linear', kind='morlet')

Return EEGLAB dftfilt2 wavelet filters.

Parameters:
Return type:

list[ndarray]

eegprep.dftfilt3(freqs, cycles, srate, *, cycleinc='linear', winsize=None, timesupport=7.0)

Return EEGLAB dftfilt3-style complex wavelet filters.

Parameters:
  • freqs (Any) – Frequencies of interest in Hz.

  • cycles (Any) – Scalar, two-value, or per-frequency cycle specification.

  • srate (float) – Sampling rate in Hz.

  • cycleinc (str) – "linear" or "log" interpolation for two cycle values.

  • winsize (int | None) – Optional fixed filter length. When omitted, Morlet filters use EEGLAB’s seven-standard-deviation support and variable lengths.

  • timesupport (float) – Number of temporal standard deviations included.

Returns:

(wavelets, cycles, freqresol, timeresol).

Return type:

tuple[list[ndarray] | ndarray, ndarray, ndarray, ndarray]

eegprep.timewarp(ev_latency, new_latency)

Return the linear interpolation matrix that warps event latencies.

ev_latency and new_latency use EEGLAB’s 1-based frame indexing. Multiplying the returned matrix by a column time series maps samples so the original event frames align with the requested event frames.

Parameters:
  • ev_latency (Any)

  • new_latency (Any)

Return type:

ndarray

eegprep.angtimewarp(ev_latency, new_latency, angdata)

Warp an angular time series and wrap results to (-pi, pi].

Parameters:
  • ev_latency (Any)

  • new_latency (Any)

  • angdata (Any)

Return type:

ndarray

eegprep.tf_cycle_calc(freqs=None, width=None, width_unit=None, *, log_spaced=False, plot=False, data=None, fs=None, norm=False)

Calculate Morlet wavelet cycles from temporal or spectral width.

Parameters:
Return type:

TFCycleCalcResult

eegprep.newtimefbaseln(power, timesout, *, baseline=0, powbase=None, basenorm='off', commonbase='off', singletrials='on', trialbase='off')

Apply EEGLAB average baseline correction to absolute power.

Parameters:
  • power (Any) – Power array, usually freqs x times x trials.

  • timesout (Any) – Time values in milliseconds.

  • baseline (Any) – Scalar threshold, [min, max] interval, or NaN to disable.

  • powbase (Any) – Optional externally supplied baseline spectrum.

  • basenorm (str) – "on" for z-like baseline normalization.

  • commonbase (str) – Average baseline spectra across a list of power arrays.

  • singletrials (str) – Whether trials remain present on the last axis.

  • trialbase (str) – Trial baseline mode from newtimef.

Returns:

(corrected_power, baseline_indices, baseline_values).

Return type:

tuple[ndarray, ndarray, ndarray]

eegprep.newtimeftrialbaseln(power, timesout, *, baseline=0, basenorm='off', trialbase='off')

Apply trial-level divisive or standardized baseline correction.

Parameters:
Return type:

ndarray

eegprep.newtimefitc(tfdecomp, itctype='phasecoher')

Compute EEGLAB-style inter-trial coherence.

Parameters:
  • tfdecomp (Any) – Complex spectral estimates with trials on the last axis.

  • itctype (str) – "phasecoher", "phasecoher2", or "coher".

Returns:

Complex coherence values with the trial axis removed.

Return type:

ndarray

eegprep.newtimefpowerunit(params=None)

Return the display unit implied by newtimef baseline settings.

Parameters:

params (dict[str, Any] | None)

Return type:

str

eegprep.bootstat(args, statistic, *, alpha=0.05, naccu=200, bootside='both', boottype='shuffle', basevect=None, shuffledim=None, rng=None)

Accumulate surrogate statistics and return EEGLAB-style thresholds.

This Python helper intentionally accepts a callable statistic instead of MATLAB expression strings. It covers the time-frequency bootstrap paths used by EEGPrep while avoiding runtime string evaluation.

Parameters:
Return type:

BootstrapResult

eegprep.correct_mc(EEG, cycles=(3, 0.5), freqrange=(2, 50), timesout=(5, 6, 7, 8, 9, 10, 12, 14, 16, 18, 20, 24, 28, 32, 36, 40))

Estimate an EEGLAB-style multiple-comparison correction count.

EEGLAB fits a Ramberg-Schmeiser distribution to neighboring-bin correlations. EEGPrep uses the same standalone fitted p-value path without depending on the vendored EEGLAB checkout at runtime.

Parameters:
Return type:

tuple[int, ndarray]

eegprep.correctfit(pvalue, *, allpval=None, gamparams=None, zeromode='on')

Return a gamma-fit corrected p-value and fitted parameters.

Parameters:
Return type:

tuple[float, float, float, float]

eegprep.rsadjust(lambda3, lambda4, mean, variance, skewness)

Return lambda1 through lambda4 adjusted to mean and variance.

Parameters:
Return type:

tuple[float, float, float, float]

eegprep.rsfit(x, value, plot=0, *, return_details=False)

Return a Ramberg-Schmeiser fitted p-value for value within x.

Parameters:
Return type:

float | tuple[float, ndarray, ndarray, float]

eegprep.rsget(lambdas, value)

Return the fitted Ramberg-Schmeiser cumulative probability at value.

Parameters:
Return type:

float

eegprep.rspdfsolv(lambdas, skewness, kurtosis)

Return the Ramberg-Schmeiser moment residual for lambda3/lambda4.

Parameters:
Return type:

float

eegprep.rspfunc(pvalue, lambdas, value)

Return the absolute quantile residual for one probability value.

Parameters:
Return type:

float

eegprep.signalstat(data, plotlab=1, dlabel=None, percent=5, dlabel2='', map=None, chan_locs=None)

Compute EEGLAB-style summary statistics for a real-valued signal.

Parameters:
Return type:

SignalStatResult

eegprep.pop_newtimef(EEG=None, typeproc=1, num=None, tlimits=None, cycles=None, *args, gui=None, renderer=None, return_com=False, **kwargs)

Plot a channel or component ERSP/ITC decomposition.

Parameters:
eegprep.pop_newcrossf(EEG=None, typeproc=1, num1=None, num2=None, tlimits=None, cycles=None, *args, gui=None, renderer=None, return_com=False, **kwargs)

Plot event-related channel/component cross-coherence.

Parameters:
eegprep.pop_timef(EEG=None, typeproc=1, num=None, tlimits=None, cycles=None, *args, gui=None, renderer=None, return_com=False, **kwargs)

Run legacy pop_timef through EEGPrep’s pop_newtimef implementation.

Parameters:
eegprep.pop_crossf(EEG=None, typeproc=1, num1=None, num2=None, tlimits=None, cycles=None, *args, gui=None, renderer=None, return_com=False, **kwargs)

Run legacy pop_crossf through EEGPrep’s pop_newcrossf implementation.

Parameters:
eegprep.pop_signalstat(EEG=None, typeproc=1, cnum=None, percent=5, *, gui=None, renderer=None, return_com=False)

Compute and plot statistics for one channel or component.

Parameters:
eegprep.pop_eventstat(EEG=None, eventfield=None, type=None, latrange=None, percent=5, *, gui=None, renderer=None, return_com=False)

Compute and plot statistics for numeric EEG event fields.

Parameters:

Browser#

eegprep.eegplot(data, *args, **kwargs)

Open an EEGLAB-style scrolling browser for channel-major EEG data.

Parameters use EEGLAB names where practical. data may be a NumPy-like array shaped channels x samples or channels x samples x trials, or an EEG dictionary containing data, srate, chanlocs, and event fields. Spectral inputs use freqs with freqlimits; in that mode winlength is interpreted as a frequency span in Hz. The input is copied into the browser model and is not mutated by the viewer.

Parameters:
Return type:

Any

eegprep.eeg_multieegplot(data, rej=None, rejE=None, oldrej=None, oldrejE=None, *args, oldcolor=(0.8, 1.0, 0.8), newcolor=(0.8, 0.8, 1.0), show=True, **kwargs)

Open eegplot with current and previous rejection marks.

rej/rejE and oldrej/oldrejE follow EEGLAB’s convention: trial vectors are sweeps-length arrays of 0/1 marks and electrode marks are channels x sweeps boolean arrays. For continuous data, rejection rows may be [start end] or EEGLAB event-like rows whose start/end are in columns 3 and 4.

Parameters:
Return type:

Any

Resampling#

eegprep.pop_resample(EEG, freq=None, engine=None, *, gui=None, renderer=None, return_com=False, fc=None, df=None)

Resample EEG data to a new sampling rate.

Parameters#

EEGdict

EEGLAB EEG structure.

freqfloat

New sampling rate in Hz.

enginestr or None

Engine to use for implementation. Options are: - None: Use the default Python implementation - ‘poly’: Use scipy’s resample_poly function - ‘matlab’: Use MATLAB engine - ‘octave’: Use Octave engine

Returns#

EEGdict

EEGLAB EEG structure with resampled data.

Baseline Removal#

eegprep.rmbase(data, frames=0, basevector=0, *, return_mean=False)

Subtract per-channel baseline means from continuous or epoched data.

Parameters:
  • data (Any) – Data array shaped (channels, frames * epochs) or (channels, frames, epochs).

  • frames (int | None) – Samples per epoch. 0 or None uses the full second dimension, matching EEGLAB’s default.

  • basevector (Any) – EEGLAB-style 1-based baseline frame indices, or 0/ empty for the whole epoch.

  • return_mean (bool) – When true, return (dataout, datamean).

Returns:

Baseline-corrected data, and optionally the channel-by-epoch means.

eegprep.pop_rmbase(EEG=<object object>, timerange=None, pointrange=None, chanlist=None, *, gui=None, renderer=None, return_com=False)

Remove baseline means from an epoched or continuous EEG dataset.

timerange uses the units stored in EEG["times"]. pointrange and numeric chanlist values use EEGLAB-facing 1-based indices. Calling pop_rmbase(EEG) opens the GUI; pass explicit ranges or gui=False for direct command-line use.

Parameters:
  • EEG (Any)

  • timerange (Any)

  • pointrange (Any)

  • chanlist (Any)

  • gui (bool | None)

  • renderer (Any | None)

  • return_com (bool)

Topography#

eegprep.cart2topo(x, *args)

Convert XYZ Cartesian coordinates to polar topoplot coordinates.

This follows current EEGLAB cart2topo.m behavior: Cartesian coordinates are converted to MATLAB-style spherical coordinates, then to topoplot theta and radius via sph2topo method 2.

Parameters:
  • x (Any) – Either an (n, 3) array of X, Y, Z coordinates or a vector of X coordinates when Y and Z are supplied as separate arguments.

  • *args (Any) – Either (y, z) vectors. Additional EEGLAB legacy options are deprecated and are not supported.

Returns:

(theta, radius, x, y, z) arrays.

Return type:

tuple

eegprep.pop_topoplot(EEG=None, typeplot=1, items=None, topotitle=None, rowcols=None, plotdip=0, *args, gui=None, renderer=None, return_com=False, **kwargs)

Plot EEGLAB-style 2-D scalp maps for ERP latencies or ICA components.

Parameters:
  • EEG (dict[str, Any] | None) – EEGLAB-style EEG dictionary.

  • typeplot (int) – 1 for channel ERP latency maps, 0 for component maps.

  • items (Any) – Latencies in ms when typeplot=1 or 1-based component indices when typeplot=0. Negative component indices invert map polarity and NaN leaves a blank subplot.

  • topotitle (str | None) – Figure title.

  • rowcols (Any) – Optional [rows, columns] layout. Empty uses EEGLAB’s near-square page geometry.

  • plotdip (Any) – Accepted for EEGLAB signature compatibility; DIPFIT overlays are deferred to the Phase 4 headplot/DIPFIT integration.

  • gui (bool | None) – Force or suppress the EEGLAB-like input dialog.

  • renderer (Any | None) – Optional dialog renderer for tests.

  • return_com (bool) – Return (figures, command) when true.

  • **kwargs (Any) – Additional topoplot options such as electrodes, colorbar and maplimits.

  • args (Any)

eegprep.topoplot(datavector, chan_locs, **kwargs)

Plot a 2D topographic map of EEG data.

Parameters#

datavectorarray-like

Values to plot at each channel location.

chan_locslist of dict

Channel location structures with ‘labels’, ‘theta’, and ‘radius’ fields.

kwargsdict

Additional keyword arguments for customization:

  • noplot : str or tuple, default ‘off’

  • plotgrid : str, default ‘off’

  • plotchans : list, default []

  • ELECTRODES : str, default ‘on’

  • intrad : float, default nan

  • plotrad : float, default nan

  • headrad : float, default 0.5

  • method : str, default ‘rbf’

Returns#

handlematplotlib.figure.Figure or None

Figure handle if plotted, None otherwise.