| Title: | EEG Analysis Functions for PhysioExperiment Objects |
|---|---|
| Description: | Provides comprehensive electroencephalography (EEG) analysis functions for PhysioExperiment objects. Includes preprocessing (filtering, re-referencing, bad channel detection, interpolation, epoching, artifact rejection), independent component analysis (FastICA, Infomax, JADE) with automatic artifact detection, event-related potential (ERP) component detection and measurement (N100, P300, N400, P600, MMN), source localization (eLORETA, sLORETA, LCMV beamformer), EEG microstate analysis (K-means, AAHC), sleep staging (AASM criteria, spindle/K-complex/slow-wave detection), brain-computer interface features (CSP, SSVEP, motor imagery), clinical EEG analysis (spike detection, QEEG, asymmetry indices), time-frequency analysis (Morlet wavelet, STFT, multitaper, ERSP, ITC), connectivity analysis (coherence, PLV, wPLI, Granger causality), visualization (signal traces, ERP waveforms, topographic maps, spectrograms, connectivity plots, hypnograms, source maps), and simulated data generators for testing and demonstration. |
| Authors: | Yusuke Matsui [aut, cre] |
| Maintainer: | Yusuke Matsui <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.7.16 |
| Built: | 2026-10-03 13:42:04 UTC |
| Source: | https://github.com/x-biosignal/PhysioEEG |
Computes the dispersion entropy (DispEn) of a one-dimensional signal
(Rostaghi & Azami, 2016) – a fast, robust symbolic-dynamics complexity
measure. Unlike the amplitude-histogram entropies (renyiEntropy,
tsallisEntropy) and the ordinal permutation entropy, DispEn maps
the signal to c amplitude classes through the normal cumulative
distribution function (NCDF), forms embedding vectors of length
dimension (the dispersion patterns), and takes the Shannon
entropy of the pattern distribution, normalized by . The NCDF
mapping makes it insensitive to outliers and much cheaper than sample entropy,
with no threshold-crossing boundary effects. Set reverse = TRUE to
return the reverse dispersion entropy (RDEn), the mean-square deviation of the
pattern distribution from uniformity (larger = more regular / less complex).
dispersionEntropy(x, c = 6L, dimension = 3L, delay = 1L, reverse = FALSE)dispersionEntropy(x, c = 6L, dimension = 3L, delay = 1L, reverse = FALSE)
x |
A numeric vector (the time series). |
c |
Number of amplitude classes / symbols (default 6; Rostaghi & Azami recommend 4–8). |
dimension |
Embedding dimension |
delay |
Time delay (lag) in samples (default 1). |
reverse |
If |
This implementation reproduces NeuroKit2's entropy_dispersion
bit-for-bit, including its normalization convention (a base-2 Shannon term
divided by the natural-log , so DispEn ranges in
).
A single numeric value: the dispersion entropy (or, if
reverse = TRUE, the reverse dispersion entropy).
Rostaghi, M., & Azami, H. (2016). "Dispersion entropy: A measure for time-series analysis." IEEE Signal Processing Letters, 23(5), 610–614. doi:10.1109/LSP.2016.2542881
renyiEntropy, tsallisEntropy,
svdEntropy, petrosianFD.
set.seed(1) dispersionEntropy(rnorm(1000)) # DispEn (c = 6, m = 3) dispersionEntropy(rnorm(1000), reverse = TRUE) # reverse dispersion entropyset.seed(1) dispersionEntropy(rnorm(1000)) # DispEn (c = 6, m = 3) dispersionEntropy(rnorm(1000), reverse = TRUE) # reverse dispersion entropy
Separates each channel's power spectrum into an aperiodic (1/f) component
and periodic (oscillatory) peaks, following the specparam / FOOOF model
(Donoghue et al. 2020). The aperiodic exponent is a widely used index of the
excitation/inhibition balance and cortical state. Delegates the fit to
PhysioAnalysis::specparam().
eegAperiodic( pe, freq_range = c(1, 45), aperiodic_mode = c("fixed", "knee"), max_n_peaks = 6L, peak_width_limits = c(1, 12), min_peak_height = 0.05, peak_threshold = 2, assay_name = NULL )eegAperiodic( pe, freq_range = c(1, 45), aperiodic_mode = c("fixed", "knee"), max_n_peaks = 6L, peak_width_limits = c(1, 12), min_peak_height = 0.05, peak_threshold = 2, assay_name = NULL )
pe |
A |
freq_range |
Frequency range to fit, in Hz (default |
aperiodic_mode |
|
max_n_peaks |
Maximum number of oscillatory peaks per channel (default 6). |
peak_width_limits |
Min/max peak width in Hz (default |
min_peak_height |
Minimum peak height above the aperiodic fit (default 0.05). |
peak_threshold |
Peak detection threshold in SD of the flattened spectrum (default 2). |
assay_name |
Assay to use (default: the object's default assay). |
An eeg_aperiodic object: a list with aperiodic (per-channel data
frame: channel, exponent, offset, optionally knee, r_squared,
error), peaks (per-channel CF/PW/BW), exponent (a named
per-channel vector, e.g. for eegPlotTopomap()), and the underlying
specparam_result.
Donoghue et al. 2020, Nat Neurosci (specparam / FOOOF).
if (requireNamespace("PhysioAnalysis", quietly = TRUE)) { pe <- make_eeg(n_time = 2500, n_channels = 8, sr = 250) ap <- eegAperiodic(pe, freq_range = c(2, 40)) ap$aperiodic # per-channel exponent / offset }if (requireNamespace("PhysioAnalysis", quietly = TRUE)) { pe <- make_eeg(n_time = 2500, n_channels = 8, sr = 250) ap <- eegAperiodic(pe, freq_range = c(2, 40)) ap$aperiodic # per-channel exponent / offset }
Identifies and removes epochs contaminated by artifacts from 3D epoched EEG data. Supports multiple detection criteria: amplitude threshold, gradient (point-to-point voltage change), and joint probability.
eegArtifactReject( x, method = c("threshold", "gradient", "joint_probability"), threshold_uv = 100, gradient_uv_ms = 50, jp_threshold = 3, assay_name = NULL, output_assay = "clean" )eegArtifactReject( x, method = c("threshold", "gradient", "joint_probability"), threshold_uv = 100, gradient_uv_ms = 50, jp_threshold = 3, assay_name = NULL, output_assay = "clean" )
x |
A PhysioExperiment object with 3D epoched data. |
method |
Artifact detection method: |
threshold_uv |
Maximum absolute amplitude in microvolts for threshold rejection (default: 100). |
gradient_uv_ms |
Maximum point-to-point change in uV/ms for gradient rejection (default: 50). |
jp_threshold |
Number of standard deviations for joint probability rejection (default: 3). |
assay_name |
Name of the assay to check. If NULL, uses
|
output_assay |
Name of the output assay (default: |
A PhysioExperiment object with clean epochs in the specified output
assay. Artifact log stored in metadata(x)$artifact_log.
pe <- make_eeg(n_time = 10000, n_channels = 19, sr = 500) events <- data.frame(onset_sec = c(1, 3, 5, 7, 9)) pe_ep <- eegEpoch(pe, events, limits = c(-0.2, 0.8)) pe_clean <- eegArtifactReject(pe_ep, method = "threshold", threshold_uv = 100, assay_name = "epoched")pe <- make_eeg(n_time = 10000, n_channels = 19, sr = 500) events <- data.frame(onset_sec = c(1, 3, 5, 7, 9)) pe_ep <- eegEpoch(pe, events, limits = c(-0.2, 0.8)) pe_clean <- eegArtifactReject(pe_ep, method = "threshold", threshold_uv = 100, assay_name = "epoched")
Computes frontal alpha asymmetry indices from paired electrode sites.
For each pair (right, left), band power is computed via FFT and the
asymmetry index is calculated as log(power_right) - log(power_left).
Positive values indicate greater right-hemisphere alpha (typically
associated with greater left-hemisphere cortical activity).
eegAsymmetry(x, pairs = NULL, band = c(8, 13), assay_name = NULL)eegAsymmetry(x, pairs = NULL, band = c(8, 13), assay_name = NULL)
x |
A PhysioExperiment object with EEG data. |
pairs |
A list of character vectors of length 2, each specifying
a (right, left) electrode pair. Defaults to |
band |
Numeric vector of length 2 specifying the frequency band
in Hz (default: |
assay_name |
Name of the input assay. If |
A data.frame with columns:
Character label for the electrode pair.
Character name of the left electrode.
Character name of the right electrode.
Numeric band power for the left electrode.
Numeric band power for the right electrode.
Numeric asymmetry: log(right) - log(left).
Nuwer, M. R., et al. (1999). IFCN standards for digital recording of clinical EEG. Electroencephalography and Clinical Neurophysiology, 106(3), 259-261.
eegSpikeDetect(), eegQEEG(), eegSlowing()
pe <- make_eeg(n_time = 5000, n_channels = 19, sr = 500) asym <- eegAsymmetry(pe) print(asym)pe <- make_eeg(n_time = 5000, n_channels = 19, sr = 500) asym <- eegAsymmetry(pe) print(asym)
Implements the autoreject algorithm (Jas et al. 2017) for epoched EEG.
Per-channel peak-to-peak rejection thresholds are chosen by cross-validation,
then each epoch is kept, repaired by interpolating its worst bad channels, or
dropped, according to two hyperparameters: consensus (the fraction of
bad channels above which an epoch is dropped) and n_interpolate (the
number of worst bad channels to interpolate in a repaired epoch). Either
hyperparameter is chosen by cross-validation when not supplied. Bad channels
are repaired with spherical-spline interpolation (the same weights used by
eegInterpolate()), so electrode positions must be present (run
eegMontage() first).
eegAutoReject( x, consensus = NULL, n_interpolate = NULL, cv_folds = 5L, thresh_range = NULL, n_thresh = 20L, assay_name = "epoched", output_assay = "autoreject_clean" )eegAutoReject( x, consensus = NULL, n_interpolate = NULL, cv_folds = 5L, thresh_range = NULL, n_thresh = 20L, assay_name = "epoched", output_assay = "autoreject_clean" )
x |
A PhysioExperiment with 3D epoched data (time x channels x epochs)
in |
consensus |
Fraction of bad channels (from 0 to 1) above which an epoch
is dropped. |
n_interpolate |
Number of worst bad channels to interpolate per repaired
epoch. |
cv_folds |
Number of cross-validation folds (default: 5). |
thresh_range |
Optional candidate peak-to-peak threshold grid: either a
length-2 |
n_thresh |
Number of grid thresholds when |
assay_name |
Name of the 3D epoched data in metadata or assays
(default: |
output_assay |
Name for the cleaned 3D data stored in metadata
(default: |
The cross-validation objective, at every stage, is the root-mean-square error between the mean of the good/cleaned training epochs and the median of the held-out test epochs - the criterion introduced by autoreject.
The PhysioExperiment with cleaned 3D epoched data in
metadata(x)[[output_assay]] (dropped epochs removed, repaired epochs
interpolated) and a rejection log in metadata(x)$autoreject: the
per-channel thresholds, chosen consensus and
n_interpolate, the epoch-by-channel bad_matrix, the
interpolated channel-epochs, and the dropped_epochs. The step
is recorded in provenance.
Jas, M., Engemann, D. A., Bekhti, Y., Raimondo, F., & Gramfort, A. (2017). Autoreject: Automated artifact rejection for MEG and EEG data. NeuroImage, 159, 417-429.
eegArtifactReject(), eegInterpolate(), eegEpoch(),
eegMontage()
pe <- make_eeg_erp(n_epochs = 40, n_channels = 19, sr = 250) pe <- eegMontage(pe, system = "10-20") pe <- eegAutoReject(pe, assay_name = "raw") dim(S4Vectors::metadata(pe)$autoreject$bad_matrix)pe <- make_eeg_erp(n_epochs = 40, n_channels = 19, sr = 250) pe <- eegMontage(pe, system = "10-20") pe <- eegAutoReject(pe, assay_name = "raw") dim(S4Vectors::metadata(pe)$autoreject$bad_matrix)
Identifies bad (noisy, flat, or poorly correlated) EEG channels using
multiple automated criteria. Channels flagged as bad can subsequently
be interpolated using eegInterpolate.
eegBadChannels( x, method = c("all", "flat", "noise", "correlation"), flat_threshold = 1e-06, noise_threshold = 4, corr_threshold = 0.4, assay_name = NULL )eegBadChannels( x, method = c("all", "flat", "noise", "correlation"), flat_threshold = 1e-06, noise_threshold = 4, corr_threshold = 0.4, assay_name = NULL )
x |
A PhysioExperiment object. |
method |
Detection method(s) to apply: |
flat_threshold |
Variance threshold below which a channel is considered flat (default: 1e-6). |
noise_threshold |
Number of standard deviations above median variance to flag a channel as noisy (default: 4). |
corr_threshold |
Minimum mean correlation with other channels. Channels below this are flagged (default: 0.4). |
assay_name |
Name of the assay to analyze. If NULL, uses
|
A data.frame with columns: channel (label), is_bad
(logical), reason (character description), score (numeric
metric value).
pe <- make_eeg(n_time = 5000, n_channels = 19, sr = 500) bad_df <- eegBadChannels(pe) bad_labels <- bad_df$channel[bad_df$is_bad]pe <- make_eeg(n_time = 5000, n_channels = 19, sr = 500) bad_df <- eegBadChannels(pe) bad_labels <- bad_df$channel[bad_df$is_bad]
Classifies BCI features using Linear Discriminant Analysis (LDA) or shrinkage LDA. Implements Fisher's LDA with optional Ledoit-Wolf shrinkage regularization for robust classification with high-dimensional or small-sample data. Optionally performs k-fold cross-validation.
eegBCIclassify( x, features = NULL, labels, method = c("lda", "shrinkage_lda"), cv_folds = NULL, assay_name = NULL )eegBCIclassify( x, features = NULL, labels, method = c("lda", "shrinkage_lda"), cv_folds = NULL, assay_name = NULL )
x |
A PhysioExperiment object with epoched (3D) EEG data. |
features |
Optional pre-computed feature matrix (n_trials x n_features).
If |
labels |
Character or factor vector of class labels, one per trial. Must contain exactly two unique classes. |
method |
Classification method: |
cv_folds |
Number of cross-validation folds (default: |
assay_name |
Input assay name used when extracting features (default: first assay). |
A data.frame with columns: trial, predicted_class,
confidence, and true_class. When cv_folds is not
NULL, predictions are out-of-fold and attr(result,
"cv_accuracy") contains the cross-validated accuracy. The trained LDA
model (on all data) is stored in metadata(x)$bci_model,
containing weights, threshold, classes,
method, and class_means.
Blankertz, B., et al. (2008). Optimizing spatial filters for robust EEG single-trial analysis. IEEE Signal Processing Magazine, 25(1), 41-56.
eegCSP(), eegBCIfeatures(), eegMotorImagery()
pe <- make_eeg_bci(n_trials = 20, n_channels = 8, sr = 256) labels <- S4Vectors::metadata(pe)$labels features <- eegBCIfeatures(pe, method = "bandpower") result <- eegBCIclassify(pe, features = features, labels = labels, method = "lda") # With 5-fold cross-validation result_cv <- eegBCIclassify(pe, features = features, labels = labels, method = "lda", cv_folds = 5) attr(result_cv, "cv_accuracy")pe <- make_eeg_bci(n_trials = 20, n_channels = 8, sr = 256) labels <- S4Vectors::metadata(pe)$labels features <- eegBCIfeatures(pe, method = "bandpower") result <- eegBCIclassify(pe, features = features, labels = labels, method = "lda") # With 5-fold cross-validation result_cv <- eegBCIclassify(pe, features = features, labels = labels, method = "lda", cv_folds = 5) attr(result_cv, "cv_accuracy")
Extracts features from epoched EEG data for Brain-Computer Interface classification. Supports band power, CSP, and Riemannian geometry methods.
eegBCIfeatures( x, method = c("bandpower", "csp", "riemannian"), labels = NULL, bands = NULL, assay_name = NULL )eegBCIfeatures( x, method = c("bandpower", "csp", "riemannian"), labels = NULL, bands = NULL, assay_name = NULL )
x |
A PhysioExperiment object with epoched (3D) EEG data (time x channels x trials). |
method |
Feature extraction method: |
labels |
Character or factor vector of class labels (required for
|
bands |
Named list of frequency bands for |
assay_name |
Input assay name (default: first assay). |
A numeric matrix with n_trials rows and feature columns.
Number of columns depends on method:
"bandpower": n_channels * n_bands
"csp": 2 * n_filters (default: 6)
"riemannian": n_channels * (n_channels + 1) / 2
Blankertz, B., et al. (2008). Optimizing spatial filters for robust EEG single-trial analysis. IEEE Signal Processing Magazine, 25(1), 41-56.
eegCSP(), eegMotorImagery(), eegBCIclassify()
pe <- make_eeg_bci(n_trials = 20, n_channels = 8, sr = 256) features <- eegBCIfeatures(pe, method = "bandpower")pe <- make_eeg_bci(n_trials = 20, n_channels = 8, sr = 256) features <- eegBCIfeatures(pe, method = "bandpower")
Applies spatial filtering (beamforming) to localize neural source power. Linearly Constrained Minimum Variance (LCMV) beamformer operates in the time domain. Dynamic Imaging of Coherent Sources (DICS) operates in the frequency domain.
eegBeamformer( x, forward_model, method = c("lcmv", "dics"), freq_range = NULL, assay_name = NULL, output_assay = "beamformer" )eegBeamformer( x, forward_model, method = c("lcmv", "dics"), freq_range = NULL, assay_name = NULL, output_assay = "beamformer" )
x |
A PhysioExperiment object with EEG data. |
forward_model |
A forward model list as returned by
|
method |
Beamformer method: |
freq_range |
Numeric vector of length 2 specifying frequency range
in Hz for DICS method (e.g., |
assay_name |
Name of the input assay. If |
output_assay |
Name for the output assay containing beamformer
results (default: |
Modified PhysioExperiment with source power stored in
output_assay as a matrix with one column named "power"
(n_sources rows). Each value represents the estimated source power
at the corresponding dipole location. Plotting metadata, including source
positions, the output name, method, and coordinate provenance, is stored
in metadata(x)$beamformer_info.
Pascual-Marqui, R. D. (2002). Standardized low-resolution brain electromagnetic tomography (sLORETA). Methods and Findings in Experimental and Clinical Pharmacology, 24(Suppl D), 5-12.
Van Veen, B. D., et al. (1997). Localization of brain electrical activity via linearly constrained minimum variance spatial filtering. IEEE Transactions on Biomedical Engineering, 44(9), 867-880.
eegForwardModel(), eegSourceEstimate(), eegSourcePower(),
eegPlotGlassBrain()
pe <- make_eeg(n_time = 1000, n_channels = 19, sr = 250) fm <- eegForwardModel(pe, method = "spherical", n_sources = 50) pe <- eegBeamformer(pe, fm, method = "lcmv")pe <- make_eeg(n_time = 1000, n_channels = 19, sr = 250) fm <- eegForwardModel(pe, method = "spherical", n_sources = 50) pe <- eegBeamformer(pe, fm, method = "lcmv")
Quantifies left/right spectral asymmetry across hemispheric electrode pairs, a
quantitative-EEG stroke marker (van Putten 2007; Sheorajpanday et al. 2011).
The global bsi is the spectrum-averaged absolute relative difference
between summed right- and left-hemisphere power, bounded from 0 (symmetric) to
1 (one hemisphere silent). The pairwise-derived pdbsi averages the same
relative difference per hemispheric pair; with directed = TRUE it keeps
the sign (positive = right-dominant). Both are returned as
reliability-characterised physioBiomarker objects
with provenance and, for the global BSI, a normative reference range.
eegBSI( x, pairs = NULL, band = c(1, 25), directed = FALSE, method = "welch", age = NULL, montage = NULL, reliability = list(icc = NA_real_, sem = NA_real_), assay_name = NULL )eegBSI( x, pairs = NULL, band = c(1, 25), directed = FALSE, method = "welch", age = NULL, montage = NULL, reliability = list(icc = NA_real_, sem = NA_real_), assay_name = NULL )
x |
A PhysioExperiment object with 2D EEG data. |
pairs |
List of length-2 character vectors, each a |
band |
Numeric length-2 frequency band in Hz (default: |
directed |
Logical; when |
method |
Spectral estimator (default: |
age |
Optional numeric age for the normative lookup. |
montage |
Optional character montage for the normative lookup. |
reliability |
Named list of reliability indices to attach (default:
|
assay_name |
Input assay name (default: the default assay). |
A named list with two PhysioBiomarker
objects: bsi (global, from 0 to 1) and pdbsi
(pairwise-derived, signed when directed = TRUE).
van Putten, M. J. A. M. (2007). The revised brain symmetry index. Clinical Neurophysiology, 118(11), 2362-2367.
Sheorajpanday, R. V. A., et al. (2011). Quantitative EEG in ischemic stroke: correlation with functional status after 6 months. Clinical Neurophysiology, 122(5), 874-883.
eegDAR(), eegAsymmetry(), PhysioExperiment::physioBiomarker()
pe <- make_eeg(n_time = 5000, n_channels = 19, sr = 250) res <- eegBSI(pe, age = 60) res$bsipe <- make_eeg(n_time = 5000, n_channels = 19, sr = 250) res <- eegBSI(pe, age = 60) res$bsi
Computes magnitude-squared coherence (MSC) or imaginary part of coherency between all EEG channel pairs using Welch's method. The signal is segmented into overlapping windows, each windowed with a Hanning function, and the cross-spectral density is averaged across windows.
eegCoherence( x, method = c("coherence", "imaginary"), window_sec = 2, overlap = 0.5, band = c(8, 13), assay_name = NULL )eegCoherence( x, method = c("coherence", "imaginary"), window_sec = 2, overlap = 0.5, band = c(8, 13), assay_name = NULL )
x |
A PhysioExperiment object with EEG data (2D: time x channels). |
method |
Coherence method: |
window_sec |
Window length in seconds for Welch's method (default: 2). |
overlap |
Overlap fraction between adjacent windows, from 0 to 1 exclusive (default: 0.5). |
band |
Numeric vector of length 2 specifying the frequency band in Hz
over which to average coherence (default: |
assay_name |
Name of the input assay. If |
Magnitude-squared coherence is defined as:
Imaginary coherence uses the imaginary part of coherency to reduce volume conduction artifacts:
The input PhysioExperiment with connectivity results stored in
metadata(x)$connectivity, a list containing:
Numeric n_channels x n_channels matrix of band-averaged coherence values.
Character string indicating the method used.
Numeric vector of the frequency band used.
Numeric vector of frequency bins.
3D array (n_freqs x n_channels x n_channels) of frequency-resolved coherence values.
Lachaux, J. P., et al. (1999). Measuring phase synchrony in brain signals. Human Brain Mapping, 8(4), 194-208.
eegPLV(), eegWPLI(), eegConnectivityMatrix(),
eegPlotConnectivity()
pe <- make_eeg(n_time = 5000, n_channels = 4, sr = 500) pe <- eegCoherence(pe, method = "coherence", band = c(8, 13)) coh_matrix <- S4Vectors::metadata(pe)$connectivity$matrixpe <- make_eeg(n_time = 5000, n_channels = 4, sr = 500) pe <- eegCoherence(pe, method = "coherence", band = c(8, 13)) coh_matrix <- S4Vectors::metadata(pe)$connectivity$matrix
Computes phase-amplitude coupling over a grid of phase and amplitude
frequencies for one EEG channel, yielding a comodulogram whose peak locates
the dominant coupling. Delegates to PhysioCrossModal::comodulogram().
eegComodulogram( pe, channel = 1L, phase_freqs = seq(2, 14, by = 2), amp_freqs = seq(20, 100, by = 10), method = c("tort", "canolty", "ozkurt", "plv"), phase_bw = 2, amp_bw = 10, n_bins = 18L, assay_name = NULL )eegComodulogram( pe, channel = 1L, phase_freqs = seq(2, 14, by = 2), amp_freqs = seq(20, 100, by = 10), method = c("tort", "canolty", "ozkurt", "plv"), phase_bw = 2, amp_bw = 10, n_bins = 18L, assay_name = NULL )
pe |
A |
channel |
Channel (index or label) to analyse. |
phase_freqs |
Phase centre frequencies in Hz (default |
amp_freqs |
Amplitude centre frequencies in Hz (default |
method |
PAC estimator (see |
phase_bw, amp_bw
|
Half-bandwidths in Hz (defaults 2 and 10). |
n_bins |
Phase bins for the Tort modulation index (default 18). |
assay_name |
Assay to use (default: the object's default assay). |
The comodulogram list from PhysioCrossModal::comodulogram() (a
matrix of phase x amplitude frequencies, plus its peak).
if (requireNamespace("PhysioCrossModal", quietly = TRUE)) { pe <- make_eeg(n_time = 7500, n_channels = 2, sr = 250) cm <- eegComodulogram(pe, channel = 1) cm$peak }if (requireNamespace("PhysioCrossModal", quietly = TRUE)) { pe <- make_eeg(n_time = 7500, n_channels = 2, sr = 250) cm <- eegComodulogram(pe, channel = 1) cm$peak }
Computes per-channel entropy, fractal-dimension and detrended-fluctuation complexity measures — the nonlinear family that complements the spectral, connectivity and source tools. For epoched (3-D) data each measure is computed per epoch and averaged across epochs.
eegComplexity( pe, measures = c("sample_entropy", "permutation_entropy", "lempel_ziv", "higuchi_fd", "dfa", "hjorth_mobility", "spectral_entropy"), assay_name = NULL, m = 2L, r = 0.2, tau = 1L, perm_order = 3L, mse_scales = 1:8, max_samples = 4000L )eegComplexity( pe, measures = c("sample_entropy", "permutation_entropy", "lempel_ziv", "higuchi_fd", "dfa", "hjorth_mobility", "spectral_entropy"), assay_name = NULL, m = 2L, r = 0.2, tau = 1L, perm_order = 3L, mse_scales = 1:8, max_samples = 4000L )
pe |
A |
measures |
Character vector of measures to compute (see Details). |
assay_name |
Assay to use (default: the object's default assay). |
m |
Embedding dimension for the entropy measures (default 2; permutation
entropy uses |
r |
Tolerance as a fraction of each channel's SD for sample/approximate/ multiscale entropy (default 0.2). |
tau |
Time delay for permutation entropy (default 1). |
perm_order |
Embedding order for permutation entropy (default 3). |
mse_scales |
Scales for multiscale entropy (default |
max_samples |
Cap on samples per channel/epoch for the O(N^2) entropy
measures; longer series are truncated with a warning (default 4000; |
Available measures: "sample_entropy" (Richman–Moorman), "approximate_entropy"
(Pincus), "permutation_entropy" (Bandt–Pompe), "multiscale_entropy" (Costa;
returns the scale-averaged SampEn as a summary plus the per-scale curve in the
attribute), "lempel_ziv" (Kaspar–Schuster), "higuchi_fd", "katz_fd",
"dfa" (scaling exponent alpha), "hurst" (R/S), "hjorth_mobility",
"hjorth_complexity", "spectral_entropy".
A data frame with one row per channel and one column per requested
measure (plus a channel column). The multiscale-entropy per-scale curves
are attached as attr(, "mse_scales") / attr(, "mse_curve").
Richman & Moorman 2000; Bandt & Pompe 2002; Costa 2002; Higuchi 1988; Katz 1988; Peng 1994; Hjorth 1970.
pe <- make_eeg(n_time = 512, n_channels = 4, sr = 128) cx <- eegComplexity(pe, measures = c("permutation_entropy", "hjorth_mobility", "spectral_entropy")) cxpe <- make_eeg(n_time = 512, n_channels = 4, sr = 128) cx <- eegComplexity(pe, measures = c("permutation_entropy", "hjorth_mobility", "spectral_entropy")) cx
Computes conditional Granger causality from source to target
given a set of conditioning channels, using the log ratio of the
target's residual variance in a VAR fitted without the source
(target + conditioning) versus with it
(target + source + conditioning); both VARs share the same order
(Geweke; Barnett & Seth 2014). Unlike the pairwise eegGrangerCausality(),
conditioning removes indirect influences, so for a chain the conditional GC
along a purely indirect path is near zero.
eegConditionalGC( x, target, source, conditioning = NULL, order = NULL, method = "ols", assay_name = NULL )eegConditionalGC( x, target, source, conditioning = NULL, order = NULL, method = "ols", assay_name = NULL )
x |
A PhysioExperiment object with 2D EEG data (time x channels). |
target |
Target channel (label or index) - the effect. |
source |
Source channel (label or index) - the putative cause. |
conditioning |
Channels to condition on (labels or indices). Defaults to all remaining channels. |
order |
MVAR model order, or |
method |
MVAR estimator passed to |
assay_name |
Input assay name (default: the default assay). |
A list with the conditional GC value (in nats, non-negative in
theory), the target, source, and conditioning labels,
and the VAR order used.
Barnett, L., & Seth, A. K. (2014). The MVGC multivariate Granger causality toolbox. Journal of Neuroscience Methods, 223, 50-68.
eegGrangerCausality(), eegDTF(), eegPDC()
pe <- make_eeg(n_time = 4000, n_channels = 3, sr = 250) eegConditionalGC(pe, target = 3, source = 1, conditioning = 2)pe <- make_eeg(n_time = 4000, n_channels = 3, sr = 250) eegConditionalGC(pe, target = 3, source = 1, conditioning = 2)
Convenience wrapper that computes a symmetric n_channels x n_channels connectivity matrix using the specified method. Dispatches to the appropriate connectivity function and returns a named matrix suitable for visualization or graph-theoretic analysis.
eegConnectivityMatrix( x, method = c("coherence", "plv", "wpli", "dtf", "pdc"), band = c(8, 13), ... )eegConnectivityMatrix( x, method = c("coherence", "plv", "wpli", "dtf", "pdc"), band = c(8, 13), ... )
x |
A PhysioExperiment object with EEG data (2D: time x channels). |
method |
Connectivity method: |
band |
Numeric vector of length 2 specifying the frequency band in Hz
(default: |
... |
Additional arguments passed to the underlying connectivity
function (e.g., |
A named numeric matrix of dimension n_channels x n_channels with channel labels as row and column names. Diagonal elements are 1. Off-diagonal elements represent the band-averaged connectivity between channel pairs.
Lachaux, J. P., et al. (1999). Measuring phase synchrony in brain signals. Human Brain Mapping, 8(4), 194-208.
eegCoherence(), eegPLV(), eegWPLI(),
eegGrangerCausality(), eegPlotConnectivity()
pe <- make_eeg(n_time = 5000, n_channels = 4, sr = 500) conn <- eegConnectivityMatrix(pe, method = "plv", band = c(8, 13)) print(conn)pe <- make_eeg(n_time = 5000, n_channels = 4, sr = 500) conn <- eegConnectivityMatrix(pe, method = "plv", band = c(8, 13)) print(conn)
Computes Common Spatial Pattern filters for two-class EEG discrimination. CSP maximizes the variance ratio between two conditions, making it a standard spatial filtering technique for motor imagery BCI.
eegCSP(x, labels, n_filters = 3, assay_name = NULL, output_assay = "csp")eegCSP(x, labels, n_filters = 3, assay_name = NULL, output_assay = "csp")
x |
A PhysioExperiment object with epoched (3D) EEG data (time x channels x trials). |
labels |
Character or factor vector of class labels, one per trial. Must contain exactly two unique classes. |
n_filters |
Number of CSP filter pairs to retain (default: 3).
The total number of spatial filters will be |
assay_name |
Input assay name (default: first assay). |
output_assay |
Name the result is stored under. Despite the
argument's name this is a key in |
Modified PhysioExperiment with CSP log-variance features in
output_assay (a matrix of trials x 2 * n_filters) and
CSP filter information stored in metadata(x)$csp as a list
containing filters (spatial filter matrix), eigenvalues
(selected eigenvalues), and classes (unique class labels).
Blankertz, B., et al. (2008). Optimizing spatial filters for robust EEG single-trial analysis. IEEE Signal Processing Magazine, 25(1), 41-56.
eegBCIfeatures(), eegBCIclassify(), eegMotorImagery()
pe <- make_eeg_bci(n_trials = 30, n_channels = 8, sr = 256) labels <- S4Vectors::metadata(pe)$labels result <- eegCSP(pe, labels = labels, n_filters = 3) # CSP filters and log-variance features are stored in metadata csp_features <- S4Vectors::metadata(result)$csp_features dim(csp_features) # trials x (2 * n_filters)pe <- make_eeg_bci(n_trials = 30, n_channels = 8, sr = 256) labels <- S4Vectors::metadata(pe)$labels result <- eegCSP(pe, labels = labels, n_filters = 3) # CSP filters and log-variance features are stored in metadata csp_features <- S4Vectors::metadata(result)$csp_features dim(csp_features) # trials x (2 * n_filters)
Computes the delta-to-alpha band-power ratio per channel (or per region), a
quantitative-EEG stroke marker whose elevation tracks ischaemic slowing
(Finnigan et al. 2016). Band powers use a Welch estimator for a stable
spectrum. Each ratio is returned as a reliability-characterised
physioBiomarker carrying provenance (band, method,
software version), reliability placeholders, and - when age (and montage) are
supplied - a published reference range from
normativeLookup so the value prints its normative
percentile.
eegDAR( x, delta = c(1, 4), alpha = c(8, 13), regions = NULL, method = "welch", age = NULL, montage = NULL, reliability = list(icc = NA_real_, sem = NA_real_), assay_name = NULL )eegDAR( x, delta = c(1, 4), alpha = c(8, 13), regions = NULL, method = "welch", age = NULL, montage = NULL, reliability = list(icc = NA_real_, sem = NA_real_), assay_name = NULL )
x |
A PhysioExperiment object with 2D EEG data. |
delta |
Numeric length-2 delta band in Hz (default: |
alpha |
Numeric length-2 alpha band in Hz (default: |
regions |
Optional named list mapping a region name to a character
vector of channel labels; band powers are averaged within each region. When
|
method |
Spectral estimator passed to the band-power routine
(default: |
age |
Optional numeric age used to select the normative reference row. |
montage |
Optional character montage for the normative lookup. |
reliability |
Named list of reliability indices to attach (default:
|
assay_name |
Input assay name (default: the default assay). |
A named list of PhysioBiomarker objects, one
per channel or region.
Finnigan, S., Wong, A., & Read, S. (2016). Defining abnormal slow EEG activity in acute ischaemic stroke: Delta/alpha ratio as an optimal QEEG index. Clinical Neurophysiology, 127(2), 1452-1459.
eegBSI(), eegSlowing(), eegQEEG(),
PhysioExperiment::physioBiomarker(), PhysioExperiment::normativeLookup()
pe <- make_eeg(n_time = 5000, n_channels = 19, sr = 250) dar <- eegDAR(pe, age = 60) dar[["C3"]]pe <- make_eeg(n_time = 5000, n_channels = 19, sr = 250) dar <- eegDAR(pe, age = 60) dar[["C3"]]
Decodes trial class labels from epoched EEG with a strictly fold-safe pipeline: the spatial filter (CSP), feature extraction, feature scaling and classifier are all estimated on the training fold only and applied, frozen, to the test fold (Varoquaux et al., 2017). This avoids the label/data leakage of fitting CSP or scaling on the full dataset before cross-validation. Folds may respect a run/block grouping to avoid temporally-contiguous-epoch leakage.
eegDecode( x, labels = NULL, pipeline = c("csp+lda", "bandpower+lda", "riemannian"), cv = c("stratified-kfold", "leave-one-run-out"), n_folds = 5, groups = NULL, n_permutations = 200, inner_cv = NULL, assay_name = NULL, n_csp = 3, bands = NULL, seed = NULL )eegDecode( x, labels = NULL, pipeline = c("csp+lda", "bandpower+lda", "riemannian"), cv = c("stratified-kfold", "leave-one-run-out"), n_folds = 5, groups = NULL, n_permutations = 200, inner_cv = NULL, assay_name = NULL, n_csp = 3, bands = NULL, seed = NULL )
x |
A PhysioExperiment with an epoched (3D: time x channels x trials) assay. |
labels |
Class labels, one per trial. If |
pipeline |
Decoding pipeline: |
cv |
Cross-validation scheme: |
n_folds |
Number of folds for k-fold CV (default: 5). |
groups |
Optional run/block grouping (one per trial); folds keep each group intact so contiguous epochs are never split across train/test. |
n_permutations |
Number of label permutations for the null distribution and p-value (default: 200; 0 to skip). |
inner_cv |
Optional number of inner CV folds for nested hyperparameter
selection (shrinkage LDA vs plain LDA). |
assay_name |
Input assay (default: |
n_csp |
Number of CSP filter pairs for |
bands |
Named list of frequency bands for |
seed |
Optional RNG seed for reproducible fold assignment/permutations. |
A list of class "eeg_decode" with:
pooled out-of-fold accuracy.
95 percent Wilson confidence interval for the accuracy.
per-fold accuracy.
binary area under the ROC curve.
confusion matrix (true x predicted).
list with p_value, null_accuracy,
n_permutations.
a data.frame (trial, fold, true, predicted,
score).
per-fold CSP filters ("csp+lda" only).
Varoquaux, G., et al. (2017). "Assessing and tuning brain decoders: cross-validation, caveats, and guidelines." NeuroImage, 145, 166-179. doi:10.1016/j.neuroimage.2016.10.038
Lemm, S., et al. (2011). "Introduction to machine learning for brain imaging." NeuroImage, 56(2), 387-399. doi:10.1016/j.neuroimage.2010.11.004
eegCSP, eegBCIfeatures. The older
eegBCIclassify cross-validation path is leakage-prone and
deprecated in favour of eegDecode.
pe <- make_eeg_bci(n_trials = 20, n_channels = 8, sr = 128, trial_sec = 3) res <- eegDecode(pe, pipeline = "csp+lda", n_permutations = 0, seed = 1) res$accuracype <- make_eeg_bci(n_trials = 20, n_channels = 8, sr = 128, trial_sec = 3) res <- eegDecode(pe, pipeline = "csp+lda", n_permutations = 0, seed = 1) res$accuracy
Localizes the single equivalent current dipole that best explains a scalp
topography, by nonlinearly optimizing the dipole position (a grid search
inside the head sphere refined with Nelder-Mead) while the dipole moment is
the closed-form least-squares fit at each candidate position. Uses the same
forward physics as eegForwardModel() and the electrode positions from
colData / the montage. This is the classic focal-source complement to the
distributed inverses in eegSourceEstimate().
eegDipoleFit( x, time = NULL, method = c("spherical", "bem_simplified"), n_grid = 8L, assay_name = NULL )eegDipoleFit( x, time = NULL, method = c("spherical", "bem_simplified"), n_grid = 8L, assay_name = NULL )
x |
A |
time |
Sample index to fit (a single index), a length-2 range to average
over, or |
method |
Forward physics: |
n_grid |
Grid resolution per axis for the initial search (default 8). |
assay_name |
Assay to use (default: the object's default assay). |
An eeg_dipole_fit object: position (x, y, z in normalized head
radius), moment, orientation (unit), amplitude, gof (goodness of
fit, variance explained), residual, and the fitted/observed topographies.
Scherg (1990); Mosher, Lewis & Leahy (1992).
eegSourceEstimate(), eegForwardModel()
pe <- make_eeg(n_time = 100, n_channels = 19, sr = 100) fit <- eegDipoleFit(pe) fit$gofpe <- make_eeg(n_time = 100, n_channels = 19, sr = 100) fit <- eegDipoleFit(pe) fit$gof
Estimates frequency-resolved directed connectivity between EEG channels with
the Directed Transfer Function (Kaminski & Blinowska 1991), computed from the
transfer function of a multivariate autoregressive (MVAR) model
fitted with PhysioExperiment::mvarFit(). Because inverts the whole VAR
system, DTF reflects both direct and indirect pathways. The (default)
normalized DTF satisfies for each
target (inflow normalization); ffDTF normalizes across all
frequencies instead (Korzeniewska 2003).
eegDTF( x, order = NULL, freqs = NULL, normalized = TRUE, ffDTF = FALSE, band = NULL, method = "ols", assay_name = NULL )eegDTF( x, order = NULL, freqs = NULL, normalized = TRUE, ffDTF = FALSE, band = NULL, method = "ols", assay_name = NULL )
x |
A PhysioExperiment object with 2D EEG data (time x channels). |
order |
MVAR model order, or |
freqs |
Numeric vector of frequencies in Hz (default: 128 points from 0 to the Nyquist frequency). |
normalized |
Row-normalize the DTF (default: |
ffDTF |
Use the full-frequency DTF normalization (default: |
band |
Optional numeric length-2 band in Hz over which to average the stored connectivity matrix (default: all frequencies). |
method |
MVAR estimator passed to |
assay_name |
Input assay name (default: the default assay). |
The PhysioExperiment with metadata(x)$connectivity set to a
list containing the band-averaged directed matrix (rows = targets,
columns = sources), the frequency-resolved array
(n_channels x n_channels x n_freqs), the frequencies, and the
settings used.
Kaminski, M. J., & Blinowska, K. J. (1991). A new method of the description of the information flow in the brain structures. Biological Cybernetics, 65(3), 203-210.
eegPDC(), eegConditionalGC(), eegConnectivityMatrix(),
PhysioExperiment::mvarFit()
pe <- make_eeg(n_time = 4000, n_channels = 5, sr = 250) pe <- eegDTF(pe, order = 5) dim(S4Vectors::metadata(pe)$connectivity$array)pe <- make_eeg(n_time = 4000, n_channels = 5, sr = 250) pe <- eegDTF(pe, order = 5) dim(S4Vectors::metadata(pe)$connectivity$array)
Segments continuous 2D EEG data into fixed-length epochs around events, producing a 3D array (time x channels x epochs). Optionally performs baseline correction by subtracting the mean of a pre-stimulus window.
eegEpoch( x, events, limits = c(-0.2, 0.8), baseline = c(-0.2, 0), assay_name = NULL, output_assay = "epoched" )eegEpoch( x, events, limits = c(-0.2, 0.8), baseline = c(-0.2, 0), assay_name = NULL, output_assay = "epoched" )
x |
A PhysioExperiment object with continuous (2D) data. |
events |
A data.frame with an |
limits |
Numeric vector of length 2 specifying the epoch window
relative to each event in seconds (default: |
baseline |
Numeric vector of length 2 specifying the baseline window
relative to each event in seconds (default: |
assay_name |
Name of the assay to epoch. If NULL, uses
|
output_assay |
Name of the output assay (default: |
A PhysioExperiment object with a 3D array (time x channels x epochs)
in the specified output assay. Event information is stored in
metadata(x)$epoch_events.
pe <- make_eeg(n_time = 10000, n_channels = 19, sr = 500) events <- data.frame(onset_sec = c(1.0, 3.0, 5.0, 7.0)) pe_ep <- eegEpoch(pe, events, limits = c(-0.2, 0.8)) # the epoched array is stored in metadata(x)$epoched dim(S4Vectors::metadata(pe_ep)$epoched) # time x channels x epochspe <- make_eeg(n_time = 10000, n_channels = 19, sr = 500) events <- data.frame(onset_sec = c(1.0, 3.0, 5.0, 7.0)) pe_ep <- eegEpoch(pe, events, limits = c(-0.2, 0.8)) # the epoched array is stored in metadata(x)$epoched dim(S4Vectors::metadata(pe_ep)$epoched) # time x channels x epochs
Subtracts the mean amplitude of a pre-stimulus baseline period from each epoch. This is an essential preprocessing step before ERP measurement.
eegERPbaseline( x, baseline = c(-200, 0), epoch_start = 0, assay_name = NULL, output_assay = "baseline_corrected" )eegERPbaseline( x, baseline = c(-200, 0), epoch_start = 0, assay_name = NULL, output_assay = "baseline_corrected" )
x |
A PhysioExperiment object with epoched (3D) EEG data. |
baseline |
Baseline period in milliseconds as |
epoch_start |
Start time of the epoch in milliseconds relative to stimulus onset. Default is 0 (epoch starts at stimulus). |
assay_name |
Input assay name (default: first assay). |
output_assay |
Output assay name (default: |
Modified PhysioExperiment with baseline-corrected data in
output_assay. Creates a new 3D assay (time x channels x epochs)
where each epoch has had the mean of its baseline period subtracted.
Luck, S. J. (2014). An Introduction to the Event-Related Potential Technique (2nd ed.). MIT Press.
eegERPdetect(), eegERPmeasure(), eegEpoch(),
eegFilter()
pe <- make_eeg_erp(n_epochs = 40, sr = 250) result <- eegERPbaseline(pe, baseline = c(-200, 0), epoch_start = -200)pe <- make_eeg_erp(n_epochs = 40, sr = 250) result <- eegERPbaseline(pe, baseline = c(-200, 0), epoch_start = -200)
Detects known event-related potential (ERP) components in epoched (3D) EEG data. Averages across epochs and finds peaks within predefined time windows.
eegERPdetect( x, component = c("N100", "P300", "N400", "P600", "MMN", "LPP"), channels = NULL, epoch_start = 0, assay_name = NULL )eegERPdetect( x, component = c("N100", "P300", "N400", "P600", "MMN", "LPP"), channels = NULL, epoch_start = 0, assay_name = NULL )
x |
A PhysioExperiment object with epoched (3D) EEG data. |
component |
ERP component to detect: |
channels |
Character vector of channel labels to analyze. If |
epoch_start |
Start time of the epoch in milliseconds relative to stimulus onset. Default is 0 (epoch starts at stimulus). |
assay_name |
Input assay name (default: first assay). |
A data.frame with columns: channel (character label),
component (character name), latency_ms (numeric peak
latency in milliseconds), and amplitude (numeric peak amplitude).
Luck, S. J. (2014). An Introduction to the Event-Related Potential Technique (2nd ed.). MIT Press.
eegERPmeasure(), eegERPlatency(), eegERPbaseline(),
eegEpoch(), eegPlotERP()
pe <- make_eeg_erp(n_epochs = 40, sr = 250) result <- eegERPdetect(pe, component = "P300")pe <- make_eeg_erp(n_epochs = 40, sr = 250) result <- eegERPdetect(pe, component = "P300")
Computes the difference waveform between two PhysioExperiment objects by
subtracting the assay data of y from x.
eegERPdifference(x, y, assay_name = NULL, output_assay = "difference")eegERPdifference(x, y, assay_name = NULL, output_assay = "difference")
x |
A PhysioExperiment object (minuend). |
y |
A PhysioExperiment object (subtrahend). Must have the same
dimensions as |
assay_name |
Input assay name (default: first assay). |
output_assay |
Output assay name (default: |
Modified x with difference waveform stored in
output_assay. The difference assay has the same dimensions as
the input assay.
Luck, S. J. (2014). An Introduction to the Event-Related Potential Technique (2nd ed.). MIT Press.
eegERPdetect(), eegERPmeasure(), eegERPtest(),
eegERPgrandAverage()
pe1 <- make_eeg_erp(n_epochs = 20, sr = 250) pe2 <- make_eeg_erp(n_epochs = 20, sr = 250) result <- eegERPdifference(pe1, pe2)pe1 <- make_eeg_erp(n_epochs = 20, sr = 250) pe2 <- make_eeg_erp(n_epochs = 20, sr = 250) result <- eegERPdifference(pe1, pe2)
Averages ERP waveforms across multiple PhysioExperiment objects (participants). Each input should already be averaged across trials.
eegERPgrandAverage(..., assay_name = NULL, output_assay = "grand_average")eegERPgrandAverage(..., assay_name = NULL, output_assay = "grand_average")
... |
PhysioExperiment objects to average, or a list of them. |
assay_name |
Input assay name (default: first assay). |
output_assay |
Output assay name (default: |
A PhysioExperiment (the first input object) with the grand average
waveform stored in output_assay. The grand average assay has the
same dimensions as the input assays.
Luck, S. J. (2014). An Introduction to the Event-Related Potential Technique (2nd ed.). MIT Press.
eegERPdetect(), eegERPmeasure(), eegERPtest(),
eegERPdifference()
pe1 <- make_eeg_erp(n_epochs = 20, sr = 250) pe2 <- make_eeg_erp(n_epochs = 20, sr = 250) result <- eegERPgrandAverage(pe1, pe2)pe1 <- make_eeg_erp(n_epochs = 20, sr = 250) pe2 <- make_eeg_erp(n_epochs = 20, sr = 250) result <- eegERPgrandAverage(pe1, pe2)
Computes the fractional area latency of an ERP component. This is the time point at which a specified fraction of the total area under the curve (in the given window) has accumulated.
eegERPlatency( x, window, fraction = 0.5, polarity = c("positive", "negative"), epoch_start = 0, assay_name = NULL )eegERPlatency( x, window, fraction = 0.5, polarity = c("positive", "negative"), epoch_start = 0, assay_name = NULL )
x |
A PhysioExperiment object with EEG data. |
window |
Numeric vector of length 2: |
fraction |
Fraction of total area (default: 0.5 for median latency). |
polarity |
Expected polarity: |
epoch_start |
Start time of the epoch in milliseconds relative to stimulus onset. Default is 0 (epoch starts at stimulus). |
assay_name |
Input assay name (default: first assay). |
A data.frame with columns: channel (character label),
latency_ms (numeric fractional area latency in milliseconds),
and fraction (numeric fraction used).
Luck, S. J. (2014). An Introduction to the Event-Related Potential Technique (2nd ed.). MIT Press.
eegERPdetect(), eegERPmeasure(), eegERPbaseline(),
eegPlotERP()
pe <- make_eeg_erp(n_epochs = 40, sr = 250) result <- eegERPlatency(pe, window = c(250, 500), fraction = 0.5, polarity = "positive")pe <- make_eeg_erp(n_epochs = 40, sr = 250) result <- eegERPlatency(pe, window = c(250, 500), fraction = 0.5, polarity = "positive")
Measures ERP amplitude in a specified time window using peak, mean, or adaptive mean methods. For epoched (3D) data, averages across epochs first.
eegERPmeasure( x, window, method = c("peak", "mean", "adaptive_mean"), polarity = c("positive", "negative"), epoch_start = 0, assay_name = NULL )eegERPmeasure( x, window, method = c("peak", "mean", "adaptive_mean"), polarity = c("positive", "negative"), epoch_start = 0, assay_name = NULL )
x |
A PhysioExperiment object with EEG data. |
window |
Numeric vector of length 2: |
method |
Measurement method: |
polarity |
Expected polarity: |
epoch_start |
Start time of the epoch in milliseconds relative to stimulus onset. Default is 0 (epoch starts at stimulus). |
assay_name |
Input assay name (default: first assay). |
A data.frame with columns: channel (character label),
amplitude (numeric measured amplitude), latency_ms
(numeric latency in milliseconds), and method (character
measurement method used).
Luck, S. J. (2014). An Introduction to the Event-Related Potential Technique (2nd ed.). MIT Press.
eegERPdetect(), eegERPlatency(), eegERPbaseline(),
eegPlotERP()
pe <- make_eeg_erp(n_epochs = 40, sr = 250) result <- eegERPmeasure(pe, window = c(250, 500), method = "peak", polarity = "positive")pe <- make_eeg_erp(n_epochs = 40, sr = 250) result <- eegERPmeasure(pe, window = c(250, 500), method = "peak", polarity = "positive")
Performs permutation testing or cluster-based permutation testing to compare ERP waveforms between conditions.
eegERPtest( x, y, method = c("permutation", "cluster"), n_perm = 1000, alpha = 0.05, cluster_alpha = 0.05, assay_name = NULL )eegERPtest( x, y, method = c("permutation", "cluster"), n_perm = 1000, alpha = 0.05, cluster_alpha = 0.05, assay_name = NULL )
x |
A PhysioExperiment with epoched data for condition 1. |
y |
A PhysioExperiment with epoched data for condition 2. |
method |
Test method: |
n_perm |
Number of permutations (default: 1000). |
alpha |
Significance level (default: 0.05). |
cluster_alpha |
Cluster-forming threshold for individual t-tests
(default: 0.05). Only used for |
assay_name |
Input assay name (default: first assay). |
A data.frame with columns: time_sample (integer),
t_statistic (numeric observed t-value), p_value
(numeric permutation-based p-value), and significant (logical).
For the "cluster" method, also includes cluster_id
(integer cluster assignment) and cluster_p (numeric cluster-level
corrected p-value).
Luck, S. J. (2014). An Introduction to the Event-Related Potential Technique (2nd ed.). MIT Press.
Maris, E., & Oostenveld, R. (2007). Nonparametric statistical testing of EEG- and MEG-data. Journal of Neuroscience Methods, 164(1), 177-190.
eegERPdetect(), eegERPmeasure(), eegERPdifference(),
eegERPgrandAverage()
pe1 <- make_eeg_erp(n_epochs = 20, sr = 250) pe2 <- make_eeg_erp(n_epochs = 20, sr = 250) result <- eegERPtest(pe1, pe2, method = "permutation", n_perm = 500)pe1 <- make_eeg_erp(n_epochs = 20, sr = 250) pe2 <- make_eeg_erp(n_epochs = 20, sr = 250) result <- eegERPtest(pe1, pe2, method = "permutation", n_perm = 500)
Computes Event-Related Spectral Perturbation for epoched (3D) EEG data. ERSP quantifies event-related changes in spectral power relative to a baseline period, expressed in decibels (dB). Uses the Morlet wavelet transform to compute time-frequency decomposition for each epoch, then averages power across epochs and normalizes to baseline.
eegERSP( x, baseline = c(1, 50), frequencies = NULL, n_cycles = 7, assay_name = NULL, output_assay = "ersp_data" )eegERSP( x, baseline = c(1, 50), frequencies = NULL, n_cycles = 7, assay_name = NULL, output_assay = "ersp_data" )
x |
A PhysioExperiment object with epoched (3D) EEG data (time x channels x epochs). |
baseline |
Numeric vector of length 2 specifying the baseline time
window in sample indices (e.g., |
frequencies |
Numeric vector of frequencies in Hz to analyze. If
|
n_cycles |
Number of cycles for the Morlet wavelet (default: 7). |
assay_name |
Name of the input assay. If |
output_assay |
Name the result is stored under. Despite the
argument's name this is a key in |
Modified PhysioExperiment with:
3D ERSP array (time x frequencies x channels) in dB in
output_assay
Baseline info and frequency vector in metadata(x)$ersp,
a list containing frequencies (numeric vector),
baseline (numeric vector), n_cycles (integer),
and n_epochs (integer)
Tallon-Baudry, C., et al. (1997). Oscillatory gamma-band activity during conscious perception. Trends in Cognitive Sciences, 3(4), 151-162.
Makeig, S. (1993). Auditory event-related dynamics of the EEG spectrum and effects of exposure to tones. Electroencephalography and Clinical Neurophysiology, 86(4), 283-293.
eegITC(), eegMorletWavelet(), eegPlotSpectrogram()
pe <- make_eeg_erp(n_epochs = 20, n_channels = 2, sr = 250) pe_ersp <- eegERSP(pe, baseline = c(1, 50), frequencies = seq(5, 30, by = 5)) # results are stored in metadata(x)$ersp str(S4Vectors::metadata(pe_ersp)$ersp, max.level = 1)pe <- make_eeg_erp(n_epochs = 20, n_channels = 2, sr = 250) pe_ersp <- eegERSP(pe, baseline = c(1, 50), frequencies = seq(5, 30, by = 5)) # results are stored in metadata(x)$ersp str(S4Vectors::metadata(pe_ersp)$ersp, max.level = 1)
Applies frequency-domain filtering to EEG data stored in a PhysioExperiment object. Supports bandpass, highpass, lowpass, and notch filtering using either FIR (windowed-sinc) or IIR (Butterworth) methods.
eegFilter( x, lowcut = NULL, highcut = NULL, notch = NULL, method = c("fir", "iir"), order = NULL, assay_name = NULL, output_assay = "filtered" )eegFilter( x, lowcut = NULL, highcut = NULL, notch = NULL, method = c("fir", "iir"), order = NULL, assay_name = NULL, output_assay = "filtered" )
x |
A PhysioExperiment object. |
lowcut |
Low cutoff frequency in Hz. If NULL, no highpass filtering is applied (set both lowcut and highcut for bandpass). |
highcut |
High cutoff frequency in Hz. If NULL, no lowpass filtering is applied (set both lowcut and highcut for bandpass). |
notch |
Notch filter center frequency in Hz (e.g., 50 or 60 for powerline noise). If NULL, no notch filter is applied. Bandwidth is +/- 2 Hz around center. |
method |
Filtering method: |
order |
Filter order. For FIR, this is the number of taps (auto-selected if NULL). For IIR, this is the Butterworth order (default: 4). |
assay_name |
Name of the assay to filter. If NULL, uses |
output_assay |
Name of the output assay (default: |
For FIR mode, the function uses windowed-sinc filters with a Hamming window.
For IIR mode, zero-phase Butterworth filtering is applied via
signal::filtfilt(), with automatic fallback to FIR if the signal
package is not available.
A PhysioExperiment object with filtered data in the specified output assay.
pe <- make_eeg(n_time = 5000, n_channels = 19, sr = 500) # Bandpass filter pe_filt <- eegFilter(pe, lowcut = 1, highcut = 40) # Highpass only pe_hp <- eegFilter(pe, lowcut = 0.1) # With notch at 50 Hz pe_notch <- eegFilter(pe, lowcut = 1, highcut = 40, notch = 50) # IIR Butterworth pe_iir <- eegFilter(pe, lowcut = 1, highcut = 40, method = "iir", order = 4)pe <- make_eeg(n_time = 5000, n_channels = 19, sr = 500) # Bandpass filter pe_filt <- eegFilter(pe, lowcut = 1, highcut = 40) # Highpass only pe_hp <- eegFilter(pe, lowcut = 0.1) # With notch at 50 Hz pe_notch <- eegFilter(pe, lowcut = 1, highcut = 40, notch = 50) # IIR Butterworth pe_iir <- eegFilter(pe, lowcut = 1, highcut = 40, method = "iir", order = 4)
Constructs a leadfield matrix that maps brain source activity to scalp
electrode potentials. Uses electrode positions from colData(x) if
available, otherwise falls back to standard 10-20 system positions on a
unit sphere.
eegForwardModel( x, method = c("spherical", "bem_simplified", "bem", "sphere_analytic", "nyhead", "fsaverage"), n_sources = 500, assay_name = NULL )eegForwardModel( x, method = c("spherical", "bem_simplified", "bem", "sphere_analytic", "nyhead", "fsaverage"), n_sources = 500, assay_name = NULL )
x |
A PhysioExperiment object with EEG data. |
method |
Forward model method: |
n_sources |
Number of dipole sources to distribute inside the head model (default: 500). |
assay_name |
Name of the assay to reference for channel count. If
|
A list with components:
Numeric matrix of dimensions n_electrodes x (n_sources * 3). Each source has 3 orientation columns (x, y, z).
Data frame with columns x, y,
z for each source location.
Data frame with columns label,
x, y, z for each electrode.
Integer number of source dipoles.
For the realistic methods, an n_sources x 3 matrix of cortical surface normals (absent for the legacy methods).
The resolved forward-model method.
Source-space origin, units, and anatomical fidelity used by coordinate-aware plotting functions.
Pascual-Marqui, R. D. (2002). Standardized low-resolution brain electromagnetic tomography (sLORETA). Methods and Findings in Experimental and Clinical Pharmacology, 24(Suppl D), 5-12.
eegSourceEstimate(), eegBeamformer(), eegSourcePower()
pe <- make_eeg(n_time = 1000, n_channels = 19, sr = 250) fm <- eegForwardModel(pe, method = "spherical", n_sources = 100) dim(fm$leadfield)pe <- make_eeg(n_time = 1000, n_channels = 19, sr = 250) fm <- eegForwardModel(pe, method = "spherical", n_sources = 100) dim(fm$leadfield)
Computes spectral Granger causality between all EEG channel pairs by fitting bivariate autoregressive (AR) models using Yule-Walker equations and computing the transfer function in the frequency domain. Unlike coherence-based measures, Granger causality is directional: GC from channel A to channel B is generally different from GC from B to A.
eegGrangerCausality(x, order = 5, band = NULL, assay_name = NULL)eegGrangerCausality(x, order = 5, band = NULL, assay_name = NULL)
x |
A PhysioExperiment object with EEG data (2D: time x channels). |
order |
Integer AR model order for the bivariate model (default: 5). |
band |
Numeric vector of length 2 specifying the frequency band in Hz
over which to average GC. If |
assay_name |
Name of the input assay. If |
The spectral Granger causality from channel x to channel y at frequency f is defined as:
A data.frame with columns:
Character or integer identifier of the source channel.
Character or integer identifier of the target channel.
Numeric Granger causality value (>= 0). Higher values indicate stronger directed influence.
Lachaux, J. P., et al. (1999). Measuring phase synchrony in brain signals. Human Brain Mapping, 8(4), 194-208.
Granger, C. W. J. (1969). Investigating causal relations by econometric models and cross-spectral methods. Econometrica, 37(3), 424-438.
eegCoherence(), eegPLV(), eegWPLI(),
eegConnectivityMatrix()
pe <- make_eeg(n_time = 5000, n_channels = 4, sr = 500) gc_df <- eegGrangerCausality(pe, order = 5, band = c(8, 13)) head(gc_df)pe <- make_eeg(n_time = 5000, n_channels = 4, sr = 500) gc_df <- eegGrangerCausality(pe, order = 5, band = c(8, 13)) head(gc_df)
Decomposes multi-channel EEG into independent components using ICA.
Supports FastICA, Infomax, and JADE algorithms. Results are stored in the
output assay (component activations) and in metadata(x)$ica (mixing
and unmixing matrices).
eegICA( x, n_components = NULL, method = c("fastica", "infomax", "jade"), max_iter = 200L, tol = 1e-06, assay_name = NULL, output_assay = "ica_components" )eegICA( x, n_components = NULL, method = c("fastica", "infomax", "jade"), max_iter = 200L, tol = 1e-06, assay_name = NULL, output_assay = "ica_components" )
x |
A PhysioExperiment object with EEG data. |
n_components |
Number of independent components to extract. Defaults to the number of channels. |
method |
ICA algorithm: |
max_iter |
Maximum number of iterations (default: 200). |
tol |
Convergence tolerance (default: 1e-6). |
assay_name |
Input assay name (default: first assay). |
output_assay |
Output assay name (default: |
Modified PhysioExperiment with component activations in
output_assay and ICA metadata in metadata(x)$ica.
The ICA metadata list contains: mixing (mixing matrix A),
unmixing (unmixing matrix), mean (channel means),
whiten (whitening matrix), and method (algorithm used).
The output assay has dimensions n_time x n_components.
Hyvarinen, A., & Oja, E. (2000). Independent component analysis: algorithms and applications. Neural Networks, 13(4-5), 411-430.
Bell, A. J., & Sejnowski, T. J. (1995). An information-maximization approach to blind separation and blind deconvolution. Neural Computation, 7(6), 1129-1159.
eegICAremove(), eegICAdetect(), eegICAmix(),
eegFilter(), eegPreprocess()
pe <- make_eeg(n_time = 5000, sr = 500) result <- eegICA(pe, n_components = 4, method = "fastica")pe <- make_eeg(n_time = 5000, sr = 500) result <- eegICA(pe, n_components = 4, method = "fastica")
Automatically identifies artifact components using one of four methods:
correlation with frontal channels, kurtosis, spatial weight pattern, or the
ICLabel-style seven-class classifier (eegICLabel()). The "iclabel"
method delegates to eegICLabel() and collapses its result to the
two-class contract (any non-brain argmax is an "artifact"), with the
score being one minus the brain probability.
eegICAdetect( x, method = c("correlation", "kurtosis", "spatial", "iclabel"), threshold = 0.3, ica_assay = "ica_components" )eegICAdetect( x, method = c("correlation", "kurtosis", "spatial", "iclabel"), threshold = 0.3, ica_assay = "ica_components" )
x |
A PhysioExperiment object with ICA results (from |
method |
Detection method: |
threshold |
Threshold for artifact detection. For |
ica_assay |
Assay name containing ICA activations (default: |
A data.frame with columns: component (integer index),
type ("artifact" or "neural"), method
(detection method used), and score (numeric detection score).
Hyvarinen, A., & Oja, E. (2000). Independent component analysis: algorithms and applications. Neural Networks, 13(4-5), 411-430.
Bell, A. J., & Sejnowski, T. J. (1995). An information-maximization approach to blind separation and blind deconvolution. Neural Computation, 7(6), 1129-1159.
eegICA(), eegICAremove(), eegICAmix()
pe <- make_eeg(n_time = 5000, sr = 500) pe <- eegICA(pe, n_components = 4, method = "fastica") artifacts <- eegICAdetect(pe, method = "kurtosis")pe <- make_eeg(n_time = 5000, sr = 500) pe <- eegICA(pe, n_components = 4, method = "fastica") artifacts <- eegICAdetect(pe, method = "kurtosis")
Returns the ICA results stored in metadata(x)$ica, including the
mixing matrix, unmixing matrix, channel means, and whitening matrix.
eegICAmix(x)eegICAmix(x)
x |
A PhysioExperiment object with ICA results. |
A list containing: mixing (mixing matrix A, n_channels x
n_components), unmixing (unmixing matrix, n_components x
n_channels), mean (channel mean vector), whiten
(whitening matrix), and method (character, algorithm used).
Hyvarinen, A., & Oja, E. (2000). Independent component analysis: algorithms and applications. Neural Networks, 13(4-5), 411-430.
Bell, A. J., & Sejnowski, T. J. (1995). An information-maximization approach to blind separation and blind deconvolution. Neural Computation, 7(6), 1129-1159.
eegICA(), eegICAremove(), eegICAdetect()
pe <- make_eeg(n_time = 5000, sr = 500) pe <- eegICA(pe, n_components = 4, method = "fastica") ica_info <- eegICAmix(pe)pe <- make_eeg(n_time = 5000, sr = 500) pe <- eegICA(pe, n_components = 4, method = "fastica") ica_info <- eegICAmix(pe)
Reconstructs EEG data with specified independent components removed. The removed components are zeroed out in the mixing matrix before back-projecting to channel space.
eegICAremove( x, components, ica_assay = "ica_components", output_assay = "ica_cleaned" )eegICAremove( x, components, ica_assay = "ica_components", output_assay = "ica_cleaned" )
x |
A PhysioExperiment object with ICA results (from |
components |
Integer vector of component indices to remove. |
ica_assay |
Assay name containing ICA component activations
(default: |
output_assay |
Output assay name (default: |
Modified PhysioExperiment with cleaned data in output_assay.
The cleaned assay contains reconstructed channel data with specified
components removed. Dimensions match the original data.
Hyvarinen, A., & Oja, E. (2000). Independent component analysis: algorithms and applications. Neural Networks, 13(4-5), 411-430.
Bell, A. J., & Sejnowski, T. J. (1995). An information-maximization approach to blind separation and blind deconvolution. Neural Computation, 7(6), 1129-1159.
eegICA(), eegICAdetect(), eegICAmix()
pe <- make_eeg(n_time = 5000, sr = 500) pe <- eegICA(pe, n_components = 4, method = "fastica") pe <- eegICAremove(pe, components = c(1, 2))pe <- make_eeg(n_time = 5000, sr = 500) pe <- eegICA(pe, n_components = 4, method = "fastica") pe <- eegICAremove(pe, components = c(1, 2))
Classifies independent components (from eegICA()) into seven classes -
brain, muscle, eye, heart, line_noise,
channel_noise, and other - and returns a calibrated probability
for each class per component together with the argmax label. The approach
follows the ICLabel framework: interpretable spatial, spectral, and temporal
features are extracted from each component and mapped to class probabilities
by a lightweight multinomial-logistic (softmax) head.
eegICLabel( x, ica_assay = "ica_components", assay_name = NULL, line_freq = 50, backend = c("heuristic", "iclabel") )eegICLabel( x, ica_assay = "ica_components", assay_name = NULL, line_freq = 50, backend = c("heuristic", "iclabel") )
x |
A PhysioExperiment object with ICA results (from |
ica_assay |
Metadata name holding the component activations
(default: |
assay_name |
Input assay used only to resolve channel labels (default: first assay). |
line_freq |
Mains line frequency in Hz used for the line-noise features (default: 50). Only used by the heuristic backend. |
backend |
Which classifier to use: |
Features per component:
Spatial: frontal energy (eye/blink topography), focality (single channel dominance), topography kurtosis.
Spectral: 1/f slope, high- versus low-frequency band ratio, low-frequency fraction, a genuine alpha-peak measure (8-12 Hz power above its theta/low-beta neighbours), and a line-noise power ratio and fraction.
Temporal: lag-1 autocorrelation, activation kurtosis (spiky blink or ECG signatures), and a roughly 1 Hz periodicity measure for cardiac components.
The softmax weights are read from
inst/extdata/iclabel_weights.csv; if that file is unavailable an
identical built-in weight table is used, so the classifier always works.
A data.frame with one row per component: component (integer
index), one numeric column per class (brain, muscle,
eye, heart, line_noise, channel_noise,
other) holding probabilities that sum to 1 across the classes, and
label (character argmax class).
Pion-Tonachini, L., Kreutz-Delgado, K., & Makeig, S. (2019). ICLabel: An automated electroencephalographic independent component classifier, dataset, and website. NeuroImage, 198, 181-197.
Winkler, I., Haufe, S., & Tangermann, M. (2011). Automatic classification of artifactual ICA-components for artifact removal in EEG signals. Behavioral and Brain Functions, 7, 30.
eegICA(), eegICLabelFlag(), eegICAdetect(), eegICAremove()
pe <- make_eeg(n_time = 5000, sr = 500) pe <- eegICA(pe, n_components = 10, method = "fastica") probs <- eegICLabel(pe)pe <- make_eeg(n_time = 5000, sr = 500) pe <- eegICA(pe, n_components = 10, method = "fastica") probs <- eegICLabel(pe)
Convenience wrapper over eegICLabel() that returns the indices of the
components most likely to be artifacts, ready to pass to eegICAremove().
A component is flagged when its probability in any of the requested artifact
classes exceeds prob_threshold.
eegICLabelFlag( x, prob_threshold = 0.5, classes = c("muscle", "eye", "heart", "line_noise", "channel_noise"), ica_assay = "ica_components", line_freq = 50 )eegICLabelFlag( x, prob_threshold = 0.5, classes = c("muscle", "eye", "heart", "line_noise", "channel_noise"), ica_assay = "ica_components", line_freq = 50 )
x |
A PhysioExperiment object with ICA results (from |
prob_threshold |
Probability above which a component is flagged (default: 0.5). |
classes |
Character vector of artifact classes to flag (default: all non-brain, non-other classes). |
ica_assay |
Metadata name holding the component activations
(default: |
line_freq |
Mains line frequency in Hz (default: 50). |
An integer vector of flagged component indices (possibly empty),
with an attribute "labels" giving the corresponding class of each.
eegICLabel(), eegICAremove(), eegICAdetect()
pe <- make_eeg(n_time = 5000, sr = 500) pe <- eegICA(pe, n_components = 10, method = "fastica") bad <- eegICLabelFlag(pe, prob_threshold = 0.5) pe <- eegICAremove(pe, components = bad)pe <- make_eeg(n_time = 5000, sr = 500) pe <- eegICA(pe, n_components = 10, method = "fastica") bad <- eegICLabelFlag(pe, prob_threshold = 0.5) pe <- eegICAremove(pe, components = bad)
Replaces data in bad channels by interpolating from remaining good channels using either spherical spline interpolation (Perrin et al., 1989) or nearest-neighbor weighted averaging.
eegInterpolate( x, bad_channels, method = c("spline", "nearest"), assay_name = NULL, output_assay = "interpolated" )eegInterpolate( x, bad_channels, method = c("spline", "nearest"), assay_name = NULL, output_assay = "interpolated" )
x |
A PhysioExperiment object. |
bad_channels |
Character vector of channel labels to interpolate. |
method |
Interpolation method: |
assay_name |
Name of the assay to interpolate. If NULL, uses
|
output_assay |
Name of the output assay (default: |
Requires electrode positions (pos_x, pos_y, pos_z) in colData.
Apply eegMontage first if positions are not set.
A PhysioExperiment object with interpolated channels in the specified output assay.
pe <- make_eeg(n_time = 5000, n_channels = 19, sr = 500) pe <- eegMontage(pe, system = "10-20") # interpolate two named channels from their neighbours pe_clean <- eegInterpolate(pe, bad_channels = c("C3", "C4")) pe_cleanpe <- make_eeg(n_time = 5000, n_channels = 19, sr = 500) pe <- eegMontage(pe, system = "10-20") # interpolate two named channels from their neighbours pe_clean <- eegInterpolate(pe, bad_channels = c("C3", "C4")) pe_clean
Computes Inter-Trial Coherence (also known as phase-locking factor or phase-locking value) for epoched (3D) EEG data. ITC measures the consistency of oscillatory phase across trials at each time-frequency point. Values range from 0 (completely random phase) to 1 (perfectly phase-locked across all trials).
eegITC( x, frequencies = NULL, n_cycles = 7, assay_name = NULL, output_assay = "itc_data" )eegITC( x, frequencies = NULL, n_cycles = 7, assay_name = NULL, output_assay = "itc_data" )
x |
A PhysioExperiment object with epoched (3D) EEG data (time x channels x epochs). |
frequencies |
Numeric vector of frequencies in Hz to analyze. If
|
n_cycles |
Number of cycles for the Morlet wavelet (default: 7). |
assay_name |
Name of the input assay. If |
output_assay |
Name the result is stored under. Despite the
argument's name this is a key in |
Modified PhysioExperiment with:
3D ITC array (time x frequencies x channels) in
output_assay, values in [0, 1]
Frequency vector and parameters in metadata(x)$itc,
a list containing frequencies (numeric vector),
n_cycles (integer), and n_epochs (integer)
Tallon-Baudry, C., et al. (1997). Oscillatory gamma-band activity during conscious perception. Trends in Cognitive Sciences, 3(4), 151-162.
Makeig, S. (1993). Auditory event-related dynamics of the EEG spectrum and effects of exposure to tones. Electroencephalography and Clinical Neurophysiology, 86(4), 283-293.
eegERSP(), eegMorletWavelet(), eegPlotSpectrogram()
pe <- make_eeg_erp(n_epochs = 20, n_channels = 2, sr = 250) pe_itc <- eegITC(pe, frequencies = seq(5, 30, by = 5)) # results are stored in metadata(x)$itc str(S4Vectors::metadata(pe_itc)$itc, max.level = 1)pe <- make_eeg_erp(n_epochs = 20, n_channels = 2, sr = 250) pe_itc <- eegITC(pe, frequencies = seq(5, 30, by = 5)) # results are stored in metadata(x)$itc str(S4Vectors::metadata(pe_itc)$itc, max.level = 1)
Identifies K-complexes in EEG data by lowpass filtering at 4 Hz, finding negative peaks exceeding a threshold amplitude, and verifying the characteristic negative-positive waveform morphology.
eegKcomplexDetect( x, min_neg_amplitude = 75, min_duration_ms = 500, max_duration_ms = 1500, assay_name = NULL )eegKcomplexDetect( x, min_neg_amplitude = 75, min_duration_ms = 500, max_duration_ms = 1500, assay_name = NULL )
x |
A PhysioExperiment object with EEG data. |
min_neg_amplitude |
Minimum absolute negative peak amplitude in
microvolts (default: 75). Peaks must be more negative than
|
min_duration_ms |
Minimum K-complex duration in milliseconds (default: 500). |
max_duration_ms |
Maximum K-complex duration in milliseconds (default: 1500). |
assay_name |
Input assay name. If |
A data.frame with columns:
Integer channel index.
Integer sample of the negative peak.
Integer sample of the positive peak.
Numeric amplitude at the negative peak.
Numeric amplitude at the positive peak.
Numeric total duration in milliseconds.
Berry, R. B., et al. (2017). AASM Scoring Manual Updates for 2017. Journal of Clinical Sleep Medicine, 13(5), 665-666.
eegSleepStage(), eegSpindleDetect(),
eegSlowWaveDetect(), eegSleepMetrics()
pe <- make_eeg_sleep(n_time = 150000, n_channels = 2, sr = 500) kcomplexes <- eegKcomplexDetect(pe) head(kcomplexes)pe <- make_eeg_sleep(n_time = 150000, n_channels = 2, sr = 500) kcomplexes <- eegKcomplexDetect(pe) head(kcomplexes)
Quantifies the hemispheric asymmetry of sensorimotor-rhythm activity during
motor imagery, a rehabilitation-relevant index of affected- versus
unaffected-hemisphere engagement. For each trial a laterality index
is computed from a right- and a
left-hemisphere channel (or ROI), bounded from -1 to 1. With
method = "erd" the activation is the event-related desynchronization
magnitude from eegMotorImagery() (a positive LI means the right hemisphere
desynchronizes more, i.e. is more active); with method = "power" it is
the raw band power (a positive LI means the right hemisphere has more power).
A symmetric input gives .
eegLateralization( x, left_ch = "C3", right_ch = "C4", band = c(8, 13), method = c("erd", "power"), baseline_fraction = 0.25, conf_level = 0.95, reliability = list(icc = NA_real_, sem = NA_real_), assay_name = NULL )eegLateralization( x, left_ch = "C3", right_ch = "C4", band = c(8, 13), method = c("erd", "power"), baseline_fraction = 0.25, conf_level = 0.95, reliability = list(icc = NA_real_, sem = NA_real_), assay_name = NULL )
x |
A PhysioExperiment object with epoched (3D) EEG data (time x channels x trials). |
left_ch |
Character label(s) of the left-hemisphere channel or ROI
(default: |
right_ch |
Character label(s) of the right-hemisphere channel or ROI
(default: |
band |
Numeric length-2 frequency band in Hz (default: |
method |
Activation measure: |
baseline_fraction |
Fraction of each trial used as the ERD baseline
(default: 0.25); only used by |
conf_level |
Confidence level for the summary interval (default: 0.95). |
reliability |
Named list of reliability indices attached to the summary
biomarker (default: |
assay_name |
Input assay name (default: the default assay). |
A list with per_trial (an n_trials x 1 matrix of
laterality indices) and summary (a
PhysioBiomarker holding the mean LI with its
confidence interval, reliability, and provenance).
Pfurtscheller, G., & Lopes da Silva, F. H. (1999). Event-related EEG/MEG synchronization and desynchronization: basic principles. Clinical Neurophysiology, 110(11), 1842-1857.
Bai, O., et al. (2005). Asymmetric spatiotemporal patterns of event-related desynchronization preceding voluntary sequential finger movements. Clinical Neurophysiology, 116(5), 1213-1221.
eegMotorImagery(), eegCSP(), PhysioExperiment::physioBiomarker()
pe <- make_eeg_bci(n_trials = 20, n_channels = 8, sr = 256) li <- eegLateralization(pe, method = "power") li$summarype <- make_eeg_bci(n_trials = 20, n_channels = 8, sr = 256) li <- eegLateralization(pe, method = "power") li$summary
Assigns each time point to the microstate template map with the highest absolute spatial correlation. This allows applying microstate maps derived from one dataset to another dataset.
eegMicrostateBackfit(x, maps, assay_name = NULL)eegMicrostateBackfit(x, maps, assay_name = NULL)
x |
A PhysioExperiment object with EEG data. |
maps |
Numeric matrix of microstate template maps (n_channels x
n_states), as returned in |
assay_name |
Name of the input assay. If |
Modified PhysioExperiment with updated microstate labels in
metadata(x)$microstates$labels. Also stores the template maps
in metadata(x)$microstates$maps and the number of states in
metadata(x)$microstates$n_states.
Michel, C. M., & Koenig, T. (2018). EEG microstates as a tool for studying the temporal dynamics of whole-brain neuronal networks. NeuroImage, 180, 577-593.
eegMicrostates(), eegMicrostateStats(),
eegMicrostateSequence()
pe1 <- make_eeg(n_time = 5000, n_channels = 19, sr = 500) pe1 <- eegMicrostates(pe1, n_states = 4) maps <- S4Vectors::metadata(pe1)$microstates$maps pe2 <- make_eeg(n_time = 3000, n_channels = 19, sr = 500) pe2 <- eegMicrostateBackfit(pe2, maps)pe1 <- make_eeg(n_time = 5000, n_channels = 19, sr = 500) pe1 <- eegMicrostates(pe1, n_states = 4) maps <- S4Vectors::metadata(pe1)$microstates$maps pe2 <- make_eeg(n_time = 3000, n_channels = 19, sr = 500) pe2 <- eegMicrostateBackfit(pe2, maps)
Performs microstate analysis on EEG data by identifying dominant scalp topographies at Global Field Power (GFP) peaks and assigning each time point to the best-matching microstate map. Supports polarity-invariant K-means, atomize-and-agglomerate hierarchical clustering (AAHC), and PCA-based extraction.
eegMicrostates( x, n_states = 4, method = c("kmeans", "aahc", "pca"), min_gfp = 1, assay_name = NULL )eegMicrostates( x, n_states = 4, method = c("kmeans", "aahc", "pca"), min_gfp = 1, assay_name = NULL )
x |
A PhysioExperiment object with EEG data. |
n_states |
Number of microstate classes to extract (default: 4). |
method |
Clustering method: |
min_gfp |
Percentile threshold (0-100) for GFP peak selection (default: 1.0). Only GFP peaks above this percentile are used for clustering. |
assay_name |
Name of the input assay. If |
Modified PhysioExperiment with microstate results stored in
metadata(x)$microstates, a list containing:
Numeric matrix of dimensions n_channels x n_states, each column a microstate topography.
Integer vector of length n_time, microstate assignment (1 to n_states) for each time point.
Numeric vector of GFP values per time point.
Integer number of microstate classes.
Michel, C. M., & Koenig, T. (2018). EEG microstates as a tool for studying the temporal dynamics of whole-brain neuronal networks. NeuroImage, 180, 577-593.
eegMicrostateStats(), eegMicrostateBackfit(),
eegMicrostateSequence()
pe <- make_eeg(n_time = 5000, n_channels = 19, sr = 500) pe <- eegMicrostates(pe, n_states = 4, method = "kmeans") ms <- S4Vectors::metadata(pe)$microstatespe <- make_eeg(n_time = 5000, n_channels = 19, sr = 500) pe <- eegMicrostates(pe, n_states = 4, method = "kmeans") ms <- S4Vectors::metadata(pe)$microstates
Converts integer microstate labels to character labels ("A", "B", "C", ...).
eegMicrostateSequence(x)eegMicrostateSequence(x)
x |
A PhysioExperiment object with microstate labels in
|
Character vector of length n_time with labels "A", "B", "C", etc. Each element corresponds to the microstate class assigned to that time point.
Michel, C. M., & Koenig, T. (2018). EEG microstates as a tool for studying the temporal dynamics of whole-brain neuronal networks. NeuroImage, 180, 577-593.
eegMicrostates(), eegMicrostateStats(),
eegMicrostateBackfit()
pe <- make_eeg(n_time = 2000, n_channels = 19, sr = 500) pe <- eegMicrostates(pe, n_states = 4) seq_labels <- eegMicrostateSequence(pe) table(seq_labels)pe <- make_eeg(n_time = 2000, n_channels = 19, sr = 500) pe <- eegMicrostates(pe, n_states = 4) seq_labels <- eegMicrostateSequence(pe) table(seq_labels)
Calculates temporal statistics for each microstate class from a segmented EEG recording: mean duration, occurrence rate, and time coverage. Also computes the transition probability matrix between states.
eegMicrostateStats(x)eegMicrostateStats(x)
x |
A PhysioExperiment object with microstate labels in
|
A data.frame with columns:
Integer microstate class (1 to n_states).
Mean duration of consecutive runs in milliseconds.
Number of state occurrences (runs) per second.
Percentage of total time spent in this state.
The transition probability matrix (n_states x n_states) is stored as
an attribute "transition_matrix".
Michel, C. M., & Koenig, T. (2018). EEG microstates as a tool for studying the temporal dynamics of whole-brain neuronal networks. NeuroImage, 180, 577-593.
eegMicrostates(), eegMicrostateBackfit(),
eegMicrostateSequence()
pe <- make_eeg(n_time = 5000, n_channels = 19, sr = 500) pe <- eegMicrostates(pe, n_states = 4, method = "kmeans") stats <- eegMicrostateStats(pe) print(stats) attr(stats, "transition_matrix")pe <- make_eeg(n_time = 5000, n_channels = 19, sr = 500) pe <- eegMicrostates(pe, n_states = 4, method = "kmeans") stats <- eegMicrostateStats(pe) print(stats) attr(stats, "transition_matrix")
Maps channel labels to standard electrode positions from a known montage
system (10-20, 10-10, BioSemi64) or from a custom positions data.frame.
Sets pos_x, pos_y, pos_z columns in colData for use
by interpolation, topographic mapping, and source localization functions.
eegMontage( x, system = c("10-20", "10-10", "biosemi64", "custom"), positions = NULL )eegMontage( x, system = c("10-20", "10-10", "biosemi64", "custom"), positions = NULL )
x |
A PhysioExperiment object. |
system |
Montage system: |
positions |
For |
A PhysioExperiment object with updated colData containing position columns.
pe <- make_eeg(n_time = 5000, n_channels = 19, sr = 500) pe <- eegMontage(pe, system = "10-20") head(SummarizedExperiment::colData(pe))pe <- make_eeg(n_time = 5000, n_channels = 19, sr = 500) pe <- eegMontage(pe, system = "10-20") head(SummarizedExperiment::colData(pe))
Computes the continuous Morlet wavelet transform for multi-channel EEG data. For each specified frequency, a complex Morlet wavelet is constructed and convolved with each channel using FFT-based convolution for efficiency. Returns time-resolved power (and optionally phase) across frequencies.
eegMorletWavelet( x, frequencies = NULL, n_cycles = 7, assay_name = NULL, output_assay = "wavelet_power" )eegMorletWavelet( x, frequencies = NULL, n_cycles = 7, assay_name = NULL, output_assay = "wavelet_power" )
x |
A PhysioExperiment object with EEG data (2D: time x channels). |
frequencies |
Numeric vector of frequencies in Hz to analyze. If
|
n_cycles |
Number of cycles in the Morlet wavelet, controlling the trade-off between time and frequency resolution (default: 7). |
assay_name |
Name of the input assay. If |
output_assay |
Name the result is stored under. Despite the
argument's name this is a key in |
Modified PhysioExperiment with:
3D power array (time x frequencies x channels) in output_assay
Frequency vector and phase array in metadata(x)$wavelet,
a list containing frequencies (numeric vector),
n_cycles (integer), and phase (3D array of
instantaneous phase values)
Tallon-Baudry, C., et al. (1997). Oscillatory gamma-band activity during conscious perception. Trends in Cognitive Sciences, 3(4), 151-162.
eegSTFT(), eegMultitaper(), eegPlotSpectrogram(),
eegERSP()
pe <- make_eeg(n_time = 1000, n_channels = 4, sr = 250) pe_wt <- eegMorletWavelet(pe, frequencies = seq(5, 40, by = 5)) # results are stored in metadata(x)$wavelet str(S4Vectors::metadata(pe_wt)$wavelet, max.level = 1)pe <- make_eeg(n_time = 1000, n_channels = 4, sr = 250) pe_wt <- eegMorletWavelet(pe, frequencies = seq(5, 40, by = 5)) # results are stored in metadata(x)$wavelet str(S4Vectors::metadata(pe_wt)$wavelet, max.level = 1)
Computes event-related desynchronization (ERD) and event-related synchronization (ERS) for motor imagery BCI analysis. ERD/ERS is expressed as a percentage change from baseline power in specified frequency bands.
eegMotorImagery( x, bands = NULL, baseline_fraction = 0.25, assay_name = NULL, output_assay = "erd_ers" )eegMotorImagery( x, bands = NULL, baseline_fraction = 0.25, assay_name = NULL, output_assay = "erd_ers" )
x |
A PhysioExperiment object with epoched (3D) EEG data (time x channels x trials). |
bands |
Named list of frequency bands, each a numeric vector
|
baseline_fraction |
Fraction of each trial to use as baseline (default: 0.25, i.e., the first 25 percent of the trial). |
assay_name |
Input assay name (default: first assay). |
output_assay |
Output assay name (default: |
Modified PhysioExperiment with ERD/ERS percentage values in
output_assay. The output is a matrix of
n_trials rows x n_channels * n_bands columns.
Sets metadata(x)$erd_ers_bands with the band definitions used.
Blankertz, B., et al. (2008). Optimizing spatial filters for robust EEG single-trial analysis. IEEE Signal Processing Magazine, 25(1), 41-56.
eegCSP(), eegBCIfeatures(), eegBCIclassify()
pe <- make_eeg_bci(n_trials = 20, n_channels = 8, sr = 256) result <- eegMotorImagery(pe) # ERD/ERS features are stored in metadata(x)$erd_ers erd_data <- S4Vectors::metadata(result)$erd_ers dim(erd_data) # trials x (channels * bands)pe <- make_eeg_bci(n_trials = 20, n_channels = 8, sr = 256) result <- eegMotorImagery(pe) # ERD/ERS features are stored in metadata(x)$erd_ers erd_data <- S4Vectors::metadata(result)$erd_ers dim(erd_data) # trials x (channels * bands)
Computes the multitaper power spectral density (PSD) estimate for multi-channel EEG data using Discrete Prolate Spheroidal Sequences (DPSS, Slepian tapers). The multitaper method provides an optimal bias-variance trade-off for spectral estimation compared to single-window methods.
eegMultitaper( x, bandwidth = 4, n_tapers = NULL, assay_name = NULL, output_assay = "multitaper_psd" )eegMultitaper( x, bandwidth = 4, n_tapers = NULL, assay_name = NULL, output_assay = "multitaper_psd" )
x |
A PhysioExperiment object with EEG data (2D: time x channels). |
bandwidth |
Time-half-bandwidth product (NW) controlling the spectral concentration of the tapers (default: 4). Higher values give smoother but lower-resolution estimates. |
n_tapers |
Number of DPSS tapers to use. If |
assay_name |
Name of the input assay. If |
output_assay |
Name the result is stored under. Despite the
argument's name this is a key in |
Modified PhysioExperiment with:
PSD matrix (frequencies x channels) in output_assay
Frequency vector and taper parameters in
metadata(x)$multitaper, a list containing
frequencies (numeric vector), bandwidth
(numeric NW parameter), and n_tapers (integer)
Tallon-Baudry, C., et al. (1997). Oscillatory gamma-band activity during conscious perception. Trends in Cognitive Sciences, 3(4), 151-162.
Thomson, D. J. (1982). Spectrum estimation and harmonic analysis. Proceedings of the IEEE, 70(9), 1055-1096.
eegMorletWavelet(), eegSTFT(), eegPlotSpectrogram()
pe <- make_eeg(n_time = 2000, n_channels = 4, sr = 250) pe_mt <- eegMultitaper(pe, bandwidth = 4) # results are stored in metadata(x)$multitaper str(S4Vectors::metadata(pe_mt)$multitaper, max.level = 1)pe <- make_eeg(n_time = 2000, n_channels = 4, sr = 250) pe_mt <- eegMultitaper(pe, bandwidth = 4) # results are stored in metadata(x)$multitaper str(S4Vectors::metadata(pe_mt)$multitaper, max.level = 1)
Measures how the phase of a slow oscillation modulates the amplitude of a fast
oscillation — within a single channel (amp_channel = NULL) or across two
channels. Delegates the estimator to PhysioCrossModal::phaseAmplitudeCoupling().
eegPAC( pe, phase_channel = 1L, amp_channel = NULL, phase_band = c(4, 8), amp_band = c(30, 80), method = c("tort", "canolty", "ozkurt", "plv"), n_bins = 18L, assay_name = NULL )eegPAC( pe, phase_channel = 1L, amp_channel = NULL, phase_band = c(4, 8), amp_band = c(30, 80), method = c("tort", "canolty", "ozkurt", "plv"), n_bins = 18L, assay_name = NULL )
pe |
A |
phase_channel |
Channel (index or label) supplying the modulating phase. |
amp_channel |
Channel supplying the modulated amplitude; |
phase_band |
Phase frequency band in Hz (default theta |
amp_band |
Amplitude frequency band in Hz (default gamma |
method |
|
n_bins |
Number of phase bins for the Tort modulation index (default 18). |
assay_name |
Assay to use (default: the object's default assay). |
The PAC result from PhysioCrossModal::phaseAmplitudeCoupling() (a
list with pac and, for "tort", the phase-amplitude distribution).
Tort et al. 2010; Canolty et al. 2006.
eegComodulogram(), eegConnectivityMatrix()
if (requireNamespace("PhysioCrossModal", quietly = TRUE)) { pe <- make_eeg(n_time = 5000, n_channels = 4, sr = 250) eegPAC(pe, phase_channel = 1, phase_band = c(4, 8), amp_band = c(30, 80)) }if (requireNamespace("PhysioCrossModal", quietly = TRUE)) { pe <- make_eeg(n_time = 5000, n_channels = 4, sr = 250) eegPAC(pe, phase_channel = 1, phase_band = c(4, 8), amp_band = c(30, 80)) }
Estimates frequency-resolved directed connectivity with Partial Directed
Coherence (Baccala & Sameshima 2001), computed from the frequency-domain
coefficient matrix of an MVAR model
(PhysioExperiment::mvarFit()). Unlike DTF, PDC reflects only direct
channel-to-channel influences, so a purely indirect pathway gives PDC near
zero. The (default) generalized PDC weights each row by the inverse residual
standard deviation to make the measure scale-invariant (Baccala 2007). PDC
satisfies for each source
(outflow normalization).
eegPDC( x, order = NULL, freqs = NULL, generalized = TRUE, band = NULL, method = "ols", assay_name = NULL )eegPDC( x, order = NULL, freqs = NULL, generalized = TRUE, band = NULL, method = "ols", assay_name = NULL )
x |
A PhysioExperiment object with 2D EEG data (time x channels). |
order |
MVAR model order, or |
freqs |
Numeric vector of frequencies in Hz (default: 128 points from 0 to the Nyquist frequency). |
generalized |
Use generalized PDC (default: |
band |
Optional numeric length-2 band in Hz over which to average the stored connectivity matrix (default: all frequencies). |
method |
MVAR estimator passed to |
assay_name |
Input assay name (default: the default assay). |
The PhysioExperiment with metadata(x)$connectivity set as in
eegDTF() (a band-averaged directed matrix, the frequency-resolved
array, frequencies, and settings).
Baccala, L. A., & Sameshima, K. (2001). Partial directed coherence: a new concept in neural structure determination. Biological Cybernetics, 84(6), 463-474.
eegDTF(), eegConditionalGC(), eegConnectivityMatrix()
pe <- make_eeg(n_time = 4000, n_channels = 5, sr = 250) pe <- eegPDC(pe, order = 5) S4Vectors::metadata(pe)$connectivity$matrixpe <- make_eeg(n_time = 4000, n_channels = 5, sr = 250) pe <- eegPDC(pe, order = 5) S4Vectors::metadata(pe)$connectivity$matrix
Displays the selected continuous EEG channels as a butterfly plot above their Global Field Power (GFP). GFP is the spatial dispersion across the displayed channels at each time point, so its magnitude depends on the selected channels and EEG reference. It is not source-localized power.
eegPlotButterflyGFP( x, channels = NULL, time_range = NULL, show_events = FALSE, assay_name = NULL, gfp_definition = c("population", "sample"), heights = c(3, 1) )eegPlotButterflyGFP( x, channels = NULL, time_range = NULL, show_events = FALSE, assay_name = NULL, gfp_definition = c("population", "sample"), heights = c(3, 1) )
x |
A PhysioExperiment object containing a numeric 2D continuous EEG assay (time x channels). |
channels |
Unique character vector of exact channel labels. If
|
time_range |
Optional finite increasing length-two vector specifying the inclusive display range in seconds. GFP is calculated before display windowing. |
show_events |
Logical; draw finite event times from
|
assay_name |
Input assay name. If |
gfp_definition |
Denominator used for spatial dispersion:
|
heights |
Two finite positive values giving the butterfly and GFP panel height ratio. |
A patchwork object containing two ggplot panels.
if (requireNamespace("ggplot2", quietly = TRUE) && requireNamespace("patchwork", quietly = TRUE)) { pe <- make_eeg(n_time = 1500, n_channels = 19, sr = 250) eegPlotButterflyGFP(pe, channels = c("Fz", "Cz", "Pz")) }if (requireNamespace("ggplot2", quietly = TRUE) && requireNamespace("patchwork", quietly = TRUE)) { pe <- make_eeg(n_time = 1500, n_channels = 19, sr = 250) eegPlotButterflyGFP(pe, channels = c("Fz", "Cz", "Pz")) }
Visualizes EEG connectivity as either a heatmap (matrix) or a circular
connectivity plot (circle). The connectivity matrix can be provided
directly or read from metadata(x)$connectivity$matrix.
eegPlotConnectivity( x, method = c("heatmap", "circle"), matrix = NULL, threshold = 0, labels = NULL, palette = "RdBu" )eegPlotConnectivity( x, method = c("heatmap", "circle"), matrix = NULL, threshold = 0, labels = NULL, palette = "RdBu" )
x |
A PhysioExperiment object with EEG data. |
method |
Display method: |
matrix |
Numeric matrix of connectivity values. If |
threshold |
Numeric; only show connections above this value (default: 0). |
labels |
Character vector of channel labels. If |
palette |
Character name of the diverging color palette
(default: |
A ggplot2 object.
if (requireNamespace("ggplot2", quietly = TRUE)) { mat <- matrix(runif(16), 4, 4) diag(mat) <- 1 pe <- make_eeg(n_time = 1000, n_channels = 4, sr = 250) eegPlotConnectivity(pe, method = "heatmap", matrix = mat) }if (requireNamespace("ggplot2", quietly = TRUE)) { mat <- matrix(runif(16), 4, 4) diag(mat) <- 1 pe <- make_eeg(n_time = 1000, n_channels = 4, sr = 250) eegPlotConnectivity(pe, method = "heatmap", matrix = mat) }
Draws a deterministic circular view of a connectivity matrix stored in
metadata(x)$connectivity$matrix. Symmetric matrices are represented
by one edge per unordered channel pair. Asymmetric matrices retain every
ordered entry, following the PhysioEEG directed-matrix convention of rows
as targets and columns as sources.
eegPlotConnectogram( x, order = c("hemisphere", "lobe", "cluster"), modules = NULL, threshold = NULL, bundle = TRUE )eegPlotConnectogram( x, order = c("hemisphere", "lobe", "cluster"), modules = NULL, threshold = NULL, bundle = TRUE )
x |
A PhysioExperiment with a finite square numeric matrix at
|
order |
Exactly one node ordering: |
modules |
Optional module declaration. Supply a named character or
factor vector, or a data frame with unique |
threshold |
A finite non-negative scalar, or |
bundle |
One non-missing logical scalar. If |
The threshold is a strict absolute display threshold
(abs(value) > threshold); it is not a p-value or a corrected
significance mask. Hemisphere and lobe are inferred only for recognized
10-20/10-10 labels. Other labels remain "unknown" unless explicit
colData columns are supplied. Label tie-breaking uses a stable UTF-8
byte key. Edge identifiers length-prefix both endpoint labels so labels
containing the visible " -- " or " -> " separators cannot
collide.
A ggplot2 object. Resolved node, edge, path, module-arc, and setting
tables are available in attr(plot, "connectogram_data").
eegPlotConnectivity(), eegConnectivityMatrix()
if (requireNamespace("ggplot2", quietly = TRUE)) { pe <- make_eeg(n_time = 1000, n_channels = 4, sr = 250) mat <- matrix(c( 1, 0.5, 0, -0.4, 0.5, 1, 0.3, 0, 0, 0.3, 1, 0.6, -0.4, 0, 0.6, 1 ), 4, 4) labels <- SummarizedExperiment::colData(pe)$label dimnames(mat) <- list(labels, labels) S4Vectors::metadata(pe)$connectivity <- list( matrix = mat, method = "coherence", band = c(8, 13) ) eegPlotConnectogram(pe, threshold = 0.2) }if (requireNamespace("ggplot2", quietly = TRUE)) { pe <- make_eeg(n_time = 1000, n_channels = 4, sr = 250) mat <- matrix(c( 1, 0.5, 0, -0.4, 0.5, 1, 0.3, 0, 0, 0.3, 1, 0.6, -0.4, 0, 0.6, 1 ), 4, 4) labels <- SummarizedExperiment::colData(pe)$label dimnames(mat) <- list(labels, labels) S4Vectors::metadata(pe)$connectivity <- list( matrix = mat, method = "coherence", band = c(8, 13) ) eegPlotConnectogram(pe, threshold = 0.2) }
Plots event-related potential waveforms averaged across epochs, with
optional confidence interval ribbons. Supports condition-based
comparisons when metadata(x)$conditions is available.
eegPlotERP( x, channels = NULL, conditions = NULL, ci = 0.95, show_ci = TRUE, epoch_start = 0, assay_name = NULL )eegPlotERP( x, channels = NULL, conditions = NULL, ci = 0.95, show_ci = TRUE, epoch_start = 0, assay_name = NULL )
x |
A PhysioExperiment object with epoched (3D) EEG data (time x channels x epochs). |
channels |
Character vector of channel labels to plot. If |
conditions |
Character vector of condition labels to include.
If |
ci |
Confidence level for the interval (default: 0.95). |
show_ci |
Logical; if |
epoch_start |
Numeric start time of each epoch in seconds for the x-axis (default: 0). |
assay_name |
Input assay name. If |
A ggplot2 object.
if (requireNamespace("ggplot2", quietly = TRUE)) { pe <- make_eeg_erp(n_epochs = 40, sr = 250) eegPlotERP(pe, channels = "Cz") }if (requireNamespace("ggplot2", quietly = TRUE)) { pe <- make_eeg_erp(n_epochs = 40, sr = 250) eegPlotERP(pe, channels = "Cz") }
Creates deterministic sagittal, axial, and coronal maximum-intensity projections from source amplitudes with real three-dimensional coordinates. The bundled outline is schematic and is not an MRI, patient anatomy, or a validation of the inverse solution.
eegPlotGlassBrain( x, source_data = NULL, views = c("sagittal", "axial", "coronal"), threshold_pct = 90 )eegPlotGlassBrain( x, source_data = NULL, views = c("sagittal", "axial", "coronal"), threshold_pct = 90 )
x |
A PhysioExperiment object. |
source_data |
Optional explicit source data. Supply a data frame with
finite |
views |
Non-empty unique character vector drawn exactly from
|
threshold_pct |
Finite percentile in |
Projection axes are sagittal y-z with depth x, axial
x-y with depth z, and coronal x-z with depth
y. Free-orientation source estimates are reduced by root-sum-square
over orientations at each time and RMS over time. This non-negative
summary is not a signed instantaneous current. A fixed 80 by 80 display
grid retains the greatest absolute amplitude in each projected bin, with
exact ties resolved by the smallest source ID. The affine display
transform comes from the complete unthresholded coordinate cloud and does
not modify amplitudes. The bundled outline is schematic: the plot is not
MRI registration, patient anatomy, or validation of localization accuracy.
Bare amplitude vectors and two-dimensional coordinates are rejected.
A patchwork object for normal projections. When fewer than three
rows survive thresholding, returns the first requested view as an
eegPlotSource() ggplot fallback without applying a second
threshold. Immutable "glassbrain_data" attributes retain the
resolved sources, panel data, display transform, and threshold settings.
eegForwardModel(), eegSourceEstimate(), eegBeamformer(),
eegPlotSource()
if (requireNamespace("ggplot2", quietly = TRUE) && requireNamespace("patchwork", quietly = TRUE)) { pe <- make_eeg(n_time = 500, n_channels = 19, sr = 250) fm <- eegForwardModel(pe, method = "spherical", n_sources = 50) localized <- eegSourceEstimate(pe, fm, method = "mne") eegPlotGlassBrain(localized) }if (requireNamespace("ggplot2", quietly = TRUE) && requireNamespace("patchwork", quietly = TRUE)) { pe <- make_eeg(n_time = 500, n_channels = 19, sr = 250) fm <- eegForwardModel(pe, method = "spherical", n_sources = 50) localized <- eegSourceEstimate(pe, fm, method = "mne") eegPlotGlassBrain(localized) }
Displays a sleep hypnogram showing sleep stage transitions over time. Stages are ordered with Wake at the top and N3 at the bottom, with a characteristic staircase pattern.
eegPlotHypnogram(x, stages = NULL, epoch_sec = 30, colors = NULL)eegPlotHypnogram(x, stages = NULL, epoch_sec = 30, colors = NULL)
x |
A PhysioExperiment object (used for metadata access). |
stages |
A data.frame with columns |
epoch_sec |
Epoch duration in seconds (default: 30). |
colors |
Named character vector of colors for each stage.
If |
A ggplot2 object.
if (requireNamespace("ggplot2", quietly = TRUE)) { pe <- make_eeg_sleep(n_time = 150000, n_channels = 2, sr = 500) stages <- eegSleepStage(pe) S4Vectors::metadata(pe)$sleep_stages <- stages eegPlotHypnogram(pe) }if (requireNamespace("ggplot2", quietly = TRUE)) { pe <- make_eeg_sleep(n_time = 150000, n_channels = 2, sr = 500) stages <- eegSleepStage(pe) S4Vectors::metadata(pe)$sleep_stages <- stages eegPlotHypnogram(pe) }
Displays ICA component time courses in a stacked layout similar to
eegPlotSignal. Optionally shows topographic maps of the mixing
matrix weights as a side panel annotation.
eegPlotICA( x, components = NULL, time_range = NULL, show_topography = TRUE, assay_name = NULL )eegPlotICA( x, components = NULL, time_range = NULL, show_topography = TRUE, assay_name = NULL )
x |
A PhysioExperiment object with ICA results. |
components |
Integer vector of component indices to display.
If |
time_range |
Numeric vector of length 2 specifying time range in
seconds. If |
show_topography |
Logical; if |
assay_name |
Input assay name. If |
A ggplot2 object.
if (requireNamespace("ggplot2", quietly = TRUE)) { pe <- make_eeg(n_time = 5000, n_channels = 19, sr = 500) pe <- eegICA(pe, n_components = 10) eegPlotICA(pe, components = 1:5) }if (requireNamespace("ggplot2", quietly = TRUE)) { pe <- make_eeg(n_time = 5000, n_channels = 19, sr = 500) pe <- eegICA(pe, n_components = 10) eegPlotICA(pe, components = 1:5) }
Displays multi-channel EEG time series in stacked, butterfly, or grid layout. Supports channel selection, time range restriction, and optional event markers.
eegPlotSignal( x, channels = NULL, time_range = NULL, mode = c("stacked", "butterfly", "grid"), scale = 1, show_events = FALSE, assay_name = NULL )eegPlotSignal( x, channels = NULL, time_range = NULL, mode = c("stacked", "butterfly", "grid"), scale = 1, show_events = FALSE, assay_name = NULL )
x |
A PhysioExperiment object with 2D EEG data (time x channels). |
channels |
Character vector of channel labels to display.
If |
time_range |
Numeric vector of length 2 specifying time range in
seconds as |
mode |
Display mode: |
scale |
Numeric scaling factor for vertical offset in stacked mode (default: 1). |
show_events |
Logical; if |
assay_name |
Input assay name. If |
A ggplot2 object.
if (requireNamespace("ggplot2", quietly = TRUE)) { pe <- make_eeg(n_time = 2500, n_channels = 4, sr = 500) eegPlotSignal(pe, mode = "stacked") }if (requireNamespace("ggplot2", quietly = TRUE)) { pe <- make_eeg(n_time = 2500, n_channels = 4, sr = 500) eegPlotSignal(pe, mode = "stacked") }
Visualizes source localization results as a 2D scatter plot or flat map projection. Sources are sized and colored by amplitude, with optional thresholding to show only the strongest activations.
eegPlotSource( x, source_data = NULL, method = c("scatter", "flatmap"), threshold_pct = 80 )eegPlotSource( x, source_data = NULL, method = c("scatter", "flatmap"), threshold_pct = 80 )
x |
A PhysioExperiment object. |
source_data |
Named numeric vector of source amplitudes or
a data.frame with columns |
method |
Display method: |
threshold_pct |
Numeric percentile threshold (0-100). Only sources above this percentile are displayed (default: 80). |
A ggplot2 object.
if (requireNamespace("ggplot2", quietly = TRUE) && requireNamespace("patchwork", quietly = TRUE)) { pe <- make_eeg(n_time = 1000, n_channels = 19, sr = 250) src <- data.frame(x = runif(50, -1, 1), y = runif(50, -1, 1), amplitude = rnorm(50)^2) eegPlotSource(pe, source_data = src, method = "scatter") }if (requireNamespace("ggplot2", quietly = TRUE) && requireNamespace("patchwork", quietly = TRUE)) { pe <- make_eeg(n_time = 1000, n_channels = 19, sr = 250) src <- data.frame(x = runif(50, -1, 1), y = runif(50, -1, 1), amplitude = rnorm(50)^2) eegPlotSource(pe, source_data = src, method = "scatter") }
Displays a time-frequency representation of EEG data as a heatmap. It uses an unambiguous stored STFT, Morlet, or ERSP product when available. For a continuous 2D assay, it computes the established sliding-window FFT.
eegPlotSpectrogram( x, channel = 1, freq_range = NULL, time_range = NULL, log_power = TRUE, palette = "viridis", assay_name = NULL, mask = NULL, mask_alpha = 0.4, contour = TRUE )eegPlotSpectrogram( x, channel = 1, freq_range = NULL, time_range = NULL, log_power = TRUE, palette = "viridis", assay_name = NULL, mask = NULL, mask_alpha = 0.4, contour = TRUE )
x |
A PhysioExperiment object with EEG data. |
channel |
Integer or character specifying which channel to display (default: 1). |
freq_range |
Numeric vector of length 2 for frequency axis limits.
If |
time_range |
Numeric vector of length 2 for time axis limits.
If |
log_power |
Logical; if |
palette |
Character name of the color palette (default: |
assay_name |
Input assay or time-frequency metadata product name. If
|
mask |
Optional display mask. Supply a logical time-by-frequency matrix,
a p-value matrix with an explicit |
mask_alpha |
Opacity for bins outside |
contour |
Logical; draw non-interpolated boundaries between included and excluded mask bins when both are present (default: TRUE). |
A mask controls opacity and optional boundaries only. It never
replaces, zeros, or otherwise changes the plotted power values. Matrix
masks describe the complete time-by-frequency grid before
freq_range or time_range is applied.
Statistical masks must be computed from repeated, independent and exchangeable observations, not inferred from the single spectrogram being plotted. The package-private cluster helper subtracts the declared baseline within each replicate and frequency, uses sign-separated four-neighbour components and a maximum cluster-mass sign-flip null, and applies the conservative plus-one correction. Its corrected p-values are cluster-level evidence; they do not make each enclosed bin individually significant or establish a neurophysiological mechanism.
A ggplot2 object.
if (requireNamespace("ggplot2", quietly = TRUE)) { pe <- make_eeg(n_time = 5000, n_channels = 4, sr = 500) eegPlotSpectrogram(pe, channel = 1) }if (requireNamespace("ggplot2", quietly = TRUE)) { pe <- make_eeg(n_time = 5000, n_channels = 4, sr = 500) eegPlotSpectrogram(pe, channel = 1) }
Creates a 2D scalp topographic map using inverse distance weighted
interpolation. Electrode positions are read from colData(x)
(columns pos_x, pos_y) or default 10-20 positions are
used as fallback. The plot includes a head outline, nose, and ears.
eegPlotTopomap( x, time = NULL, values = NULL, assay_name = NULL, resolution = 100, palette = "RdBu", contours = TRUE, electrodes = TRUE )eegPlotTopomap( x, time = NULL, values = NULL, assay_name = NULL, resolution = 100, palette = "RdBu", contours = TRUE, electrodes = TRUE )
x |
A PhysioExperiment object with EEG data. |
time |
Numeric time point in seconds at which to extract values
from the assay. If |
values |
Named numeric vector of channel values to plot directly. If provided, overrides data extraction from the assay. |
assay_name |
Input assay name. If |
resolution |
Integer grid resolution for interpolation (default: 100). |
palette |
Character name of the diverging color palette
(default: |
contours |
Logical; if |
electrodes |
Logical; if |
A ggplot2 object.
if (requireNamespace("ggplot2", quietly = TRUE)) { pe <- make_eeg(n_time = 500, n_channels = 19, sr = 250) eegPlotTopomap(pe, time = 0.5) }if (requireNamespace("ggplot2", quietly = TRUE)) { pe <- make_eeg(n_time = 500, n_channels = 19, sr = 250) eegPlotTopomap(pe, time = 0.5) }
Creates multiple topographic maps at specified time points arranged in a grid layout with a shared or independent color scale.
eegPlotTopomapSeries( x, times, assay_name = NULL, ncol = NULL, palette = "RdBu", shared_limits = TRUE )eegPlotTopomapSeries( x, times, assay_name = NULL, ncol = NULL, palette = "RdBu", shared_limits = TRUE )
x |
A PhysioExperiment object with EEG data. |
times |
Numeric vector of time points in seconds. |
assay_name |
Input assay name. If |
ncol |
Integer number of columns in the grid layout.
If |
palette |
Character name of the diverging color palette
(default: |
shared_limits |
Logical; if |
A ggplot2 object with faceted topomaps.
if (requireNamespace("ggplot2", quietly = TRUE)) { pe <- make_eeg(n_time = 2500, n_channels = 19, sr = 500) eegPlotTopomapSeries(pe, times = c(0.1, 0.2, 0.3)) }if (requireNamespace("ggplot2", quietly = TRUE)) { pe <- make_eeg(n_time = 2500, n_channels = 19, sr = 500) eegPlotTopomapSeries(pe, times = c(0.1, 0.2, 0.3)) }
Computes the Phase Locking Value between all EEG channel pairs within a specified frequency band. Each channel is bandpass filtered, instantaneous phase is extracted via the Hilbert transform, and PLV is computed as the mean resultant length of the phase difference distribution.
eegPLV(x, band = c(8, 13), assay_name = NULL)eegPLV(x, band = c(8, 13), assay_name = NULL)
x |
A PhysioExperiment object with EEG data (2D: time x channels). |
band |
Numeric vector of length 2 specifying the frequency band in Hz
for bandpass filtering before phase extraction (default: |
assay_name |
Name of the input assay. If |
A data.frame with columns:
Character or integer identifier of the first channel.
Character or integer identifier of the second channel.
Numeric PLV value in [0, 1].
Lachaux, J. P., et al. (1999). Measuring phase synchrony in brain signals. Human Brain Mapping, 8(4), 194-208.
eegCoherence(), eegWPLI(), eegConnectivityMatrix(),
eegPlotConnectivity()
pe <- make_eeg(n_time = 5000, n_channels = 4, sr = 500) plv_df <- eegPLV(pe, band = c(8, 13)) head(plv_df)pe <- make_eeg(n_time = 5000, n_channels = 4, sr = 500) plv_df <- eegPLV(pe, band = c(8, 13)) head(plv_df)
Convenience wrapper that runs a complete EEG preprocessing pipeline in sequence: filtering, re-referencing, bad channel detection and interpolation, optional ICA, epoching, and artifact rejection. Each step can be toggled on or off.
eegPreprocess( x, filter = TRUE, lowcut = 0.1, highcut = 40, notch = NULL, rereference = TRUE, ref_type = "average", bad_channels = TRUE, interpolate = TRUE, ica = FALSE, epoch = FALSE, events = NULL, epoch_limits = c(-0.2, 0.8), baseline = c(-0.2, 0), artifact_reject = FALSE, threshold_uv = 100, assay_name = NULL, verbose = TRUE )eegPreprocess( x, filter = TRUE, lowcut = 0.1, highcut = 40, notch = NULL, rereference = TRUE, ref_type = "average", bad_channels = TRUE, interpolate = TRUE, ica = FALSE, epoch = FALSE, events = NULL, epoch_limits = c(-0.2, 0.8), baseline = c(-0.2, 0), artifact_reject = FALSE, threshold_uv = 100, assay_name = NULL, verbose = TRUE )
x |
A PhysioExperiment object with continuous (2D) EEG data. |
filter |
Logical; apply frequency filtering (default: TRUE). |
lowcut |
Low cutoff frequency in Hz for filtering (default: 0.1). |
highcut |
High cutoff frequency in Hz for filtering (default: 40). |
notch |
Notch filter center frequency in Hz (NULL for none). |
rereference |
Logical; apply re-referencing (default: TRUE). |
ref_type |
Re-referencing type (default: |
bad_channels |
Logical; detect and report bad channels (default: TRUE). |
interpolate |
Logical; interpolate detected bad channels (default: TRUE).
Requires electrode positions in colData (apply |
ica |
Logical; apply ICA-based artifact removal (default: FALSE).
Requires the |
epoch |
Logical; epoch the data around events (default: FALSE). |
events |
Event data for epoching (data.frame or integer vector).
Required if |
epoch_limits |
Epoch window in seconds (default: |
baseline |
Baseline window in seconds (default: |
artifact_reject |
Logical; reject artifact epochs (default: FALSE).
Only applies if |
threshold_uv |
Amplitude threshold for artifact rejection (default: 100). |
assay_name |
Starting assay name. If NULL, uses |
verbose |
Logical; print progress messages (default: TRUE). |
A PhysioExperiment object with processed data. The final assay name
depends on which steps are enabled. Processing log is stored in
metadata(x)$preprocess_log.
pe <- make_eeg(n_time = 10000, n_channels = 19, sr = 500) pe <- eegMontage(pe, system = "10-20") # filter + average-reference; bad-channel detection/interpolation disabled # so the example does not depend on the montage's neighbour geometry pe_proc <- eegPreprocess(pe, lowcut = 1, highcut = 40, notch = 50, bad_channels = FALSE, interpolate = FALSE, verbose = FALSE) pe_procpe <- make_eeg(n_time = 10000, n_channels = 19, sr = 500) pe <- eegMontage(pe, system = "10-20") # filter + average-reference; bad-channel detection/interpolation disabled # so the example does not depend on the montage's neighbour geometry pe_proc <- eegPreprocess(pe, lowcut = 1, highcut = 40, notch = 50, bad_channels = FALSE, interpolate = FALSE, verbose = FALSE) pe_proc
Computes absolute and relative spectral band powers for each channel using
Welch's method (windowed FFT averaging). Results are stored as a new assay
(channels x bands matrix of absolute power) and as relative power in
metadata(x)$qeeg.
eegQEEG( x, bands = NULL, window_sec = 2, overlap = 0.5, assay_name = NULL, output_assay = "qeeg" )eegQEEG( x, bands = NULL, window_sec = 2, overlap = 0.5, assay_name = NULL, output_assay = "qeeg" )
x |
A PhysioExperiment object with EEG data. |
bands |
Named list of frequency bands. Each element is a numeric vector of length 2 specifying the lower and upper frequency in Hz. Defaults to standard EEG bands: delta (1-4), theta (4-8), alpha (8-13), beta (13-30), gamma (30-50). |
window_sec |
Window length in seconds for Welch's method (default: 2). |
overlap |
Overlap fraction between windows, 0 to 1 (default: 0.5). |
assay_name |
Name of the input assay. If |
output_assay |
Name of the assay to store absolute power results
(default: |
Modified PhysioExperiment with:
Absolute power matrix (n_channels x n_bands) in output_assay
Band definitions and relative power in metadata(x)$qeeg,
a list containing bands, absolute_power,
relative_power, band_names, window_sec,
and overlap.
Nuwer, M. R., et al. (1999). IFCN standards for digital recording of clinical EEG. Electroencephalography and Clinical Neurophysiology, 106(3), 259-261.
Thatcher, R. W. (2010). Validity and reliability of quantitative electroencephalography. Journal of Neurotherapy, 14(2), 122-152.
eegSpikeDetect(), eegAsymmetry(), eegSlowing(),
eegPlotSpectrogram()
pe <- make_eeg(n_time = 5000, n_channels = 19, sr = 500) pe_qeeg <- eegQEEG(pe) qeeg_info <- S4Vectors::metadata(pe_qeeg)$qeeg print(qeeg_info$relative_power)pe <- make_eeg(n_time = 5000, n_channels = 19, sr = 500) pe_qeeg <- eegQEEG(pe) qeeg_info <- S4Vectors::metadata(pe_qeeg)$qeeg print(qeeg_info$relative_power)
Prints a guided walkthrough with runnable code examples for selected EEG analysis workflows. Covers ERP analysis, sleep staging, BCI classification, and connectivity analysis.
eegQuickStart(workflow = "all")eegQuickStart(workflow = "all")
workflow |
Character string: one of |
Invisibly returns NULL. Prints guide to console.
make_eeg(), make_eeg_erp(), make_eeg_sleep(),
make_eeg_bci()
eegQuickStart("erp")eegQuickStart("erp")
Applies a re-referencing scheme to EEG data. Re-referencing transforms the data by subtracting a reference signal from all channels, which can improve spatial resolution and comparability across studies.
eegRereference( x, ref_type = c("average", "robust", "median", "mastoids", "cz", "rest", "channel"), ref_channels = NULL, exclude = NULL, assay_name = NULL, output_assay = "rereferenced", robust_noise_sd = 4, robust_max_iter = 5 )eegRereference( x, ref_type = c("average", "robust", "median", "mastoids", "cz", "rest", "channel"), ref_channels = NULL, exclude = NULL, assay_name = NULL, output_assay = "rereferenced", robust_noise_sd = 4, robust_max_iter = 5 )
x |
A PhysioExperiment object. |
ref_type |
Re-referencing scheme: |
ref_channels |
Character vector of channel labels to use as reference
(required for |
exclude |
Character vector of channel labels to exclude from the
average reference calculation (only used for |
assay_name |
Name of the assay to re-reference. If NULL, uses
|
output_assay |
Name of the output assay (default: |
robust_noise_sd |
Noise threshold (SDs above the median channel
variance) for bad-channel detection in |
robust_max_iter |
Maximum PREP iterations for |
A PhysioExperiment object with re-referenced data in the specified
output assay. Stores reference info (including the channels excluded by the
robust reference) in metadata(x)$reference and logs the step in the
object's provenance.
Bigdely-Shamlo, N., et al. (2015). "The PREP pipeline: standardized preprocessing for large-scale EEG analysis." Frontiers in Neuroinformatics, 9, 16. doi:10.3389/fninf.2015.00016
pe <- make_eeg(n_time = 5000, n_channels = 19, sr = 500) pe_avg <- eegRereference(pe, ref_type = "average") pe_robust <- eegRereference(pe, ref_type = "robust") pe_median <- eegRereference(pe, ref_type = "median")pe <- make_eeg(n_time = 5000, n_channels = 19, sr = 500) pe_avg <- eegRereference(pe, ref_type = "average") pe_robust <- eegRereference(pe, ref_type = "robust") pe_median <- eegRereference(pe, ref_type = "median")
Calculates summary sleep architecture metrics from staged sleep data.
Requires that eegSleepStage() has been run and results are stored
in metadata(x)$sleep_stages.
eegSleepMetrics(x)eegSleepMetrics(x)
x |
A PhysioExperiment object with sleep staging results in
|
A data.frame with columns:
Character name of the sleep metric.
Numeric value of the metric.
Character unit of measurement.
Metrics include:
total_sleep_time: Time in N1+N2+N3+REM (minutes)
sleep_efficiency: TST / total recording time * 100 (percent)
waso: Wake after sleep onset (minutes)
sleep_latency: Time to first non-Wake epoch (minutes)
rem_latency: Time from first sleep to first REM (minutes)
pct_N1: Percentage of TST in N1
pct_N2: Percentage of TST in N2
pct_N3: Percentage of TST in N3
pct_REM: Percentage of TST in REM
pct_W: Percentage of total time in Wake
Berry, R. B., et al. (2017). AASM Scoring Manual Updates for 2017. Journal of Clinical Sleep Medicine, 13(5), 665-666.
eegSleepStage(), eegSpindleDetect(),
eegKcomplexDetect(), eegSlowWaveDetect(), eegPlotHypnogram()
pe <- make_eeg_sleep(n_time = 150000, n_channels = 2, sr = 500) stages <- eegSleepStage(pe, epoch_sec = 30) S4Vectors::metadata(pe)$sleep_stages <- stages metrics <- eegSleepMetrics(pe) print(metrics)pe <- make_eeg_sleep(n_time = 150000, n_channels = 2, sr = 500) stages <- eegSleepStage(pe, epoch_sec = 30) S4Vectors::metadata(pe)$sleep_stages <- stages metrics <- eegSleepMetrics(pe) print(metrics)
Classifies EEG epochs into sleep stages (Wake, N1, N2, N3, REM) using spectral power analysis based on simplified AASM criteria. Each epoch is scored by computing spectral band powers (delta, theta, alpha, sigma, beta) and applying rule-based classification.
eegSleepStage( x, method = c("spectral", "rule_based"), epoch_sec = 30, assay_name = NULL )eegSleepStage( x, method = c("spectral", "rule_based"), epoch_sec = 30, assay_name = NULL )
x |
A PhysioExperiment object with EEG data. |
method |
Staging method: |
epoch_sec |
Epoch duration in seconds (default: 30, AASM standard). |
assay_name |
Input assay name. If |
A data.frame with columns:
Integer epoch number.
Character sleep stage: "W", "N1", "N2", "N3", or "REM".
Integer start sample of the epoch.
Integer end sample of the epoch.
Numeric delta band power (0.5-4 Hz).
Numeric theta band power (4-8 Hz).
Numeric alpha band power (8-13 Hz).
Numeric sigma band power (12-16 Hz).
Numeric beta band power (16-30 Hz).
The result is also stored in metadata(x)$sleep_stages.
Berry, R. B., et al. (2017). AASM Scoring Manual Updates for 2017. Journal of Clinical Sleep Medicine, 13(5), 665-666.
eegSpindleDetect(), eegKcomplexDetect(),
eegSlowWaveDetect(), eegSleepMetrics(), eegPlotHypnogram()
pe <- make_eeg_sleep(n_time = 90000, n_channels = 2, sr = 500) stages <- eegSleepStage(pe, epoch_sec = 30) head(stages)pe <- make_eeg_sleep(n_time = 90000, n_channels = 2, sr = 500) stages <- eegSleepStage(pe, epoch_sec = 30) head(stages)
Detects pathological EEG slowing using spectral analysis. Supports three methods: theta/delta ratio (TDR), delta-theta/alpha-beta ratio (DTAR), and peak frequency analysis. Each channel is classified into normal, mild, moderate, or severe slowing categories.
eegSlowing( x, method = c("tdr", "dtar", "peak_frequency"), bands = NULL, assay_name = NULL )eegSlowing( x, method = c("tdr", "dtar", "peak_frequency"), bands = NULL, assay_name = NULL )
x |
A PhysioExperiment object with EEG data. |
method |
Analysis method: |
bands |
Named list of frequency bands for TDR and DTAR methods. Defaults to standard EEG bands. |
assay_name |
Name of the input assay. If |
A data.frame with columns:
Integer channel index.
Character name of the metric used.
Numeric value of the metric.
Character: "normal",
"mild_slowing", "moderate_slowing", or
"severe_slowing".
Nuwer, M. R., et al. (1999). IFCN standards for digital recording of clinical EEG. Electroencephalography and Clinical Neurophysiology, 106(3), 259-261.
eegSpikeDetect(), eegQEEG(), eegAsymmetry(),
eegSuppression()
pe <- make_eeg(n_time = 5000, n_channels = 19, sr = 500) result <- eegSlowing(pe, method = "dtar") print(result)pe <- make_eeg(n_time = 5000, n_channels = 19, sr = 500) result <- eegSlowing(pe, method = "dtar") print(result)
Identifies slow oscillations in EEG data by bandpass filtering in the slow wave frequency range, finding zero crossings, and measuring negative half-wave amplitudes and slopes.
eegSlowWaveDetect( x, min_amplitude = 75, freq_range = c(0.5, 2), min_duration_ms = 250, max_duration_ms = 1000, assay_name = NULL )eegSlowWaveDetect( x, min_amplitude = 75, freq_range = c(0.5, 2), min_duration_ms = 250, max_duration_ms = 1000, assay_name = NULL )
x |
A PhysioExperiment object with EEG data. |
min_amplitude |
Minimum absolute negative peak amplitude in microvolts (default: 75). |
freq_range |
Numeric vector of length 2 specifying the slow wave
frequency range in Hz (default: |
min_duration_ms |
Minimum half-wave duration in milliseconds (default: 250). |
max_duration_ms |
Maximum half-wave duration in milliseconds (default: 1000). |
assay_name |
Input assay name. If |
A data.frame with columns:
Integer channel index.
Integer sample at first zero crossing.
Integer sample at second zero crossing.
Numeric negative peak amplitude.
Numeric positive peak amplitude.
Numeric half-wave duration in milliseconds.
Numeric slope from negative to positive peak (microvolts per millisecond).
Berry, R. B., et al. (2017). AASM Scoring Manual Updates for 2017. Journal of Clinical Sleep Medicine, 13(5), 665-666.
eegSleepStage(), eegSpindleDetect(),
eegKcomplexDetect(), eegSleepMetrics()
pe <- make_eeg_sleep(n_time = 150000, n_channels = 2, sr = 500) slow_waves <- eegSlowWaveDetect(pe) head(slow_waves)pe <- make_eeg_sleep(n_time = 150000, n_channels = 2, sr = 500) slow_waves <- eegSlowWaveDetect(pe) head(slow_waves)
Estimates brain source activity from scalp EEG data using distributed
source imaging methods. Requires a forward model from
eegForwardModel.
eegSourceEstimate( x, forward_model, method = c("sloreta", "eloreta", "mne", "dspm"), lambda = 0.05, assay_name = NULL, output_assay = "source" )eegSourceEstimate( x, forward_model, method = c("sloreta", "eloreta", "mne", "dspm"), lambda = 0.05, assay_name = NULL, output_assay = "source" )
x |
A PhysioExperiment object with EEG data. |
forward_model |
A forward model list as returned by
|
method |
Source estimation method: |
lambda |
Regularization parameter (default: 0.05). Higher values produce smoother solutions. |
assay_name |
Name of the input assay. If |
output_assay |
Name for the output assay containing source estimates
(default: |
Modified PhysioExperiment with source estimates stored in
output_assay. The assay is a matrix of dimensions
n_time x (n_sources * 3). Sets metadata(x)$source_estimate
with a list containing: method, lambda,
n_sources, n_source_cols, source_positions,
output_assay, orientation_count, and coordinate provenance.
Pascual-Marqui, R. D. (2002). Standardized low-resolution brain electromagnetic tomography (sLORETA). Methods and Findings in Experimental and Clinical Pharmacology, 24(Suppl D), 5-12.
eegForwardModel(), eegBeamformer(), eegSourcePower(),
eegPlotSource(), eegPlotGlassBrain()
pe <- make_eeg(n_time = 500, n_channels = 19, sr = 250) fm <- eegForwardModel(pe, method = "spherical", n_sources = 50) pe <- eegSourceEstimate(pe, fm, method = "mne")pe <- make_eeg(n_time = 500, n_channels = 19, sr = 250) fm <- eegForwardModel(pe, method = "spherical", n_sources = 50) pe <- eegSourceEstimate(pe, fm, method = "mne")
Computes spectral band power for each source from source-estimated EEG
data. Requires prior source estimation via eegSourceEstimate.
eegSourcePower(x, bands = NULL, source_assay = "source")eegSourcePower(x, bands = NULL, source_assay = "source")
x |
A PhysioExperiment object with source estimates. |
bands |
Named list of frequency bands, each a numeric vector of
length 2 (lower, upper Hz). If |
source_assay |
Name of the assay containing source data (default:
|
A data.frame with columns:
Integer source index.
Character name of the frequency band.
Numeric spectral power in the band.
Pascual-Marqui, R. D. (2002). Standardized low-resolution brain electromagnetic tomography (sLORETA). Methods and Findings in Experimental and Clinical Pharmacology, 24(Suppl D), 5-12.
eegSourceEstimate(), eegForwardModel(), eegBeamformer()
pe <- make_eeg(n_time = 1000, n_channels = 19, sr = 250) fm <- eegForwardModel(pe, method = "spherical", n_sources = 20) pe <- eegSourceEstimate(pe, fm, method = "mne") bp <- eegSourcePower(pe) head(bp)pe <- make_eeg(n_time = 1000, n_channels = 19, sr = 250) fm <- eegForwardModel(pe, method = "spherical", n_sources = 20) pe <- eegSourceEstimate(pe, fm, method = "mne") bp <- eegSourcePower(pe) head(bp)
Identifies epileptiform spike discharges in multi-channel EEG using either morphology-based derivative analysis or template matching via cross-correlation. The morphology method detects sharp transients by thresholding the first derivative, while the template method cross-correlates a canonical spike waveform with each channel.
eegSpikeDetect( x, method = c("morphology", "template"), threshold_sd = 4, min_duration_ms = 20, max_duration_ms = 200, min_amplitude = 50, assay_name = NULL )eegSpikeDetect( x, method = c("morphology", "template"), threshold_sd = 4, min_duration_ms = 20, max_duration_ms = 200, min_amplitude = 50, assay_name = NULL )
x |
A PhysioExperiment object with EEG data. |
method |
Detection method: |
threshold_sd |
Number of standard deviations above the mean derivative magnitude for detection (default: 4). |
min_duration_ms |
Minimum spike duration in milliseconds (default: 20). |
max_duration_ms |
Maximum spike duration in milliseconds (default: 200). |
min_amplitude |
Minimum peak amplitude in microvolts for a valid spike detection (default: 50). |
assay_name |
Name of the assay to use. If |
A data.frame with columns:
Integer channel index.
Integer sample index of the spike peak.
Time of the spike in seconds.
Peak amplitude at the spike location.
Estimated spike duration in milliseconds.
Confidence score for the detection.
Nuwer, M. R., et al. (1999). IFCN standards for digital recording of clinical EEG. Electroencephalography and Clinical Neurophysiology, 106(3), 259-261.
eegQEEG(), eegAsymmetry(), eegSlowing()
pe <- make_eeg_spikes(n_time = 30000, n_channels = 19, sr = 500, n_spikes = 15) spikes <- eegSpikeDetect(pe, method = "morphology") head(spikes)pe <- make_eeg_spikes(n_time = 30000, n_channels = 19, sr = 500, n_spikes = 15) spikes <- eegSpikeDetect(pe, method = "morphology") head(spikes)
Identifies sleep spindles in EEG data by bandpass filtering in the sigma frequency range, computing an RMS envelope, and detecting continuous segments exceeding a threshold. Spindle frequency is estimated from zero crossings in the bandpassed signal.
eegSpindleDetect( x, method = c("sigma", "wavelet"), freq_range = c(11, 16), min_duration_ms = 500, max_duration_ms = 2000, threshold_sd = 1.5, assay_name = NULL )eegSpindleDetect( x, method = c("sigma", "wavelet"), freq_range = c(11, 16), min_duration_ms = 500, max_duration_ms = 2000, threshold_sd = 1.5, assay_name = NULL )
x |
A PhysioExperiment object with EEG data. |
method |
Detection method: |
freq_range |
Numeric vector of length 2 specifying the spindle
frequency range in Hz (default: |
min_duration_ms |
Minimum spindle duration in milliseconds (default: 500). |
max_duration_ms |
Maximum spindle duration in milliseconds (default: 2000). |
threshold_sd |
Number of standard deviations above the mean for detection threshold (default: 1.5). |
assay_name |
Input assay name. If |
A data.frame with columns:
Integer channel index.
Integer start sample of the spindle.
Integer end sample of the spindle.
Numeric spindle duration in milliseconds.
Integer sample index of peak amplitude.
Numeric peak RMS amplitude.
Numeric estimated spindle frequency in Hz.
Berry, R. B., et al. (2017). AASM Scoring Manual Updates for 2017. Journal of Clinical Sleep Medicine, 13(5), 665-666.
Molle, M., et al. (2011). Fast and slow spindles during the sleep slow oscillation. Sleep, 34(10), 1411-1421.
eegSleepStage(), eegKcomplexDetect(),
eegSlowWaveDetect(), eegSleepMetrics()
pe <- make_eeg_sleep(n_time = 150000, n_channels = 2, sr = 500) spindles <- eegSpindleDetect(pe) head(spindles)pe <- make_eeg_sleep(n_time = 150000, n_channels = 2, sr = 500) spindles <- eegSpindleDetect(pe) head(spindles)
Detects Steady-State Visual Evoked Potentials using canonical correlation analysis (CCA) or filter-bank CCA (FBCCA). For each candidate stimulus frequency, a CCA is computed between the EEG data and sinusoidal reference signals at the frequency and its harmonics.
eegSSVEP( x, frequencies, n_harmonics = 3, method = c("cca", "fbcca"), assay_name = NULL )eegSSVEP( x, frequencies, n_harmonics = 3, method = c("cca", "fbcca"), assay_name = NULL )
x |
A PhysioExperiment object with EEG data. If 3D (time x channels x trials), data is averaged across trials before analysis. |
frequencies |
Numeric vector of target stimulus frequencies in Hz. |
n_harmonics |
Number of harmonics to include in reference signals (default: 3). |
method |
Detection method: |
assay_name |
Input assay name (default: first assay). |
A data.frame with columns: frequency (numeric target
frequency in Hz), correlation (numeric CCA correlation),
snr (numeric signal-to-noise ratio), and
predicted_class (numeric predicted stimulus frequency).
Blankertz, B., et al. (2008). Optimizing spatial filters for robust EEG single-trial analysis. IEEE Signal Processing Magazine, 25(1), 41-56.
Norcia, A. M., et al. (2015). The steady-state visual evoked potential in vision research: a review. Journal of Vision, 15(6), 4.
eegCSP(), eegBCIfeatures(), eegBCIclassify()
pe <- make_eeg_bci(n_trials = 10, n_channels = 8, sr = 256) result <- eegSSVEP(pe, frequencies = c(10, 12, 15), method = "cca")pe <- make_eeg_bci(n_trials = 10, n_channels = 8, sr = 256) result <- eegSSVEP(pe, frequencies = c(10, 12, 15), method = "cca")
Computes the Short-Time Fourier Transform (STFT) spectrogram for multi-channel EEG data. Uses a sliding window with configurable overlap and window function to produce a time-frequency power representation.
eegSTFT( x, window_sec = 0.5, overlap = 0.75, window_type = c("hanning", "hamming", "rectangular"), assay_name = NULL, output_assay = "stft_power" )eegSTFT( x, window_sec = 0.5, overlap = 0.75, window_type = c("hanning", "hamming", "rectangular"), assay_name = NULL, output_assay = "stft_power" )
x |
A PhysioExperiment object with EEG data (2D: time x channels). |
window_sec |
Window length in seconds (default: 0.5). |
overlap |
Overlap fraction between adjacent windows, from 0 to 1 exclusive (default: 0.75). |
window_type |
Window function to apply: |
assay_name |
Name of the input assay. If |
output_assay |
Name the result is stored under. Despite the
argument's name this is a key in |
Modified PhysioExperiment with:
3D power array (time_bins x frequencies x channels) in
output_assay
Time bin centers, frequency vector, and parameters in
metadata(x)$stft, a list containing time_axis,
freq_axis, window_sec, overlap,
window_type, window_length, and hop_size
Tallon-Baudry, C., et al. (1997). Oscillatory gamma-band activity during conscious perception. Trends in Cognitive Sciences, 3(4), 151-162.
eegMorletWavelet(), eegMultitaper(), eegPlotSpectrogram()
pe <- make_eeg(n_time = 2000, n_channels = 4, sr = 250) pe_stft <- eegSTFT(pe, window_sec = 0.5, overlap = 0.75) # results are stored in metadata(x)$stft str(S4Vectors::metadata(pe_stft)$stft, max.level = 1)pe <- make_eeg(n_time = 2000, n_channels = 4, sr = 250) pe_stft <- eegSTFT(pe, window_sec = 0.5, overlap = 0.75) # results are stored in metadata(x)$stft str(S4Vectors::metadata(pe_stft)$stft, max.level = 1)
Identifies periods of burst and suppression in EEG data by computing
the root mean square (RMS) amplitude in sliding windows. Suppression
segments are defined as consecutive windows where RMS falls below
the specified threshold for at least min_duration_ms.
eegSuppression( x, threshold = 10, min_duration_ms = 500, window_ms = 500, assay_name = NULL )eegSuppression( x, threshold = 10, min_duration_ms = 500, window_ms = 500, assay_name = NULL )
x |
A PhysioExperiment object with EEG data. |
threshold |
RMS amplitude threshold below which signal is considered suppressed (default: 10). |
min_duration_ms |
Minimum duration in milliseconds for a segment to be classified as suppression (default: 500). |
window_ms |
Window length in milliseconds for RMS computation (default: 500). |
assay_name |
Name of the input assay. If |
A data.frame with columns:
Character: "burst" or "suppression".
Integer start sample of the segment.
Integer end sample of the segment.
Numeric duration of the segment in milliseconds.
An attribute "bsr" (Burst-Suppression Ratio) is attached,
representing the percentage of total time in suppression.
Nuwer, M. R., et al. (1999). IFCN standards for digital recording of clinical EEG. Electroencephalography and Clinical Neurophysiology, 106(3), 259-261.
eegSpikeDetect(), eegQEEG(), eegSlowing()
pe <- make_eeg(n_time = 10000, n_channels = 4, sr = 500) result <- eegSuppression(pe, threshold = 10) print(attr(result, "bsr"))pe <- make_eeg(n_time = 10000, n_channels = 4, sr = 500) result <- eegSuppression(pe, threshold = 10) print(attr(result, "bsr"))
Applies the spherical-spline surface Laplacian (current source density, CSD)
of Perrin et al. (1989). CSD is reference-free and acts as a spatial
high-pass filter, deblurring volume conduction so that each channel reflects
the radial current under it rather than the whole-head average — sharpening
focal topographies and attenuating broadly distributed activity. It needs
electrode positions (from colData columns pos_x/pos_y/pos_z, else matched
to a standard 10-10/10-20 montage by channel label).
eegSurfaceLaplacian( x, order = 4L, lambda = 1e-05, n_terms = 50L, assay_name = NULL, output_assay = "csd" )eegSurfaceLaplacian( x, order = 4L, lambda = 1e-05, n_terms = 50L, assay_name = NULL, output_assay = "csd" )
x |
A |
order |
Spline flexibility |
lambda |
Smoothing / regularization added to the spline system (default
|
n_terms |
Number of Legendre terms in the g/h series (default 50). |
assay_name |
Assay to transform (default: the object's default assay). |
output_assay |
Name of the assay to store the CSD in (default |
The PhysioExperiment with the CSD stored in output_assay (same
shape as the input assay; units are µV/m² up to a scale/head-radius
constant).
Perrin, Pernier, Bertrand & Echallier (1989), Electroenceph Clin Neurophysiol; Kayser & Tenke (2006), Clin Neurophysiol.
eegRereference(), eegPlotTopomap(), eegConnectivityMatrix()
pe <- make_eeg(n_time = 500, n_channels = 19, sr = 250) pe <- eegSurfaceLaplacian(pe) "csd" %in% SummarizedExperiment::assayNames(pe)pe <- make_eeg(n_time = 500, n_channels = 19, sr = 250) pe <- eegSurfaceLaplacian(pe) "csd" %in% SummarizedExperiment::assayNames(pe)
Computes the Weighted Phase Lag Index and its debiased variant between all EEG channel pairs. The wPLI reduces the influence of volume conduction by weighting the phase differences by the magnitude of the imaginary part of the cross-spectrum, computed via Welch's method.
eegWPLI( x, band = c(8, 13), window_sec = 2, overlap = 0.5, assay_name = NULL, debiased = TRUE )eegWPLI( x, band = c(8, 13), window_sec = 2, overlap = 0.5, assay_name = NULL, debiased = TRUE )
x |
A PhysioExperiment object with EEG data (2D: time x channels). |
band |
Numeric vector of length 2 specifying the frequency band in Hz
over which to compute wPLI (default: |
window_sec |
Window length in seconds for spectral estimation (default: 2). |
overlap |
Overlap fraction between adjacent windows, from 0 to 1 exclusive (default: 0.5). |
assay_name |
Name of the input assay. If |
debiased |
Logical; also compute the unbiased debiased wPLI (default TRUE). |
The debiased wPLI corrects for sample-size bias:
A data.frame with columns:
Character or integer identifier of the first channel.
Character or integer identifier of the second channel.
Numeric wPLI value in [0, 1].
Numeric debiased wPLI (Vinck et al., 2011, Eq. 6),
computed by the shared wpliEstimate estimator
so it matches PhysioCrossModal::weightedPLI. It is unbiased and
therefore distributes around 0 for independent signals (it is
not clamped to be non-negative).
Lachaux, J. P., et al. (1999). Measuring phase synchrony in brain signals. Human Brain Mapping, 8(4), 194-208.
Vinck, M., et al. (2011). An improved index of phase-synchronization for electrophysiological data in the presence of volume-conduction, noise and sample-size bias. NeuroImage, 55(4), 1548-1565.
eegCoherence(), eegPLV(), eegConnectivityMatrix(),
eegPlotConnectivity(), wpliEstimate
pe <- make_eeg(n_time = 5000, n_channels = 4, sr = 500) wpli_df <- eegWPLI(pe, band = c(8, 13)) head(wpli_df)pe <- make_eeg(n_time = 5000, n_channels = 4, sr = 500) wpli_df <- eegWPLI(pe, band = c(8, 13)) head(wpli_df)
Computes the fuzzy entropy (FuzzyEn) of a one-dimensional signal (Chen et al.,
2007) – the fuzzy generalization of the sample entropy. Sample entropy
counts template matches with a crisp threshold (a Heaviside step: two vectors
either match within tolerance or do not); fuzzy entropy replaces that
hard step with a smooth exponential membership
, so near-matches contribute partially. This makes
FuzzyEn markedly more robust and continuous than sample entropy, especially on
short or noisy segments where the crisp count is unstable. Each embedding
vector has its own baseline (mean) removed before the Chebyshev distance is
taken, following Chen et al.
fuzzyEntropy(x, dimension = 2L, r = 0.2, delay = 1L, n = 1)fuzzyEntropy(x, dimension = 2L, r = 0.2, delay = 1L, n = 1)
x |
A numeric vector (the time series). |
dimension |
Embedding dimension |
r |
Tolerance as a fraction of the signal's standard deviation; the
distance tolerance is |
delay |
Time delay (lag) in samples (default 1). |
n |
Fuzzy power (exponent) of the membership function (default 1). |
This implementation reproduces NeuroKit2's entropy_fuzzy
bit-for-bit (the default tolerance = "sd" there corresponds to
r = 0.2).
A single numeric value, the fuzzy entropy.
Chen, W., Zhuang, J., Yu, W., & Wang, Z. (2009). "Measuring complexity using FuzzyEn, ApEn, and SampEn." Medical Engineering & Physics, 31(1), 61–68. doi:10.1016/j.medengphy.2008.04.005
dispersionEntropy, svdEntropy,
renyiEntropy, tsallisEntropy.
set.seed(1) fuzzyEntropy(rnorm(300), dimension = 2) # fuzzy generalization of sample entropyset.seed(1) fuzzyEntropy(rnorm(300), dimension = 2) # fuzzy generalization of sample entropy
Computes the increment entropy (IncrEn) of a one-dimensional signal (Liu et
al., 2016) – a symbolic complexity measure defined on the signal's
increments (successive differences) rather than its amplitudes. Each
increment in an embedding vector is mapped to a word letter combining its
sign () with a magnitude class in
obtained by quantizing
relative to the vector's own standard deviation; IncrEn is the Shannon entropy
of the resulting word distribution, normalized by . Because it
encodes both the direction and the graded size of changes, it is sensitive to
dynamics that amplitude-based entropies miss, and is a distinct mechanism from
the amplitude-histogram (renyiEntropy, tsallisEntropy),
NCDF-pattern (dispersionEntropy) and template-matching
(fuzzyEntropy) entropies.
incrementEntropy(x, dimension = 2L, q = 4L)incrementEntropy(x, dimension = 2L, q = 4L)
x |
A numeric vector (the time series). |
dimension |
Embedding dimension |
q |
Number of magnitude quantization levels (default 4); each increment
is binned into one of |
This implementation reproduces NeuroKit2's entropy_increment
bit-for-bit.
A single numeric value, the increment entropy.
Liu, X., Jiang, A., Xu, N., & Xue, J. (2016). "Increment Entropy as a Measure of Complexity for Time Series." Entropy, 18(1), 22. doi:10.3390/e18010022
dispersionEntropy, fuzzyEntropy,
renyiEntropy, tsallisEntropy.
set.seed(1) incrementEntropy(rnorm(1000), dimension = 2, q = 4)set.seed(1) incrementEntropy(rnorm(1000), dimension = 2, q = 4)
Computes Katz's fractal dimension (KFD) of a one-dimensional signal
(Katz, 1988) – a waveform-complexity measure derived from the total length of
the signal curve relative to its extent. Let be the sum of the
absolute successive differences (the curve length), their mean, and
the maximum absolute distance from the first sample; then
. A smoother, more regular
signal has a lower KFD; a more convoluted (noise-like) waveform a higher one.
katzFD(x)katzFD(x)
x |
A numeric vector (the time series). |
This uses the amplitude-only convention adopted by the de-facto reference
implementations (Python antropy, NeuroKit2, pyeeg,
mne-features), in which both the successive distances and the extent are
measured in the signal's amplitude units alone; it reproduces
antropy.katz_fd and NeuroKit2's fractal_katz bit-for-bit.
(Katz's original definition uses the Euclidean distance in the
sample-index/amplitude plane, which mixes the two axes' units, is
scale-dependent, and is not comparable across tools; the amplitude-only form
is what the field uses and what makes KFD reproducible.)
A single numeric value, Katz's fractal dimension.
Katz, M. J. (1988). "Fractals and the analysis of waveforms." Computers in Biology and Medicine, 18(3), 145–156. doi:10.1016/0010-4825(88)90041-8
petrosianFD for the derivative-sign-change fractal view,
svdEntropy, eegComplexity for the multi-measure
wrapper.
katzFD(sin(seq(0, 20 * pi, length.out = 500))) # low (smooth oscillation) set.seed(1); katzFD(rnorm(500)) # higher (noise-like)katzFD(sin(seq(0, 20 * pi, length.out = 500))) # low (smooth oscillation) set.seed(1); katzFD(rnorm(500)) # higher (noise-like)
Generates multi-channel EEG with alpha (10 Hz) and beta (20 Hz) oscillations plus pink noise. Channels are labeled using the International 10-20 system.
make_eeg(n_time = 5000, n_channels = 19, sr = 500)make_eeg(n_time = 5000, n_channels = 19, sr = 500)
n_time |
Number of time points (default: 5000 = 10s at 500 Hz). |
n_channels |
Number of EEG channels (default: 19, standard 10-20). |
sr |
Sampling rate in Hz (default: 500). |
A PhysioExperiment with simulated EEG in the "raw" assay.
Channel labels follow the International 10-20 system (Fp1, Fp2, F7, ...,
O1, O2). Column data contains label and type fields.
Each channel is generated independently, so the channels are only weakly
correlated: on a 19-channel, 10 s record the median absolute between-channel
correlation is about 0.26. Real EEG is spatially smooth and neighbouring
electrodes correlate strongly, which several methods rely on. In particular
eegBadChannels judges a channel partly by its correlation with
the others against corr_threshold (default 0.4), so on this generator's
output it flags every channel as bad – and anything downstream that needs good
channels, such as eegInterpolate, then has none to work with.
That is the generator being independent, not the detector being wrong. Use it
for per-channel operations – filtering, spectra, epoching, per-channel
measures – and use real data, or a generator with a shared spatial component,
when exercising anything that assumes channels covary.
pe <- make_eeg(n_time = 2500, n_channels = 4, sr = 250) dim(SummarizedExperiment::assay(pe, "raw")) # 2500 x 4
make_eeg_erp(), make_eeg_sleep(), make_eeg_bci(),
make_eeg_spikes(), eegFilter(), eegCoherence()
Generates epoched EEG with two classes: left motor imagery (mu ERD over C4) and right motor imagery (mu ERD over C3). Also includes SSVEP at specified frequencies at occipital channels. Data is stored as a 3D array (time x channels x trials).
make_eeg_bci(n_trials = 30, n_channels = 8, sr = 256, trial_sec = 4)make_eeg_bci(n_trials = 30, n_channels = 8, sr = 256, trial_sec = 4)
n_trials |
Number of trials per class (default: 30). Total trials
will be |
n_channels |
Number of channels (default: 8). |
sr |
Sampling rate in Hz (default: 256). |
trial_sec |
Trial duration in seconds (default: 4.0). |
A PhysioExperiment with a 3D "raw" assay (time x channels x
total_trials). Sets metadata(x)$labels with a character vector
of class labels ("left" or "right") for each trial.
make_eeg(), eegCSP(), eegBCIfeatures(),
eegBCIclassify(), eegMotorImagery()
pe <- make_eeg_bci(n_trials = 5, n_channels = 4, sr = 128) dim(SummarizedExperiment::assay(pe, "raw")) # 512 x 4 x 10pe <- make_eeg_bci(n_trials = 5, n_channels = 4, sr = 128) dim(SummarizedExperiment::assay(pe, "raw")) # 512 x 4 x 10
Generates epoched EEG (3D array: time x channels x epochs) with known ERP components: N100 (negative peak at ~100ms) and P300 (positive peak at ~300ms). Target epochs have larger P300 amplitude than standard epochs.
make_eeg_erp(n_epochs = 40, n_channels = 19, sr = 250, epoch_sec = 1)make_eeg_erp(n_epochs = 40, n_channels = 19, sr = 250, epoch_sec = 1)
n_epochs |
Number of epochs (default: 40). |
n_channels |
Number of channels (default: 19). |
sr |
Sampling rate in Hz (default: 250). |
epoch_sec |
Epoch duration in seconds (default: 1.0). |
A PhysioExperiment with a 3D "raw" assay (time x channels x
epochs) containing simulated ERP data. Sets
metadata(x)$conditions with a character vector of epoch
conditions ("target" or "standard").
make_eeg(), eegERPdetect(), eegERPmeasure(),
eegERPbaseline(), eegERPtest()
pe <- make_eeg_erp(n_epochs = 10, n_channels = 4, sr = 250) dim(SummarizedExperiment::assay(pe, "raw")) # 250 x 4 x 10pe <- make_eeg_erp(n_epochs = 10, n_channels = 4, sr = 250) dim(SummarizedExperiment::assay(pe, "raw")) # 250 x 4 x 10
Generates continuous EEG with segments having distinct frequency content matching AASM sleep stages: Wake (alpha), N1 (theta), N2 (spindles + K), N3 (delta/SWA), REM (mixed low-voltage). Each 30-second epoch is assigned a stage in a cyclic pattern.
make_eeg_sleep(n_time = 150000, n_channels = 2, sr = 500)make_eeg_sleep(n_time = 150000, n_channels = 2, sr = 500)
n_time |
Number of time points (default: 150000 = 5min at 500Hz). |
n_channels |
Number of channels (default: 2, C3 and C4). |
sr |
Sampling rate in Hz (default: 500). |
A PhysioExperiment with simulated sleep EEG in the "raw"
assay. Sets metadata(x)$sleep_stages with a data.frame
containing columns: epoch, stage (ground truth),
start_sample, and end_sample.
make_eeg(), eegSleepStage(), eegSpindleDetect(),
eegKcomplexDetect(), eegSleepMetrics()
pe <- make_eeg_sleep(n_time = 30000, n_channels = 2, sr = 500) dim(SummarizedExperiment::assay(pe, "raw")) # 30000 x 2pe <- make_eeg_sleep(n_time = 30000, n_channels = 2, sr = 500) dim(SummarizedExperiment::assay(pe, "raw")) # 30000 x 2
Generates multi-channel EEG with sharp transient spikes at known locations. Spikes are ~50-100ms duration with high amplitude and sharp morphology, inserted at random time points across a subset of channels.
make_eeg_spikes(n_time = 30000, n_channels = 19, sr = 500, n_spikes = 15)make_eeg_spikes(n_time = 30000, n_channels = 19, sr = 500, n_spikes = 15)
n_time |
Number of time points (default: 30000 = 60s at 500Hz). |
n_channels |
Number of channels (default: 19). |
sr |
Sampling rate in Hz (default: 500). |
n_spikes |
Number of epileptic spikes to insert (default: 15). |
A PhysioExperiment with simulated clinical EEG in the "raw"
assay. Sets metadata(x)$spike_locations with a data.frame
containing columns: spike_id, sample (sample index),
time_sec (time in seconds), and channels (list column
of affected channel indices).
make_eeg(), eegSpikeDetect(), eegQEEG(),
eegSlowing()
pe <- make_eeg_spikes(n_time = 5000, n_channels = 4, sr = 250, n_spikes = 3) dim(SummarizedExperiment::assay(pe, "raw")) # 5000 x 4pe <- make_eeg_spikes(n_time = 5000, n_channels = 4, sr = 250, n_spikes = 3) dim(SummarizedExperiment::assay(pe, "raw")) # 5000 x 4
Computes the multiscale entropy (MSE; Costa, Goldberger & Peng, 2002) of a
one-dimensional signal: the sample entropy of the signal after coarse-graining
it at a series of time scales. At scale the signal is partitioned into
non-overlapping windows of length , each window is replaced by its mean,
and the sample entropy (embedding m, tolerance r times the SD of
the ORIGINAL signal, held fixed across scales) of that coarse-grained series is
the MSE at scale . A signal whose MSE stays high or rises at coarse
scales carries structure across time scales; white noise, by contrast, has an
MSE that falls monotonically from scale 1.
multiscaleEntropy(x, m = 2L, r = 0.2, scales = 1:8)multiscaleEntropy(x, m = 2L, r = 0.2, scales = 1:8)
x |
A numeric vector (the time series). |
m |
Embedding dimension for the sample entropy (default 2). |
r |
Tolerance as a fraction of the ORIGINAL signal's SD (default 0.2), held fixed across all scales (Costa's convention). |
scales |
Integer vector of time scales (default |
A named numeric vector of sample entropies, one per scale
(scale1, scale2, ...). NA for a scale whose
coarse-grained series is too short or yields no template matches.
Costa, M., Goldberger, A. L., & Peng, C.-K. (2002). "Multiscale entropy analysis of complex physiologic time series." Physical Review Letters, 89(6), 068102. doi:10.1103/PhysRevLett.89.068102
eegComplexity for the multi-measure wrapper;
PhysioMoCap's sampleEntropy for the single-scale measure.
set.seed(1); multiscaleEntropy(rnorm(1000), scales = 1:5) # noise: falls with scaleset.seed(1); multiscaleEntropy(rnorm(1000), scales = 1:5) # noise: falls with scale
Computes the Petrosian fractal dimension of a one-dimensional signal
(Petrosian, 1995) – a fast waveform-complexity measure based on the number of
sign changes in the signal's derivative (i.e. the density of local extrema).
A smooth, oscillatory signal has few derivative sign changes and a Petrosian FD
near 1; a complex or noise-like signal has many and a higher FD.
,
where is the signal length and the number of sign
changes in the first difference.
petrosianFD(x)petrosianFD(x)
x |
A numeric vector (the time series). |
A single numeric value, the Petrosian fractal dimension (typically in
for physiological signals).
Petrosian, A. (1995). "Kolmogorov complexity of finite sequences and recognition of different preictal EEG patterns." In Proceedings of the Eighth IEEE Symposium on Computer-Based Medical Systems, 212–217. doi:10.1109/CBMS.1995.465426
svdEntropy for the singular-value complexity view,
eegComplexity for the multi-measure wrapper.
petrosianFD(sin(seq(0, 20 * pi, length.out = 500))) # low (smooth oscillation) set.seed(1); petrosianFD(rnorm(500)) # higher (noise-like)petrosianFD(sin(seq(0, 20 * pi, length.out = 500))) # low (smooth oscillation) set.seed(1); petrosianFD(rnorm(500)) # higher (noise-like)
Computes the phase entropy (PhasEn) of a one-dimensional signal (Rohila &
Sharma, 2019) from its Second-Order Difference Plot (SODP). Each point plots
the first difference against the second difference
; the polar angle of each point is binned into
equal sectors of , and PhasEn is the (normalized)
Shannon entropy of the angle-weighted sector distribution. It summarizes how
the signal's local rate-of-change and its change-of-rate co-vary – a
phase-plane geometry distinct from the amplitude, template-matching and
symbolic (dispersion/increment/slope) entropies.
phaseEntropy(x, delay = 1L, k = 4L)phaseEntropy(x, delay = 1L, k = 4L)
x |
A numeric vector (the time series). |
delay |
Time delay (lag) in samples for the differences (default 1). |
k |
Number of angular sectors of the SODP (default 4). |
This implementation reproduces NeuroKit2's entropy_phase
bit-for-bit, including its normalization (a base-2 Shannon term divided by the
natural-log , so PhasEn ranges in ).
A single numeric value, the phase entropy.
Rohila, A., & Sharma, A. (2019). "Phase entropy: a new complexity measure for heart rate variability." Physiological Measurement, 40(10), 105006. doi:10.1088/1361-6579/ab499e
slopeEntropy, incrementEntropy,
dispersionEntropy.
set.seed(1) phaseEntropy(rnorm(1000), k = 4)set.seed(1) phaseEntropy(rnorm(1000), k = 4)
Computes the Renyi entropy of order alpha of a one-dimensional signal
(Renyi, 1961) – a one-parameter generalization of the Shannon entropy of the
signal's amplitude distribution. The signal is discretized into bins
equal-width bins to form a probability distribution , and
is returned
in nats. Special cases: is the Shannon entropy,
the collision entropy, and the
min-entropy. is non-increasing in .
renyiEntropy(x, alpha = 2, bins = 16L)renyiEntropy(x, alpha = 2, bins = 16L)
x |
A numeric vector (the time series). |
alpha |
Order of the Renyi entropy (default 2, the collision entropy);
|
bins |
Number of equal-width bins for the amplitude histogram (default 16). |
A single numeric value, the Renyi entropy in nats.
Renyi, A. (1961). "On measures of entropy and information." In Proceedings of the Fourth Berkeley Symposium on Mathematical Statistics and Probability, Volume 1, 547–561.
svdEntropy, petrosianFD,
eegComplexity for other complexity measures.
set.seed(1) renyiEntropy(rnorm(1000), alpha = 2) # collision entropy renyiEntropy(rnorm(1000), alpha = 1) # = Shannon entropyset.seed(1) renyiEntropy(rnorm(1000), alpha = 2) # collision entropy renyiEntropy(rnorm(1000), alpha = 1) # = Shannon entropy
Computes the slope entropy (SlopEn) of a one-dimensional signal (Cuesta-Frau,
2019) – a symbolic complexity measure defined on the slopes between
successive samples. Each first difference is turned into the angle
(in degrees) and mapped to one of five
symbols by two angle thresholds: steep-up (), gentle-up
(), flat (), gentle-down and
steep-down; SlopEn is the Shannon entropy of the resulting length-(m-1) slope
patterns. By combining a coarse (steep/gentle) and fine (flat) angular
resolution it captures the shape of local trends, a mechanism distinct from
the amplitude, NCDF-pattern, template-matching and increment-magnitude
entropies.
slopeEntropy(x, dimension = 3L, thresholds = c(0.1, 45), delay = 1L)slopeEntropy(x, dimension = 3L, thresholds = c(0.1, 45), delay = 1L)
x |
A numeric vector (the time series). |
dimension |
Embedding dimension |
thresholds |
Increasing positive angle thresholds (degrees) that split
the slope into symbol classes (default |
delay |
Time delay (lag) in samples for the difference (default 1). |
This implementation reproduces NeuroKit2's entropy_slope
bit-for-bit.
A single numeric value, the slope entropy (bits).
Cuesta-Frau, D. (2019). "Slope Entropy: A New Time Series Complexity Estimator Based on Both Symbolic Patterns and Amplitude Information." Entropy, 21(12), 1167. doi:10.3390/e21121167
incrementEntropy, dispersionEntropy,
fuzzyEntropy.
set.seed(1) slopeEntropy(rnorm(1000), dimension = 3)set.seed(1) slopeEntropy(rnorm(1000), dimension = 3)
Computes the SVD entropy of a one-dimensional signal (Roberts et al., 1999) –
a measure of the signal's dimensionality / the number of eigenvectors needed to
explain it. The signal is time-delay embedded into an
order-dimensional matrix; the normalized singular values of that matrix
are treated as a probability distribution, and their Shannon entropy is the SVD
entropy. Low SVD entropy indicates a low-dimensional (structured, e.g.
oscillatory) signal; high SVD entropy indicates a high-dimensional (complex or
noise-like) signal.
svdEntropy(x, order = 3L, delay = 1L, normalize = FALSE)svdEntropy(x, order = 3L, delay = 1L, normalize = FALSE)
x |
A numeric vector (the time series). |
order |
Embedding dimension (default 3); the number of singular values. |
delay |
Embedding delay / lag in samples (default 1). |
normalize |
If |
A single numeric value, the SVD entropy (in bits, or normalized).
Roberts, S. J., Penny, W., & Rezek, I. (1999). "Temporal and spatial complexity measures for electroencephalogram based brain-computer interfacing." Medical & Biological Engineering & Computing, 37(1), 93–98. doi:10.1007/BF02513272
eegComplexity for the multi-measure complexity wrapper
(permutation entropy, Lempel-Ziv, Hjorth, DFA, ...).
set.seed(1) svdEntropy(sin(seq(0, 20 * pi, length.out = 500))) # low (structured) svdEntropy(rnorm(500)) # high (noise-like)set.seed(1) svdEntropy(sin(seq(0, 20 * pi, length.out = 500))) # low (structured) svdEntropy(rnorm(500)) # high (noise-like)
Computes the Tsallis entropy of order q of a one-dimensional signal
(Tsallis, 1988) – the non-additive one-parameter generalization of the
Shannon entropy of the signal's amplitude distribution, complementary to the
(additive) renyiEntropy. The signal is discretized into
bins equal-width bins to form a probability distribution , and
is returned (equivalently
with the q-logarithm). recovers the
Shannon entropy (in nats); unlike Renyi, Tsallis is non-additive
( for independent
), so Renyi and Tsallis agree only at .
tsallisEntropy(x, q = 2, bins = 16L)tsallisEntropy(x, q = 2, bins = 16L)
x |
A numeric vector (the time series). |
q |
Order of the Tsallis entropy (default 2); |
bins |
Number of equal-width bins for the amplitude histogram (default 16). |
A single numeric value, the Tsallis entropy.
Tsallis, C. (1988). "Possible generalization of Boltzmann-Gibbs statistics." Journal of Statistical Physics, 52(1-2), 479–487. doi:10.1007/BF01016429
renyiEntropy for the additive generalization,
svdEntropy, petrosianFD.
set.seed(1) tsallisEntropy(rnorm(1000), q = 2) # non-additive (collision-like) tsallisEntropy(rnorm(1000), q = 1) # = Shannon entropyset.seed(1) tsallisEntropy(rnorm(1000), q = 2) # non-additive (collision-like) tsallisEntropy(rnorm(1000), q = 1) # = Shannon entropy