| Title: | Unified Analysis of Physiological Signals |
|---|---|
| Description: | A comprehensive R/Bioconductor framework for physiological signal analysis. Provides a unified data model (PhysioExperiment class extending SummarizedExperiment) for multi-modal sensor signals (EEG, EMG, ECG, IMU, MoCap). Includes file I/O (EDF, BDF, BrainVision, GDF, HDF5, BIDS, CSV, MATLAB), database integration (DuckDB), signal preprocessing (filtering, artifact removal, epoching), time-frequency analysis, connectivity analysis, network metrics, statistical testing (SPM1D, permutation tests), and publication-quality visualization. |
| Authors: | Yusuke Matsui [aut, cre] |
| Maintainer: | Yusuke Matsui <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 1.0.0 |
| Built: | 2026-05-28 14:47:44 UTC |
| Source: | https://github.com/x-biosignal/PhysioExperiment |
Subset PhysioExperiment by time indices
## S4 method for signature 'PhysioExperiment,ANY,ANY,ANY' x[i, j, ..., drop = FALSE]## S4 method for signature 'PhysioExperiment,ANY,ANY,ANY' x[i, j, ..., drop = FALSE]
x |
A PhysioExperiment object. |
i |
Time indices (rows). |
j |
Channel indices (columns in first non-time dimension). |
... |
Additional arguments (not used). |
drop |
Logical. If TRUE, drops dimensions of size 1. |
A subsetted PhysioExperiment object.
pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), samplingRate = 100 ) # Subset by time pe_subset <- pe[1:50, ] dim(pe_subset) # 50 4 # Subset by channels pe_channels <- pe[, 1:2] dim(pe_channels) # 100 2pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), samplingRate = 100 ) # Subset by time pe_subset <- pe[1:50, ] dim(pe_subset) # 50 4 # Subset by channels pe_channels <- pe[, 1:2] dim(pe_channels) # 100 2
Add events to a PhysioExperiment object
addEvents(x, onset, duration = 0, type = "event", value = "")addEvents(x, onset, duration = 0, type = "event", value = "")
x |
A PhysioExperiment object. |
onset |
Numeric vector of event onset times in seconds. |
duration |
Numeric vector of event durations in seconds. |
type |
Character vector of event types. |
value |
Character vector of event values/labels. |
The modified PhysioExperiment object.
pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1000), nrow = 100)), samplingRate = 100 ) # Add stimulus events pe <- addEvents(pe, onset = c(1, 2, 3), type = "stimulus") # Add response events pe <- addEvents(pe, onset = c(1.5, 2.5), type = "response", value = c("hit", "hit")) nEvents(pe) # 5 events totalpe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1000), nrow = 100)), samplingRate = 100 ) # Add stimulus events pe <- addEvents(pe, onset = c(1, 2, 3), type = "stimulus") # Add response events pe <- addEvents(pe, onset = c(1.5, 2.5), type = "response", value = c("hit", "hit")) nEvents(pe) # 5 events total
Functions for graph-theoretic analysis of functional connectivity networks, including network construction, topology measures, and spectral analysis. Create adjacency matrix from connectivity
adjacencyMatrix(connectivity, threshold = NULL, absolute = FALSE)adjacencyMatrix(connectivity, threshold = NULL, absolute = FALSE)
connectivity |
A connectivity matrix or result from connectivityMatrix(). |
threshold |
Threshold value for binarization. If NULL, keeps weighted edges. |
absolute |
If TRUE, uses absolute values before thresholding. |
Converts a connectivity matrix into an adjacency matrix for network analysis.
A square adjacency matrix.
set.seed(123) pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(500 * 4), nrow = 500, ncol = 4)), samplingRate = 100 ) conn <- correlationMatrix(pe) adj <- adjacencyMatrix(conn$correlation, threshold = 0.3)set.seed(123) pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(500 * 4), nrow = 500, ncol = 4)), samplingRate = 100 ) conn <- correlationMatrix(pe) adj <- adjacencyMatrix(conn$correlation, threshold = 0.3)
Performs one-way ANOVA at each time point and channel across multiple conditions.
anovaEpochs(x, groups)anovaEpochs(x, groups)
x |
An epoched PhysioExperiment object (4D data). |
groups |
Factor or character vector indicating group membership for each epoch. Can also be a column name from epoch_info metadata. |
A list containing:
f_values |
Matrix of F-statistics (time x channel) |
p_values |
Matrix of p-values (time x channel) |
df_between |
Between-group degrees of freedom |
df_within |
Within-group degrees of freedom |
group_means |
Array of group means (time x channel x group) |
# Create example epoched data with conditions set.seed(123) epochs <- array(rnorm(100 * 4 * 30 * 1), dim = c(100, 4, 30, 1)) pe <- PhysioExperiment( assays = list(epoched = epochs), samplingRate = 100, metadata = list( epoch_info = S4Vectors::DataFrame( condition = rep(c("A", "B", "C"), each = 10) ) ) ) # ANOVA across conditions result <- anovaEpochs(pe, groups = "condition")# Create example epoched data with conditions set.seed(123) epochs <- array(rnorm(100 * 4 * 30 * 1), dim = c(100, 4, 30, 1)) pe <- PhysioExperiment( assays = list(epoched = epochs), samplingRate = 100, metadata = list( epoch_info = S4Vectors::DataFrame( condition = rep(c("A", "B", "C"), each = 10) ) ) ) # ANOVA across conditions result <- anovaEpochs(pe, groups = "condition")
Applies a standard electrode montage (e.g., 10-20 system).
applyMontage(x, system = c("10-20", "10-10", "10-5"))applyMontage(x, system = c("10-20", "10-10", "10-5"))
x |
A PhysioExperiment object. |
system |
Montage system: "10-20", "10-10", or "10-5". |
Modified PhysioExperiment object with electrode positions.
pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), colData = S4Vectors::DataFrame(label = c("Fz", "Cz", "Pz", "Oz")), samplingRate = 100 ) # Apply 10-20 system positions pe <- applyMontage(pe, "10-20") getElectrodePositions(pe)pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), colData = S4Vectors::DataFrame(label = c("Fz", "Cz", "Pz", "Oz")), samplingRate = 100 ) # Apply 10-20 system positions pe <- applyMontage(pe, "10-20") getElectrodePositions(pe)
Converts the default assay to a data.frame.
## S4 method for signature 'PhysioExperiment' as.data.frame(x, row.names = NULL, optional = FALSE, ...)## S4 method for signature 'PhysioExperiment' as.data.frame(x, row.names = NULL, optional = FALSE, ...)
x |
A PhysioExperiment object. |
row.names |
Unused. |
optional |
Unused. |
... |
Additional arguments. |
A data.frame.
pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(12), nrow = 3, ncol = 4)), colData = S4Vectors::DataFrame(label = c("Fz", "Cz", "Pz", "Oz")), samplingRate = 100 ) df <- as.data.frame(pe) head(df)pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(12), nrow = 3, ncol = 4)), colData = S4Vectors::DataFrame(label = c("Fz", "Cz", "Pz", "Oz")), samplingRate = 100 ) df <- as.data.frame(pe) head(df)
Returns sampling rates associated with each assay.
assaySamplingRates(x)assaySamplingRates(x)
x |
A PhysioExperiment object. |
Named numeric vector of sampling rates.
Computes the average across epochs, optionally by condition.
averageEpochs(x, by = NULL)averageEpochs(x, by = NULL)
x |
An epoched PhysioExperiment object. |
by |
Optional column name in epoch_info to group by. |
A PhysioExperiment object with averaged epochs.
Extracts power in specified frequency bands.
bandPower(x, bands = NULL, method = c("welch", "wavelet"), relative = FALSE)bandPower(x, bands = NULL, method = c("welch", "wavelet"), relative = FALSE)
x |
A PhysioExperiment object. |
bands |
Named list of frequency bands. Each element should be c(low, high). Default includes standard EEG bands. |
method |
Method: "welch" (PSD) or "wavelet". |
relative |
If TRUE, returns relative power (proportion of total). |
A data.frame with band powers for each channel.
pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(2560), nrow = 256, ncol = 10)), rowData = S4Vectors::DataFrame(label = paste0("Ch", 1:10)), samplingRate = 256 ) # Compute band power for standard EEG bands bp <- bandPower(pe) head(bp) # Compute relative band power bp_rel <- bandPower(pe, relative = TRUE)pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(2560), nrow = 256, ncol = 10)), rowData = S4Vectors::DataFrame(label = paste0("Ch", 1:10)), samplingRate = 256 ) # Compute band power for standard EEG bands bp <- bandPower(pe) head(bp) # Compute relative band power bp_rel <- bandPower(pe, relative = TRUE)
Subtracts baseline from epochs.
baselineCorrect( x, baseline = c(-0.2, 0), method = c("mean", "median"), output_assay = "baseline_corrected" )baselineCorrect( x, baseline = c(-0.2, 0), method = c("mean", "median"), output_assay = "baseline_corrected" )
x |
An epoched PhysioExperiment object. |
baseline |
Numeric vector of length 2 (tmin, tmax) for baseline period. |
method |
Correction method: "mean" or "median". |
output_assay |
Name for the output assay. |
Modified PhysioExperiment with baseline-corrected data.
Calculates betweenness centrality for each node.
betweennessCentrality( adjacency, normalized = TRUE, use_cpp = TRUE, n_cores = 1L )betweennessCentrality( adjacency, normalized = TRUE, use_cpp = TRUE, n_cores = 1L )
adjacency |
An adjacency matrix. |
normalized |
If TRUE, normalizes by (n-1)(n-2)/2. |
A numeric vector of betweenness centrality values.
# Star network - center node should have highest betweenness adj <- matrix(0, 4, 4) adj[1, 2:4] <- 1 adj[2:4, 1] <- 1 betweennessCentrality(adj)# Star network - center node should have highest betweenness adj <- matrix(0, 4, 4) adj[1, 2:4] <- 1 adj[2:4, 1] <- 1 betweennessCentrality(adj)
Converts a weighted adjacency matrix to a binary network.
binarizeNetwork(adjacency, threshold = 0)binarizeNetwork(adjacency, threshold = 0)
adjacency |
A weighted adjacency matrix. |
threshold |
Threshold for binarization. Default 0 (any non-zero edge). |
A binary adjacency matrix (0s and 1s).
set.seed(123) adj <- matrix(c(0, 0.5, 0.3, 0.5, 0, 0.8, 0.3, 0.8, 0), 3, 3) bin <- binarizeNetwork(adj)set.seed(123) adj <- matrix(c(0, 0.5, 0.3, 0.5, 0, 0.8, 0.3, 0.8, 0), 3, 3) bin <- binarizeNetwork(adj)
Computes bootstrap confidence intervals for averaged epochs.
bootstrapCI( x, n_bootstrap = 1000L, ci_level = 0.95, condition = NULL, seed = NULL )bootstrapCI( x, n_bootstrap = 1000L, ci_level = 0.95, condition = NULL, seed = NULL )
x |
An epoched PhysioExperiment object (4D data). |
n_bootstrap |
Number of bootstrap iterations (default: 1000). |
ci_level |
Confidence interval level (default: 0.95). |
condition |
Epoch indices to include. If NULL, uses all epochs. |
seed |
Random seed for reproducibility. |
A list containing:
mean |
Mean across epochs (time x channel) |
ci_lower |
Lower CI bound (time x channel) |
ci_upper |
Upper CI bound (time x channel) |
se |
Standard error (time x channel) |
# Create example epoched data set.seed(123) epochs <- array(rnorm(100 * 4 * 20 * 1), dim = c(100, 4, 20, 1)) pe <- PhysioExperiment( assays = list(epoched = epochs), samplingRate = 100 ) # Bootstrap CI result <- bootstrapCI(pe, n_bootstrap = 500)# Create example epoched data set.seed(123) epochs <- array(rnorm(100 * 4 * 20 * 1), dim = c(100, 4, 20, 1)) pe <- PhysioExperiment( assays = list(epoched = epochs), samplingRate = 100 ) # Bootstrap CI result <- bootstrapCI(pe, n_bootstrap = 500)
This file provides advanced filtering operations including Butterworth, FIR, and notch filters for physiological signal processing. Butterworth filter
butterworthFilter( x, low = NULL, high = NULL, order = 4L, type = c("pass", "low", "high", "stop"), output_assay = "filtered" )butterworthFilter( x, low = NULL, high = NULL, order = 4L, type = c("pass", "low", "high", "stop"), output_assay = "filtered" )
x |
A |
low |
Lower cutoff frequency in Hz. Required for highpass and bandpass. |
high |
Upper cutoff frequency in Hz. Required for lowpass and bandpass. |
order |
Filter order. Default is 4. |
type |
Filter type: "low", "high", "pass" (bandpass), or "stop" (bandstop). |
output_assay |
Name for the output assay. Default is "filtered". |
Applies a Butterworth filter (lowpass, highpass, bandpass, or bandstop) along the time axis of the specified assay.
The input object with a new assay containing filtered data.
# Create example EEG data pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1000 * 4), nrow = 1000)), samplingRate = 250 ) # Bandpass filter (1-40 Hz) - common for EEG pe <- butterworthFilter(pe, low = 1, high = 40, type = "pass") # Lowpass filter (30 Hz) pe <- butterworthFilter(pe, high = 30, type = "low", output_assay = "lowpass") # Highpass filter (0.5 Hz) to remove DC drift pe <- butterworthFilter(pe, low = 0.5, type = "high", output_assay = "highpass")# Create example EEG data pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1000 * 4), nrow = 1000)), samplingRate = 250 ) # Bandpass filter (1-40 Hz) - common for EEG pe <- butterworthFilter(pe, low = 1, high = 40, type = "pass") # Lowpass filter (30 Hz) pe <- butterworthFilter(pe, high = 30, type = "low", output_assay = "lowpass") # Highpass filter (0.5 Hz) to remove DC drift pe <- butterworthFilter(pe, low = 0.5, type = "high", output_assay = "highpass")
Combines two PhysioExperiment objects by adding channels.
cbindPhysio(x, y)cbindPhysio(x, y)
x |
A PhysioExperiment object. |
y |
A PhysioExperiment object to combine. |
Combined PhysioExperiment object.
pe1 <- PhysioExperiment( assays = list(raw = matrix(rnorm(200), nrow = 100, ncol = 2)), colData = S4Vectors::DataFrame(label = c("Fz", "Cz")), samplingRate = 100 ) pe2 <- PhysioExperiment( assays = list(raw = matrix(rnorm(200), nrow = 100, ncol = 2)), colData = S4Vectors::DataFrame(label = c("Pz", "Oz")), samplingRate = 100 ) # Combine channels pe_combined <- cbindPhysio(pe1, pe2) nChannels(pe_combined) # 4pe1 <- PhysioExperiment( assays = list(raw = matrix(rnorm(200), nrow = 100, ncol = 2)), colData = S4Vectors::DataFrame(label = c("Fz", "Cz")), samplingRate = 100 ) pe2 <- PhysioExperiment( assays = list(raw = matrix(rnorm(200), nrow = 100, ncol = 2)), colData = S4Vectors::DataFrame(label = c("Pz", "Oz")), samplingRate = 100 ) # Combine channels pe_combined <- cbindPhysio(pe1, pe2) nChannels(pe_combined) # 4
Functions for managing channel metadata including labels, types, units, and electrode positions. Get channel information
channelInfo(x)channelInfo(x)
x |
A PhysioExperiment object. |
Returns channel metadata as a DataFrame. Channel information is stored in colData (columns = channels).
A DataFrame with channel information.
pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), colData = S4Vectors::DataFrame( label = c("Fz", "Cz", "Pz", "Oz"), type = rep("EEG", 4) ), samplingRate = 100 ) # Get channel information channelInfo(pe) # Get channel names channelNames(pe) # Get number of channels nChannels(pe)pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), colData = S4Vectors::DataFrame( label = c("Fz", "Cz", "Pz", "Oz"), type = rep("EEG", 4) ), samplingRate = 100 ) # Get channel information channelInfo(pe) # Get channel names channelNames(pe) # Get number of channels nChannels(pe)
Updates channel metadata. Channel information is stored in colData (columns = channels).
channelInfo(x) <- valuechannelInfo(x) <- value
x |
A PhysioExperiment object. |
value |
A DataFrame with channel information. |
Modified PhysioExperiment object.
pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), samplingRate = 100 ) # Set channel info channelInfo(pe) <- S4Vectors::DataFrame( label = c("Fz", "Cz", "Pz", "Oz"), type = rep("EEG", 4) )pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), samplingRate = 100 ) # Set channel info channelInfo(pe) <- S4Vectors::DataFrame( label = c("Fz", "Cz", "Pz", "Oz"), type = rep("EEG", 4) )
Get channel names/labels
channelNames(x)channelNames(x)
x |
A PhysioExperiment object. |
Character vector of channel names.
pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), colData = S4Vectors::DataFrame(label = c("Fz", "Cz", "Pz", "Oz")), samplingRate = 100 ) channelNames(pe) # c("Fz", "Cz", "Pz", "Oz")pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), colData = S4Vectors::DataFrame(label = c("Fz", "Cz", "Pz", "Oz")), samplingRate = 100 ) channelNames(pe) # c("Fz", "Cz", "Pz", "Oz")
Set channel names/labels
channelNames(x) <- valuechannelNames(x) <- value
x |
A PhysioExperiment object. |
value |
Character vector of channel names. |
Modified PhysioExperiment object.
pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), samplingRate = 100 ) channelNames(pe) <- c("Fz", "Cz", "Pz", "Oz") channelNames(pe)pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), samplingRate = 100 ) channelNames(pe) <- c("Fz", "Cz", "Pz", "Oz") channelNames(pe)
Checks if all required dependencies for the GUI are available.
checkGUIDependencies()checkGUIDependencies()
A list with the status of each dependency.
## Not run: checkGUIDependencies() ## End(Not run)## Not run: checkGUIDependencies() ## End(Not run)
Validates assay data for NA values and reports statistics.
checkNA(x, action = c("warn", "error", "none"))checkNA(x, action = c("warn", "error", "none"))
x |
A PhysioExperiment object or numeric array. |
action |
Action to take: "warn" (default), "error", or "none". |
Invisibly returns a list with NA statistics.
pe <- PhysioExperiment( assays = list(raw = matrix(c(1, NA, 3, 4), nrow = 2)), samplingRate = 100 ) checkNA(pe)pe <- PhysioExperiment( assays = list(raw = matrix(c(1, NA, 3, 4), nrow = 2)), samplingRate = 100 ) checkNA(pe)
Automatically identifies artifact ICA components using statistical criteria.
classifyICAComponents( x, method = c("autocorrelation", "kurtosis", "frequency"), eog_channels = NULL, threshold = NULL )classifyICAComponents( x, method = c("autocorrelation", "kurtosis", "frequency"), eog_channels = NULL, threshold = NULL )
x |
A PhysioExperiment object with ICA decomposition
(from |
method |
Classification method: "autocorrelation", "kurtosis", or "frequency". |
eog_channels |
Integer vector of EOG channel indices for correlation-based detection. If provided, also computes EOG correlation scores. |
threshold |
Classification threshold. If NULL, uses method-specific defaults: autocorrelation=0.9, kurtosis=3.0, frequency=0.5. |
A list with:
artifact_indices: Integer vector of artifact component indices
scores: Named numeric vector of scores per component
threshold: The threshold used
method: The method used
Runs a configurable sequence of artifact removal steps.
cleanData( x, steps = c("bad_channels", "ica"), bad_channel_method = "zscore", bad_channel_threshold = NULL, interpolation_method = "average", ica_method = "fastica", ica_classify_method = "kurtosis", output_assay = "cleaned" )cleanData( x, steps = c("bad_channels", "ica"), bad_channel_method = "zscore", bad_channel_threshold = NULL, interpolation_method = "average", ica_method = "fastica", ica_classify_method = "kurtosis", output_assay = "cleaned" )
x |
A PhysioExperiment object. |
steps |
Character vector of steps to run. Options: "bad_channels", "ica". |
bad_channel_method |
Method for |
bad_channel_threshold |
Threshold for bad channel detection. |
interpolation_method |
Method for |
ica_method |
Method for |
ica_classify_method |
Method for |
output_assay |
Name for the output assay. |
Modified PhysioExperiment with cleaned data.
Calculates the local clustering coefficient for each node.
clusteringCoefficient( adjacency, weighted = FALSE, use_cpp = TRUE, n_cores = 1L )clusteringCoefficient( adjacency, weighted = FALSE, use_cpp = TRUE, n_cores = 1L )
adjacency |
An adjacency matrix. |
weighted |
If TRUE, uses weighted clustering coefficient. |
A numeric vector of clustering coefficients.
# Fully connected triangle adj <- matrix(c(0, 1, 1, 1, 0, 1, 1, 1, 0), 3, 3) clusteringCoefficient(adj) # Should be 1 for all nodes# Fully connected triangle adj <- matrix(c(0, 1, 1, 1, 0, 1, 1, 1, 0), 3, 3) clusteringCoefficient(adj) # Should be 1 for all nodes
Performs cluster-based permutation testing for multiple comparison correction. Identifies clusters of significant effects and computes cluster-level p-values.
clusterPermutationTest( x, condition1 = NULL, condition2 = NULL, n_permutations = 1000L, cluster_threshold = 0.05, tail = 0L, seed = NULL, n_cores = NULL )clusterPermutationTest( x, condition1 = NULL, condition2 = NULL, n_permutations = 1000L, cluster_threshold = 0.05, tail = 0L, seed = NULL, n_cores = NULL )
x |
An epoched PhysioExperiment object (4D data). |
condition1 |
Indices for first condition. |
condition2 |
Indices for second condition. If NULL, tests against zero. |
n_permutations |
Number of permutations (default: 1000). |
cluster_threshold |
Initial threshold for cluster formation (p-value). |
tail |
Test type: 0 = two-tailed, 1 = right tail, -1 = left tail. |
seed |
Random seed for reproducibility. |
n_cores |
Number of cores for parallel processing. Default NULL uses sequential processing. Set to parallel::detectCores() - 1 for maximum speed. |
A list containing:
clusters |
List of identified clusters with their statistics |
cluster_p |
P-values for each cluster |
t_obs |
Observed t-values matrix |
cluster_mask |
Logical matrix indicating cluster membership |
# Create example epoched data set.seed(123) epochs <- array(rnorm(50 * 4 * 20 * 1), dim = c(50, 4, 20, 1)) # Add effect to condition 2 epochs[20:30, 1:2, 11:20, 1] <- epochs[20:30, 1:2, 11:20, 1] + 1 pe <- PhysioExperiment( assays = list(epoched = epochs), samplingRate = 100 ) # Cluster permutation test result <- clusterPermutationTest(pe, 1:10, 11:20, n_permutations = 100) # With parallel processing (faster for large datasets) # result <- clusterPermutationTest(pe, 1:10, 11:20, n_cores = 4)# Create example epoched data set.seed(123) epochs <- array(rnorm(50 * 4 * 20 * 1), dim = c(50, 4, 20, 1)) # Add effect to condition 2 epochs[20:30, 1:2, 11:20, 1] <- epochs[20:30, 1:2, 11:20, 1] + 1 pe <- PhysioExperiment( assays = list(epoched = epochs), samplingRate = 100 ) # Cluster permutation test result <- clusterPermutationTest(pe, 1:10, 11:20, n_permutations = 100) # With parallel processing (faster for large datasets) # result <- clusterPermutationTest(pe, 1:10, 11:20, n_cores = 4)
Functions for computing functional connectivity between channels including coherence, phase synchrony measures, and correlation-based metrics. Compute coherence between channels
coherence( x, channels = NULL, freq_range = NULL, nperseg = 256L, noverlap = NULL, assay_name = NULL )coherence( x, channels = NULL, freq_range = NULL, nperseg = 256L, noverlap = NULL, assay_name = NULL )
x |
A PhysioExperiment object. |
channels |
Integer vector of channel indices to analyze. If NULL, uses all. |
freq_range |
Numeric vector of length 2 specifying frequency range (Hz). |
nperseg |
Number of samples per segment for Welch's method. Default is 256. |
noverlap |
Number of overlapping samples. Default is nperseg/2. |
assay_name |
Input assay name. If NULL, uses default assay. |
Calculates the magnitude-squared coherence between pairs of channels, which measures the linear correlation between signals as a function of frequency.
Coherence is computed using Welch's averaged periodogram method. Values range from 0 (no linear relationship) to 1 (perfect linear relationship).
A list with components:
coherence |
3D array (freq x channel x channel) of coherence values |
frequencies |
Frequency vector |
channel_names |
Channel names |
# Create example with 4 channels set.seed(123) pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(4000), nrow = 1000, ncol = 4)), rowData = S4Vectors::DataFrame(label = c("Fz", "Cz", "Pz", "Oz")), samplingRate = 256 ) # Compute coherence coh <- coherence(pe, freq_range = c(1, 50)) dim(coh$coherence) # frequencies x channels x channels# Create example with 4 channels set.seed(123) pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(4000), nrow = 1000, ncol = 4)), rowData = S4Vectors::DataFrame(label = c("Fz", "Cz", "Pz", "Oz")), samplingRate = 256 ) # Compute coherence coh <- coherence(pe, freq_range = c(1, 50)) dim(coh$coherence) # frequencies x channels x channels
These functions establish a connection to a DuckDB database using the
DBI interface. They form a minimal skeleton to be expanded with concrete
schema management functions in future iterations.
connectDatabase(path = ":memory:") disconnectDatabase(con)connectDatabase(path = ":memory:") disconnectDatabase(con)
path |
Path to a DuckDB database file. |
con |
A database connection produced by |
A database connection object.
## Not run: # Connect to an in-memory database con <- connectDatabase() # Connect to a file-based database con <- connectDatabase("experiments.duckdb") # Always disconnect when done disconnectDatabase(con) ## End(Not run)## Not run: # Connect to an in-memory database con <- connectDatabase() # Connect to a file-based database con <- connectDatabase("experiments.duckdb") # Always disconnect when done disconnectDatabase(con) ## End(Not run)
High-level function to compute connectivity using various metrics.
connectivityMatrix( x, method = c("coherence", "plv", "pli", "wpli", "correlation"), freq_band = NULL, channels = NULL, assay_name = NULL )connectivityMatrix( x, method = c("coherence", "plv", "pli", "wpli", "correlation"), freq_band = NULL, channels = NULL, assay_name = NULL )
x |
A PhysioExperiment object. |
method |
Connectivity method: "coherence", "plv", "pli", "wpli", "correlation". |
freq_band |
Frequency band for phase-based methods. |
channels |
Integer vector of channel indices. |
assay_name |
Input assay name. |
A connectivity matrix or array depending on the method.
set.seed(123) pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(4000), nrow = 1000, ncol = 4)), samplingRate = 256 ) # Compute PLV connectivity in alpha band conn <- connectivityMatrix(pe, method = "plv", freq_band = c(8, 12))set.seed(123) pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(4000), nrow = 1000, ncol = 4)), samplingRate = 256 ) # Compute PLV connectivity in alpha band conn <- connectivityMatrix(pe, method = "plv", freq_band = c(8, 12))
Applies multiple comparison correction to p-values.
correctPValues(p_values, method = c("fdr", "bonferroni", "holm", "bh", "none"))correctPValues(p_values, method = c("fdr", "bonferroni", "holm", "bh", "none"))
p_values |
Matrix or vector of p-values. |
method |
Correction method: "bonferroni", "holm", "fdr" (Benjamini-Hochberg), "bh" (alias for fdr), or "none". |
Corrected p-values in the same format as input.
# Example p-values p <- matrix(runif(100), nrow = 10) # Apply FDR correction p_corrected <- correctPValues(p, method = "fdr")# Example p-values p <- matrix(runif(100), nrow = 10) # Apply FDR correction p_corrected <- correctPValues(p, method = "fdr")
Calculates the Pearson correlation coefficient between all channel pairs.
correlationMatrix( x, channels = NULL, method = c("pearson", "spearman", "kendall"), assay_name = NULL )correlationMatrix( x, channels = NULL, method = c("pearson", "spearman", "kendall"), assay_name = NULL )
x |
A PhysioExperiment object. |
channels |
Integer vector of channel indices. |
method |
Correlation method: "pearson", "spearman", or "kendall". |
assay_name |
Input assay name. |
A correlation matrix (channel x channel).
set.seed(123) pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(4000), nrow = 1000, ncol = 4)), rowData = S4Vectors::DataFrame(label = c("Fz", "Cz", "Pz", "Oz")), samplingRate = 256 ) # Compute Pearson correlation cor_matrix <- correlationMatrix(pe)set.seed(123) pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(4000), nrow = 1000, ncol = 4)), rowData = S4Vectors::DataFrame(label = c("Fz", "Cz", "Pz", "Oz")), samplingRate = 256 ) # Compute Pearson correlation cor_matrix <- correlationMatrix(pe)
Calculates the cross-spectral density between channel pairs.
crossSpectrum( x, channels = NULL, nperseg = 256L, noverlap = NULL, assay_name = NULL )crossSpectrum( x, channels = NULL, nperseg = 256L, noverlap = NULL, assay_name = NULL )
x |
A PhysioExperiment object. |
channels |
Integer vector of channel indices. If NULL, uses all. |
nperseg |
Number of samples per segment. Default is 256. |
noverlap |
Number of overlapping samples. |
assay_name |
Input assay name. |
A list with components:
csd |
3D complex array (freq x channel x channel) |
frequencies |
Frequency vector |
channel_names |
Channel names |
set.seed(123) pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(2000), nrow = 500, ncol = 4)), samplingRate = 256 ) # Compute cross-spectral density csd <- crossSpectrum(pe)set.seed(123) pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(2000), nrow = 500, ncol = 4)), samplingRate = 256 ) # Compute cross-spectral density csd <- crossSpectrum(pe)
Get database statistics
dbStats(con)dbStats(con)
con |
A DuckDB connection. |
A list with database statistics.
## Not run: con <- connectDatabase("experiments.duckdb") initPhysioSchema(con) # Get database statistics stats <- dbStats(con) cat("Experiments:", stats$n_experiments, "\n") cat("Channels:", stats$n_channels, "\n") cat("Subjects:", paste(stats$subjects, collapse = ", "), "\n") disconnectDatabase(con) ## End(Not run)## Not run: con <- connectDatabase("experiments.duckdb") initPhysioSchema(con) # Get database statistics stats <- dbStats(con) cat("Experiments:", stats$n_experiments, "\n") cat("Channels:", stats$n_channels, "\n") cat("Subjects:", paste(stats$subjects, collapse = ", "), "\n") disconnectDatabase(con) ## End(Not run)
Downsamples by an integer factor with anti-aliasing filter.
decimate(x, factor, filter_order = 8L, output_assay = "decimated")decimate(x, factor, filter_order = 8L, output_assay = "decimated")
x |
A PhysioExperiment object. |
factor |
Integer decimation factor. |
filter_order |
Order of the anti-aliasing lowpass filter. |
output_assay |
Name for the output assay. |
A new PhysioExperiment with decimated data.
Retrieve the default assay name
defaultAssay(x)defaultAssay(x)
x |
A |
Character scalar naming the first assay or NA_character_ when absent.
Delete experiment from database
deleteExperiment(con, experiment_id, confirm = TRUE)deleteExperiment(con, experiment_id, confirm = TRUE)
con |
A DuckDB connection. |
experiment_id |
The experiment identifier. |
confirm |
If TRUE, requires confirmation. |
Invisible NULL.
## Not run: con <- connectDatabase("experiments.duckdb") # Delete an experiment deleteExperiment(con, "exp_20240101120000_1234") # Skip existence check (for batch deletion) deleteExperiment(con, "exp_id", confirm = FALSE) disconnectDatabase(con) ## End(Not run)## Not run: con <- connectDatabase("experiments.duckdb") # Delete an experiment deleteExperiment(con, "exp_20240101120000_1234") # Skip existence check (for batch deletion) deleteExperiment(con, "exp_id", confirm = FALSE) disconnectDatabase(con) ## End(Not run)
Scans continuous data for artifacts using amplitude or gradient criteria.
detectArtifacts( x, method = c("amplitude", "gradient", "joint"), threshold = NULL, window_sec = 1 )detectArtifacts( x, method = c("amplitude", "gradient", "joint"), threshold = NULL, window_sec = 1 )
x |
A PhysioExperiment object. |
method |
Detection method: "amplitude", "gradient", or "joint". |
threshold |
Detection threshold. If NULL, computed as median + 5 * MAD. |
window_sec |
Detection window in seconds (default: 1.0). |
A data.frame with columns: onset (seconds), offset (seconds), channel (index), type (detection method).
Identifies channels with abnormal characteristics.
detectBadChannels( x, method = c("zscore", "correlation", "flatline"), threshold = NULL )detectBadChannels( x, method = c("zscore", "correlation", "flatline"), threshold = NULL )
x |
A PhysioExperiment object. |
method |
Detection method: "zscore", "correlation", or "flatline". |
threshold |
Threshold for detection (depends on method). |
Integer vector of bad channel indices.
Removes linear or polynomial trends from the signal.
detrendSignal(x, type = c("linear", "constant"), output_assay = "detrended")detrendSignal(x, type = c("linear", "constant"), output_assay = "detrended")
x |
A |
type |
Type of detrending: "linear" or "constant" (mean removal). |
output_assay |
Name for the output assay. Default is "detrended". |
The input object with a new assay containing detrended data.
Returns dimensions of the default assay.
## S4 method for signature 'PhysioExperiment' dim(x)## S4 method for signature 'PhysioExperiment' dim(x)
x |
A PhysioExperiment object. |
Integer vector of dimensions.
pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), samplingRate = 100 ) dim(pe) # 100 4pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), samplingRate = 100 ) dim(pe) # 100 4
Creates a new PhysioExperiment without specified channels.
dropChannels(x, channels)dropChannels(x, channels)
x |
A PhysioExperiment object. |
channels |
Integer indices or character names of channels to drop. |
A new PhysioExperiment without specified channels.
pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), colData = S4Vectors::DataFrame(label = c("Fz", "Cz", "Pz", "Oz")), samplingRate = 100 ) # Drop by index pe_dropped <- dropChannels(pe, 1) nChannels(pe_dropped) # 3 # Drop by name pe_dropped <- dropChannels(pe, c("Fz", "Oz"))pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), colData = S4Vectors::DataFrame(label = c("Fz", "Cz", "Pz", "Oz")), samplingRate = 100 ) # Drop by index pe_dropped <- dropChannels(pe, 1) nChannels(pe_dropped) # 3 # Drop by name pe_dropped <- dropChannels(pe, c("Fz", "Oz"))
Get signal duration
duration(x)duration(x)
x |
A PhysioExperiment object. |
Duration in seconds.
pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1000), nrow = 1000, ncol = 4)), samplingRate = 100 ) duration(pe) # 10 secondspe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1000), nrow = 1000, ncol = 4)), samplingRate = 100 ) duration(pe) # 10 seconds
Calculates Cohen's d effect size at each time point and channel.
effectSize(x, condition1 = NULL, condition2 = NULL, pooled = TRUE)effectSize(x, condition1 = NULL, condition2 = NULL, pooled = TRUE)
x |
An epoched PhysioExperiment object (4D data). |
condition1 |
Indices for first condition. |
condition2 |
Indices for second condition. If NULL, computes d against zero. |
pooled |
If TRUE (default for two-sample), uses pooled standard deviation. |
A list containing:
d |
Matrix of Cohen's d values (time x channel) |
ci_lower |
Lower 95% CI for d |
ci_upper |
Upper 95% CI for d |
# Create example epoched data set.seed(123) epochs <- array(rnorm(100 * 4 * 20 * 1), dim = c(100, 4, 20, 1)) pe <- PhysioExperiment( assays = list(epoched = epochs), samplingRate = 100 ) # Effect size for one-sample result <- effectSize(pe, condition1 = 1:10) # Effect size between conditions result2 <- effectSize(pe, condition1 = 1:10, condition2 = 11:20)# Create example epoched data set.seed(123) epochs <- array(rnorm(100 * 4 * 20 * 1), dim = c(100, 4, 20, 1)) pe <- PhysioExperiment( assays = list(epoched = epochs), samplingRate = 100 ) # Effect size for one-sample result <- effectSize(pe, condition1 = 1:10) # Effect size between conditions result2 <- effectSize(pe, condition1 = 1:10, condition2 = 11:20)
Calculates eigenvector centrality for each node.
eigenvectorCentrality(adjacency, max_iter = 100, tol = 1e-06, use_cpp = TRUE)eigenvectorCentrality(adjacency, max_iter = 100, tol = 1e-06, use_cpp = TRUE)
adjacency |
An adjacency matrix. |
max_iter |
Maximum iterations for power method. |
tol |
Convergence tolerance. |
A numeric vector of eigenvector centrality values.
adj <- matrix(c(0, 1, 1, 1, 0, 1, 1, 1, 0), 3, 3) eigenvectorCentrality(adj)adj <- matrix(c(0, 1, 1, 1, 0, 1, 1, 1, 0), 3, 3) eigenvectorCentrality(adj)
Functions for segmenting continuous data into epochs/trials based on events. Epoch data around events
epochData( x, tmin = -0.2, tmax = 0.8, event_type = NULL, baseline = NULL, reject = NULL, events = NULL, min_length = NULL )epochData( x, tmin = -0.2, tmax = 0.8, event_type = NULL, baseline = NULL, reject = NULL, events = NULL, min_length = NULL )
x |
A PhysioExperiment object. |
tmin |
Time before event onset in seconds (negative for pre-stimulus). |
tmax |
Time after event onset in seconds. |
event_type |
Character vector of event types to epoch around.
If NULL, uses all events. Ignored if |
baseline |
Numeric vector of length 2 specifying baseline period (tmin, tmax) for baseline correction. NULL for no correction. |
reject |
Amplitude threshold for epoch rejection. NULL to keep all. |
events |
An EventQuery object for advanced event filtering.
If provided, overrides |
min_length |
Minimum epoch length in seconds when using variable-length epochs (tmax as event name). Epochs shorter than this are excluded. |
Extracts epochs (segments) of data around specified events.
A new PhysioExperiment object with epoched data. The assay becomes 4D: (time x channel x epoch x sample).
# Create continuous data with events pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1000 * 4), nrow = 1000)), samplingRate = 100 ) pe <- addEvents(pe, onset = c(1, 2, 3, 4, 5), type = "stimulus") # Extract epochs: 200ms before to 800ms after stimulus epochs <- epochData(pe, tmin = -0.2, tmax = 0.8) # With baseline correction epochs_bl <- epochData(pe, tmin = -0.2, tmax = 0.8, baseline = c(-0.2, 0)) # With artifact rejection epochs_clean <- epochData(pe, tmin = -0.2, tmax = 0.8, reject = 100)# Create continuous data with events pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1000 * 4), nrow = 1000)), samplingRate = 100 ) pe <- addEvents(pe, onset = c(1, 2, 3, 4, 5), type = "stimulus") # Extract epochs: 200ms before to 800ms after stimulus epochs <- epochData(pe, tmin = -0.2, tmax = 0.8) # With baseline correction epochs_bl <- epochData(pe, tmin = -0.2, tmax = 0.8, baseline = c(-0.2, 0)) # With artifact rejection epochs_clean <- epochData(pe, tmin = -0.2, tmax = 0.8, reject = 100)
Segments continuous data into overlapping epochs using a sliding window approach. This is useful for time-frequency analysis or when events are not available.
epochSliding(x, window, step = NULL, baseline = NULL)epochSliding(x, window, step = NULL, baseline = NULL)
x |
A PhysioExperiment object |
window |
Window size in seconds |
step |
Step size in seconds (default: window/2 for 50% overlap) |
baseline |
Optional baseline correction window as c(start, end) in seconds relative to epoch start. NULL for no correction. |
PhysioExperiment with epoched data
pe <- make_pe_2d(n_time = 1000, n_channels = 4, sr = 100) # Create 0.5 second windows with 0.1 second step epoched <- epochSliding(pe, window = 0.5, step = 0.1)pe <- make_pe_2d(n_time = 1000, n_channels = 4, sr = 100) # Create 0.5 second windows with 0.1 second step epoched <- epochSliding(pe, window = 0.5, step = 0.1)
Returns the time vector for epoched data relative to event onset.
epochTimes(x)epochTimes(x)
x |
An epoched PhysioExperiment object. |
Numeric vector of times in seconds.
Create an EventQuery from a PhysioExperiment
eventQuery(x)eventQuery(x)
x |
A PhysioExperiment object |
An EventQuery object
pe <- make_pe_2d() pe <- addEvents(pe, onset = c(1, 2, 3), type = "stimulus") q <- eventQuery(pe)pe <- make_pe_2d() pe <- addEvents(pe, onset = c(1, 2, 3), type = "stimulus") q <- eventQuery(pe)
EventQuery class for composable event filtering
sourcePhysioExperiment object
filtersList of filter functions to apply
resolvedCached resolved events (NULL if not yet resolved)
Extracts a time window from the signal.
extractWindow(x, tmin, tmax)extractWindow(x, tmin, tmax)
x |
A PhysioExperiment object. |
tmin |
Start time in seconds. |
tmax |
End time in seconds. |
A PhysioExperiment with the extracted time window.
pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1000), nrow = 1000, ncol = 4)), samplingRate = 100 ) # Extract 2 to 5 seconds pe_window <- extractWindow(pe, tmin = 2, tmax = 5) duration(pe_window) # approximately 3 secondspe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1000), nrow = 1000, ncol = 4)), samplingRate = 100 ) # Extract 2 to 5 seconds pe_window <- extractWindow(pe, tmin = 2, tmax = 5) duration(pe_window) # approximately 3 seconds
Computes the discrete Fourier transform along the time axis of the default
assay and stores the magnitude spectrum in a new assay named "fft".
fftSignals(x)fftSignals(x)
x |
A |
The modified object containing an FFT assay.
Fills NA values at the beginning and end of a signal that may result from filtering operations.
fillEdgeNA(x, method = c("extend", "zero"))fillEdgeNA(x, method = c("extend", "zero"))
x |
Numeric vector. |
method |
Fill method: "extend" (extend nearest valid value) or "zero" (fill with zeros). |
Vector with edge NA values filled.
x <- c(NA, NA, 1, 2, 3, NA, NA) fillEdgeNA(x, method = "extend")x <- c(NA, NA, 1, 2, 3, NA, NA) fillEdgeNA(x, method = "extend")
Applies a moving average filter along the first dimension (time axis) of the default assay.
filterSignals(x, window = 5L, na.rm = FALSE, output_assay = "filtered")filterSignals(x, window = 5L, na.rm = FALSE, output_assay = "filtered")
x |
A |
window |
Integer window length for the moving average. |
na.rm |
Logical. If TRUE, NA values are ignored in the filter computation. |
output_assay |
Name for the output assay. Default is "filtered". |
The input object with a new assay containing filtered data.
Filter events by type
filterType(q, types)filterType(q, types)
q |
An EventQuery object |
types |
Character vector of event types to keep |
Modified EventQuery
Filter events by value
filterValue(q, values)filterValue(q, values)
q |
An EventQuery object |
values |
Character vector of event values to keep |
Modified EventQuery
Identifies contiguous time periods with significant effects.
findSignificantWindows(p_values, times = NULL, alpha = 0.05, min_duration = 0)findSignificantWindows(p_values, times = NULL, alpha = 0.05, min_duration = 0)
p_values |
Vector of p-values across time. |
times |
Vector of time points. |
alpha |
Significance threshold (default: 0.05). |
min_duration |
Minimum duration of significant window in time units. |
A data.frame with columns: start, end, duration, min_p.
# Example p-values times <- seq(-0.2, 0.8, length.out = 100) p <- c(rep(0.5, 30), rep(0.01, 20), rep(0.5, 50)) windows <- findSignificantWindows(p, times)# Example p-values times <- seq(-0.2, 0.8, length.out = 100) p <- c(rep(0.5, 30), rep(0.01, 20), rep(0.5, 50)) windows <- findSignificantWindows(p, times)
Applies a Finite Impulse Response (FIR) filter along the time axis.
firFilter( x, low = NULL, high = NULL, order = 100L, type = c("pass", "low", "high", "stop"), window = "hamming", output_assay = "filtered" )firFilter( x, low = NULL, high = NULL, order = 100L, type = c("pass", "low", "high", "stop"), window = "hamming", output_assay = "filtered" )
x |
A |
low |
Lower cutoff frequency in Hz. |
high |
Upper cutoff frequency in Hz. |
order |
Filter order (number of taps - 1). Default is 100. |
type |
Filter type: "low", "high", "pass" (bandpass), or "stop" (bandstop). |
window |
Window function for FIR design. Default is "hamming". |
output_assay |
Name for the output assay. Default is "filtered". |
The input object with a new assay containing filtered data.
Returns indices of channels matching specified types.
getChannelsByType(x, types)getChannelsByType(x, types)
x |
A PhysioExperiment object. |
types |
Character vector of channel types to match. |
Integer vector of matching channel indices.
pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), colData = S4Vectors::DataFrame( label = c("Fz", "EOG1", "EMG1", "Oz"), type = c("EEG", "EOG", "EMG", "EEG") ), samplingRate = 100 ) # Get EEG channels eeg_idx <- getChannelsByType(pe, "EEG") # c(1, 4)pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), colData = S4Vectors::DataFrame( label = c("Fz", "EOG1", "EMG1", "Oz"), type = c("EEG", "EOG", "EMG", "EEG") ), samplingRate = 100 ) # Get EEG channels eeg_idx <- getChannelsByType(pe, "EEG") # c(1, 4)
Returns the current reference electrode information.
getCurrentReference(x)getCurrentReference(x)
x |
A PhysioExperiment object. |
Character string describing the current reference, or NULL if not set.
pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(100), nrow = 10, ncol = 10)), samplingRate = 100 ) pe <- setReference(pe, "Cz") getCurrentReference(pe) # "Cz"pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(100), nrow = 10, ncol = 10)), samplingRate = 100 ) pe <- setReference(pe, "Cz") getCurrentReference(pe) # "Cz"
Get electrode positions
getElectrodePositions(x)getElectrodePositions(x)
x |
A PhysioExperiment object. |
A data.frame with x, y, z columns or NULL if not set.
pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(300), nrow = 100, ncol = 3)), colData = S4Vectors::DataFrame(label = c("Fz", "Cz", "Pz")), samplingRate = 100 ) pe <- applyMontage(pe, "10-20") getElectrodePositions(pe)pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(300), nrow = 100, ncol = 3)), colData = S4Vectors::DataFrame(label = c("Fz", "Cz", "Pz")), samplingRate = 100 ) pe <- applyMontage(pe, "10-20") getElectrodePositions(pe)
Get events from a PhysioExperiment object
getEvents(x, type = NULL)getEvents(x, type = NULL)
x |
A PhysioExperiment object. |
type |
Optional character vector of event types to filter. |
A PhysioEvents object or DataFrame of events.
# Create PhysioExperiment with events pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1000), nrow = 100)), samplingRate = 100 ) events <- PhysioEvents( onset = c(1, 2, 3), type = c("stimulus", "response", "stimulus") ) pe <- setEvents(pe, events) # Get all events getEvents(pe) # Get only stimulus events getEvents(pe, type = "stimulus")# Create PhysioExperiment with events pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1000), nrow = 100)), samplingRate = 100 ) events <- PhysioEvents( onset = c(1, 2, 3), type = c("stimulus", "response", "stimulus") ) pe <- setEvents(pe, events) # Get all events getEvents(pe) # Get only stimulus events getEvents(pe, type = "stimulus")
Get reference electrode
getReference(x)getReference(x)
x |
A PhysioExperiment object. |
Character string of reference electrode or NULL.
pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), samplingRate = 100 ) pe <- setReference(pe, "Cz") getReference(pe) # "Cz"pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), samplingRate = 100 ) pe <- setReference(pe, "Cz") getReference(pe) # "Cz"
Calculates the global efficiency of a network.
globalEfficiency(adjacency, weighted = FALSE, use_cpp = TRUE)globalEfficiency(adjacency, weighted = FALSE, use_cpp = TRUE)
adjacency |
An adjacency matrix. |
weighted |
If TRUE, uses weighted paths. |
Global efficiency value (0-1).
# Fully connected - maximum efficiency adj <- matrix(1, 4, 4) diag(adj) <- 0 globalEfficiency(adj)# Fully connected - maximum efficiency adj <- matrix(1, 4, 4) diag(adj) <- 0 globalEfficiency(adj)
Computes grand average across multiple PhysioExperiment objects.
grandAverage(...)grandAverage(...)
... |
PhysioExperiment objects or a list of them. |
A PhysioExperiment object with grand averaged data.
Calculates the graph Laplacian matrix.
graphLaplacian(adjacency, normalized = FALSE)graphLaplacian(adjacency, normalized = FALSE)
adjacency |
An adjacency matrix. |
normalized |
If TRUE, returns normalized Laplacian. |
The Laplacian matrix.
adj <- matrix(c(0, 1, 1, 1, 0, 1, 1, 1, 0), 3, 3) L <- graphLaplacian(adj)adj <- matrix(c(0, 1, 1, 1, 0, 1, 1, 1, 0), 3, 3) L <- graphLaplacian(adj)
Provides various strategies for handling NA values in signal data.
handleNA( x, method = c("interpolate", "omit", "zero", "mean", "locf", "none"), ... )handleNA( x, method = c("interpolate", "omit", "zero", "mean", "locf", "none"), ... )
x |
Numeric vector or matrix. |
method |
Method for handling NA: "omit" (remove), "interpolate" (linear), "zero" (replace with 0), "mean" (replace with mean), "locf" (last observation carried forward), or "none" (no action). |
... |
Additional arguments passed to interpolation methods. |
Data with NA values handled according to the specified method.
x <- c(1, NA, 3, NA, 5) # Linear interpolation handleNA(x, method = "interpolate") # Replace with mean handleNA(x, method = "mean") # Last observation carried forward handleNA(x, method = "locf")x <- c(1, NA, 3, NA, 5) # Linear interpolation handleNA(x, method = "interpolate") # Replace with mean handleNA(x, method = "mean") # Last observation carried forward handleNA(x, method = "locf")
Quick check for NA presence in PhysioExperiment data.
hasNA(x, assay_name = NULL)hasNA(x, assay_name = NULL)
x |
A PhysioExperiment object. |
assay_name |
Optional specific assay to check. |
Logical indicating presence of NA values.
pe <- PhysioExperiment( assays = list(raw = matrix(1:4, nrow = 2)), samplingRate = 100 ) hasNA(pe)pe <- PhysioExperiment( assays = list(raw = matrix(1:4, nrow = 2)), samplingRate = 100 ) hasNA(pe)
Computes the analytic signal using the Hilbert transform. The analytic signal can be used to extract instantaneous amplitude and phase.
hilbertTransform(x, output_assay = "analytic")hilbertTransform(x, output_assay = "analytic")
x |
A PhysioExperiment object. |
output_assay |
Name for the output assay. |
Modified PhysioExperiment with analytic signal assay.
pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(500 * 4), nrow = 500)), samplingRate = 100 ) # Compute Hilbert transform pe <- hilbertTransform(pe) # Extract amplitude and phase pe <- instantaneousAmplitude(pe) pe <- instantaneousPhase(pe)pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(500 * 4), nrow = 500)), samplingRate = 100 ) # Compute Hilbert transform pe <- hilbertTransform(pe) # Extract amplitude and phase pe <- instantaneousAmplitude(pe) pe <- instantaneousPhase(pe)
Functions for Independent Component Analysis (ICA) and artifact removal from physiological signals. Perform ICA decomposition
icaDecompose( x, n_components = NULL, method = c("fastica", "jade"), max_iter = 200L, tol = 1e-04 )icaDecompose( x, n_components = NULL, method = c("fastica", "jade"), max_iter = 200L, tol = 1e-04 )
x |
A PhysioExperiment object. |
n_components |
Number of components to extract. If NULL, uses number of channels. |
method |
ICA method: "fastica" (default) or "jade". |
max_iter |
Maximum iterations for convergence. |
tol |
Tolerance for convergence. |
Decomposes the signal into independent components using FastICA algorithm.
A list containing:
components: The independent components (time x component matrix)
mixing: The mixing matrix (channel x component)
unmixing: The unmixing matrix (component x channel)
object: Modified PhysioExperiment with ICA components as assay
Removes specified ICA components and reconstructs the signal.
icaRemove(x, components, output_assay = "ica_cleaned")icaRemove(x, components, output_assay = "ica_cleaned")
x |
A PhysioExperiment object with ICA decomposition. |
components |
Integer vector of component indices to remove. |
output_assay |
Name for the output assay. |
Modified PhysioExperiment with cleaned signal.
Functions for managing experiment data in DuckDB database. Provides a relational schema for storing metadata, signals, and events. Initialize PhysioExperiment database schema
initPhysioSchema(con)initPhysioSchema(con)
con |
A DuckDB connection from connectDatabase(). |
Creates the database tables for storing experiment metadata, signals, and events.
Invisible NULL.
## Not run: # Set up a new database con <- connectDatabase("experiments.duckdb") initPhysioSchema(con) # Check statistics dbStats(con) disconnectDatabase(con) ## End(Not run)## Not run: # Set up a new database con <- connectDatabase("experiments.duckdb") initPhysioSchema(con) # Check statistics dbStats(con) disconnectDatabase(con) ## End(Not run)
Extracts the instantaneous amplitude (envelope) from the analytic signal.
instantaneousAmplitude(x, assay_name = "analytic", output_assay = "amplitude")instantaneousAmplitude(x, assay_name = "analytic", output_assay = "amplitude")
x |
A PhysioExperiment object with analytic signal. |
assay_name |
Name of the analytic signal assay. |
output_assay |
Name for the output assay. |
Modified PhysioExperiment with amplitude assay.
pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(500 * 4), nrow = 500)), samplingRate = 100 ) # First compute Hilbert transform, then extract amplitude pe <- hilbertTransform(pe) pe <- instantaneousAmplitude(pe)pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(500 * 4), nrow = 500)), samplingRate = 100 ) # First compute Hilbert transform, then extract amplitude pe <- hilbertTransform(pe) pe <- instantaneousAmplitude(pe)
Extracts the instantaneous phase from the analytic signal.
instantaneousPhase(x, assay_name = "analytic", output_assay = "phase")instantaneousPhase(x, assay_name = "analytic", output_assay = "phase")
x |
A PhysioExperiment object with analytic signal. |
assay_name |
Name of the analytic signal assay. |
output_assay |
Name for the output assay. |
Modified PhysioExperiment with phase assay.
pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(500 * 4), nrow = 500)), samplingRate = 100 ) # First compute Hilbert transform, then extract phase pe <- hilbertTransform(pe) pe <- instantaneousPhase(pe)pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(500 * 4), nrow = 500)), samplingRate = 100 ) # First compute Hilbert transform, then extract phase pe <- hilbertTransform(pe) pe <- instantaneousPhase(pe)
Upsamples by an integer factor with interpolation.
interpolate( x, factor, method = c("linear", "spline"), output_assay = "interpolated" )interpolate( x, factor, method = c("linear", "spline"), output_assay = "interpolated" )
x |
A PhysioExperiment object. |
factor |
Integer interpolation factor. |
method |
Interpolation method: "linear" or "spline". |
output_assay |
Name for the output assay. |
A new PhysioExperiment with interpolated data.
Replaces bad channels with interpolated values from neighboring channels.
interpolateBadChannels( x, bad_channels, method = c("average", "spline"), output_assay = "interpolated" )interpolateBadChannels( x, bad_channels, method = c("average", "spline"), output_assay = "interpolated" )
x |
A PhysioExperiment object. |
bad_channels |
Integer vector of channel indices to interpolate. |
method |
Interpolation method: "average" or "spline". |
output_assay |
Name for the output assay. |
Modified PhysioExperiment with interpolated channels.
Check if data is average referenced
isAverageReferenced(x)isAverageReferenced(x)
x |
A PhysioExperiment object. |
Logical indicating if data is average referenced.
pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(100), nrow = 10, ncol = 10)), samplingRate = 100 ) pe <- rereference(pe, ref_type = "average") isAverageReferenced(pe) # TRUEpe <- PhysioExperiment( assays = list(raw = matrix(rnorm(100), nrow = 10, ncol = 10)), samplingRate = 100 ) pe <- rereference(pe, ref_type = "average") isAverageReferenced(pe) # TRUE
Standard S4 methods for PhysioExperiment objects including show, subsetting, and combining. Check if object is HDF5-backed
isHDF5Backed(x) isHDF5Backed(x)isHDF5Backed(x) isHDF5Backed(x)
x |
A PhysioExperiment object. |
Returns FALSE by default in PhysioCore. PhysioIO provides the full implementation.
Logical indicating if backed by HDF5.
Logical indicating if assays are HDF5-backed DelayedArrays.
# Regular in-memory PhysioExperiment pe <- PhysioExperiment( assays = list(raw = matrix(1:100, nrow = 10)), samplingRate = 100 ) isHDF5Backed(pe) # FALSE# Regular in-memory PhysioExperiment pe <- PhysioExperiment( assays = list(raw = matrix(1:100, nrow = 10)), samplingRate = 100 ) isHDF5Backed(pe) # FALSE
Starts the PhysioExperiment graphical user interface. This launches a local web server with the Plumber API backend and opens the React-based GUI in either a browser or Electron desktop application.
launchGUI( port = 8000L, host = "127.0.0.1", desktop = FALSE, browser = TRUE, quiet = FALSE )launchGUI( port = 8000L, host = "127.0.0.1", desktop = FALSE, browser = TRUE, quiet = FALSE )
port |
Integer. Port number for the API server. Default is 8000. |
host |
Character. Host address to bind to. Default is "127.0.0.1" for local access only. Use "0.0.0.0" to allow external access. |
desktop |
Logical. If TRUE, attempts to launch the Electron desktop application. If FALSE (default), opens in the default web browser. |
browser |
Logical. If TRUE (default), automatically opens the GUI in the browser. Set to FALSE to start only the API server. |
quiet |
Logical. If TRUE, suppresses startup messages. Default is FALSE. |
The GUI provides a modern, responsive interface for:
Data import and management (EDF, BDF, BrainVision, HDF5, CSV)
Signal visualization with multi-channel display
Preprocessing (filtering, referencing, resampling)
Time-frequency analysis (spectrograms, wavelets)
Connectivity analysis (coherence, PLV, PLI)
Statistical testing (t-test, ANOVA, cluster permutation)
Workflow building for batch processing
The GUI communicates with R through a REST API built on plumber. All computations are performed in R using the PhysioExperiment package.
Invisibly returns the plumber object. The function blocks while the server is running unless run in background mode.
Desktop mode requires Electron to be installed. The Electron application provides native file access and a more integrated desktop experience. If Electron is not available, the function falls back to browser mode.
The following packages are required and will be loaded automatically:
plumber - for the REST API server
jsonlite - for JSON serialization
## Not run: # Launch GUI in browser launchGUI() # Launch on a different port launchGUI(port = 3000) # Start API server without opening browser launchGUI(browser = FALSE) # Launch in desktop mode (requires Electron) launchGUI(desktop = TRUE) ## End(Not run)## Not run: # Launch GUI in browser launchGUI() # Launch on a different port launchGUI(port = 3000) # Start API server without opening browser launchGUI(browser = FALSE) # Launch in desktop mode (requires Electron) launchGUI(desktop = TRUE) ## End(Not run)
Returns the number of time points.
## S4 method for signature 'PhysioExperiment' length(x)## S4 method for signature 'PhysioExperiment' length(x)
x |
A PhysioExperiment object. |
Integer number of time points.
pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), samplingRate = 100 ) length(pe) # 100pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), samplingRate = 100 ) length(pe) # 100
List sessions for a subject in BIDS dataset
listBIDSSessions(bids_root, subject)listBIDSSessions(bids_root, subject)
bids_root |
Path to the BIDS dataset root. |
subject |
Subject identifier (without 'sub-' prefix). |
Character vector of session IDs (without 'ses-' prefix).
## Not run: # List sessions for a specific subject sessions <- listBIDSSessions("path/to/bids", subject = "01") print(sessions) # e.g., c("baseline", "followup") ## End(Not run)## Not run: # List sessions for a specific subject sessions <- listBIDSSessions("path/to/bids", subject = "01") print(sessions) # e.g., c("baseline", "followup") ## End(Not run)
List subjects in a BIDS dataset
listBIDSSubjects(bids_root)listBIDSSubjects(bids_root)
bids_root |
Path to the BIDS dataset root. |
Character vector of subject IDs (without 'sub-' prefix).
## Not run: # List all subjects in a BIDS dataset subjects <- listBIDSSubjects("path/to/bids") print(subjects) # e.g., c("01", "02", "03") ## End(Not run)## Not run: # List all subjects in a BIDS dataset subjects <- listBIDSSubjects("path/to/bids") print(subjects) # e.g., c("01", "02", "03") ## End(Not run)
Reconstructs a PhysioExperiment object from database records.
loadExperiment(con, experiment_id, load_signals = FALSE)loadExperiment(con, experiment_id, load_signals = FALSE)
con |
A DuckDB connection. |
experiment_id |
The experiment identifier. |
load_signals |
If TRUE, loads signal data from chunks. |
A PhysioExperiment object.
## Not run: con <- connectDatabase("experiments.duckdb") # Load experiment metadata only pe <- loadExperiment(con, "exp_20240101120000_1234") # Load with signal data pe_full <- loadExperiment(con, "exp_20240101120000_1234", load_signals = TRUE ) disconnectDatabase(con) ## End(Not run)## Not run: con <- connectDatabase("experiments.duckdb") # Load experiment metadata only pe <- loadExperiment(con, "exp_20240101120000_1234") # Load with signal data pe_full <- loadExperiment(con, "exp_20240101120000_1234", load_signals = TRUE ) disconnectDatabase(con) ## End(Not run)
Calculates the local efficiency for each node.
localEfficiency(adjacency, weighted = FALSE)localEfficiency(adjacency, weighted = FALSE)
adjacency |
An adjacency matrix. |
weighted |
If TRUE, uses weighted paths. |
A numeric vector of local efficiency values.
adj <- matrix(c(0, 1, 1, 1, 0, 1, 1, 1, 0), 3, 3) localEfficiency(adj)adj <- matrix(c(0, 1, 1, 1, 0, 1, 1, 1, 0), 3, 3) localEfficiency(adj)
Calculates the modularity of a network given a community partition.
modularity(adjacency, communities)modularity(adjacency, communities)
adjacency |
An adjacency matrix. |
communities |
A vector of community assignments for each node. |
Modularity value (-0.5 to 1).
# Two clear communities adj <- matrix(0, 6, 6) adj[1:3, 1:3] <- 1 adj[4:6, 4:6] <- 1 diag(adj) <- 0 communities <- c(1, 1, 1, 2, 2, 2) modularity(adj, communities)# Two clear communities adj <- matrix(0, 6, 6) adj[1:3, 1:3] <- 1 adj[4:6, 4:6] <- 1 diag(adj) <- 0 communities <- c(1, 1, 1, 2, 2, 2) modularity(adj, communities)
Returns a summary of NA values across all assays.
naSummary(x)naSummary(x)
x |
A PhysioExperiment object. |
A data.frame with NA statistics for each assay.
pe <- PhysioExperiment( assays = list( raw = matrix(c(1, NA, 3, 4), nrow = 2), filtered = matrix(1:4, nrow = 2) ), samplingRate = 100 ) naSummary(pe)pe <- PhysioExperiment( assays = list( raw = matrix(c(1, NA, 3, 4), nrow = 2), filtered = matrix(1:4, nrow = 2) ), samplingRate = 100 ) naSummary(pe)
Get number of channels
nChannels(x)nChannels(x)
x |
A PhysioExperiment object. |
Integer number of channels.
pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), samplingRate = 100 ) nChannels(pe) # 4pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), samplingRate = 100 ) nChannels(pe) # 4
Get number of events
nEvents(x)nEvents(x)
x |
A PhysioEvents object. |
Integer count of events.
Calculates the degree (number of connections) for each node.
nodeDegree(adjacency, weighted = FALSE, use_cpp = TRUE)nodeDegree(adjacency, weighted = FALSE, use_cpp = TRUE)
adjacency |
An adjacency matrix (binary or weighted). |
weighted |
If TRUE, returns weighted degree (strength). |
A numeric vector of node degrees.
adj <- matrix(c(0, 1, 1, 1, 0, 0, 1, 0, 0), 3, 3) nodeDegree(adj)adj <- matrix(c(0, 1, 1, 1, 0, 0, 1, 0, 0), 3, 3) nodeDegree(adj)
Applies a notch filter to remove power line noise (50 Hz or 60 Hz) and optionally its harmonics.
notchFilter( x, freq = 50, bandwidth = 2, harmonics = 1L, output_assay = "filtered" )notchFilter( x, freq = 50, bandwidth = 2, harmonics = 1L, output_assay = "filtered" )
x |
A |
freq |
Center frequency to remove in Hz. Default is 50 (European power line). |
bandwidth |
Bandwidth of the notch in Hz. Default is 2. |
harmonics |
Number of harmonics to remove. Default is 1 (only fundamental). |
output_assay |
Name for the output assay. Default is "filtered". |
The input object with a new assay containing filtered data.
pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1000 * 4), nrow = 1000)), samplingRate = 250 ) # Remove 50 Hz power line noise (Europe/Asia) pe <- notchFilter(pe, freq = 50) # Remove 60 Hz and harmonics (Americas) pe <- notchFilter(pe, freq = 60, harmonics = 2)pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1000 * 4), nrow = 1000)), samplingRate = 250 ) # Remove 50 Hz power line noise (Europe/Asia) pe <- notchFilter(pe, freq = 50) # Remove 60 Hz and harmonics (Americas) pe <- notchFilter(pe, freq = 60, harmonics = 2)
Calculates the shortest path length between all node pairs using Floyd-Warshall.
pathLength(adjacency, weighted = FALSE, use_cpp = TRUE)pathLength(adjacency, weighted = FALSE, use_cpp = TRUE)
adjacency |
An adjacency matrix. |
weighted |
If TRUE, uses edge weights as distances. |
A matrix of shortest path lengths.
adj <- matrix(c(0, 1, 0, 1, 0, 1, 0, 1, 0), 3, 3) pathLength(adj)adj <- matrix(c(0, 1, 0, 1, 0, 1, 0, 1, 0), 3, 3) pathLength(adj)
Create a PhysioEvents object
PhysioEvents( onset = numeric(0), duration = numeric(0), type = character(0), value = character(0) )PhysioEvents( onset = numeric(0), duration = numeric(0), type = character(0), value = character(0) )
onset |
Numeric vector of event onset times in seconds. |
duration |
Numeric vector of event durations in seconds. |
type |
Character vector of event types (e.g., "stimulus", "response"). |
value |
Character vector of event values/labels. |
A PhysioEvents object.
# Create events for a simple experiment events <- PhysioEvents( onset = c(1.0, 2.5, 4.0, 5.5), duration = c(0.5, 0.5, 0.5, 0.5), type = c("stimulus", "response", "stimulus", "response"), value = c("target", "hit", "distractor", "false_alarm") ) events # Create events with single type stim_events <- PhysioEvents( onset = c(1, 2, 3, 4, 5), type = "stimulus" )# Create events for a simple experiment events <- PhysioEvents( onset = c(1.0, 2.5, 4.0, 5.5), duration = c(0.5, 0.5, 0.5, 0.5), type = c("stimulus", "response", "stimulus", "response"), value = c("target", "hit", "distractor", "false_alarm") ) events # Create events with single type stim_events <- PhysioEvents( onset = c(1, 2, 3, 4, 5), type = "stimulus" )
Functions for managing experimental events (triggers, markers, annotations) within PhysioExperiment objects. PhysioEvents class
A simple S4 class to store event information as a DataFrame.
eventsA DataFrame containing event information with columns: onset (numeric), duration (numeric), type (character), value (character).
Construct a PhysioExperiment object
PhysioExperiment( assays = S4Vectors::SimpleList(), rowData = NULL, colData = NULL, metadata = list(), samplingRate = as.numeric(NA) )PhysioExperiment( assays = S4Vectors::SimpleList(), rowData = NULL, colData = NULL, metadata = list(), samplingRate = as.numeric(NA) )
assays |
A |
rowData |
Feature-level metadata as a |
colData |
Sample-level metadata as a |
metadata |
Optional experiment-level metadata list. |
samplingRate |
Numeric scalar sampling rate in Hz. |
A PhysioExperiment instance.
# Create a simple PhysioExperiment with random EEG-like data # 1000 time points, 4 channels eeg_data <- matrix(rnorm(1000 * 4), nrow = 1000, ncol = 4) colnames(eeg_data) <- c("Fz", "Cz", "Pz", "Oz") pe <- PhysioExperiment( assays = list(raw = eeg_data), colData = S4Vectors::DataFrame( label = c("Fz", "Cz", "Pz", "Oz"), type = rep("EEG", 4) ), samplingRate = 250 ) pe # Access sampling rate samplingRate(pe) # Create with multiple assays pe2 <- PhysioExperiment( assays = list(raw = eeg_data, filtered = eeg_data * 0.5), samplingRate = 500 )# Create a simple PhysioExperiment with random EEG-like data # 1000 time points, 4 channels eeg_data <- matrix(rnorm(1000 * 4), nrow = 1000, ncol = 4) colnames(eeg_data) <- c("Fz", "Cz", "Pz", "Oz") pe <- PhysioExperiment( assays = list(raw = eeg_data), colData = S4Vectors::DataFrame( label = c("Fz", "Cz", "Pz", "Oz"), type = rep("EEG", 4) ), samplingRate = 250 ) pe # Access sampling rate samplingRate(pe) # Create with multiple assays pe2 <- PhysioExperiment( assays = list(raw = eeg_data, filtered = eeg_data * 0.5), samplingRate = 500 )
The PhysioExperiment class extends SummarizedExperiment to store
multi-modal physiological signal data alongside metadata such as sampling
rate. This file defines the class, its validity checks, and the
user-facing constructor.
samplingRateNumeric scalar describing the acquisition frequency in Hz.
Creates a new PhysioExperiment with only selected channels.
pickChannels(x, channels)pickChannels(x, channels)
x |
A PhysioExperiment object. |
channels |
Integer indices or character names of channels to keep. |
A new PhysioExperiment with selected channels.
pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), colData = S4Vectors::DataFrame(label = c("Fz", "Cz", "Pz", "Oz")), samplingRate = 100 ) # Pick by index pe_subset <- pickChannels(pe, c(1, 3)) nChannels(pe_subset) # 2 # Pick by name pe_frontal <- pickChannels(pe, c("Fz", "Cz"))pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), colData = S4Vectors::DataFrame(label = c("Fz", "Cz", "Pz", "Oz")), samplingRate = 100 ) # Pick by index pe_subset <- pickChannels(pe, c(1, 3)) nChannels(pe_subset) # 2 # Pick by name pe_frontal <- pickChannels(pe, c("Fz", "Cz"))
Calculates the Phase Lag Index between channel pairs, a measure of asymmetry in the phase difference distribution.
pli(x, freq_band, channels = NULL, assay_name = NULL)pli(x, freq_band, channels = NULL, assay_name = NULL)
x |
A PhysioExperiment object. |
freq_band |
Numeric vector of length 2 specifying frequency band (Hz). |
channels |
Integer vector of channel indices. |
assay_name |
Input assay name. |
PLI measures the asymmetry of the distribution of phase differences. Unlike PLV, PLI is insensitive to volume conduction effects that lead to zero-lag synchronization.
PLI = |mean(sign(Im(S_xy)))|, where S_xy is the cross-spectrum.
A matrix of PLI values (channel x channel), values 0-1.
set.seed(123) pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(4000), nrow = 1000, ncol = 4)), rowData = S4Vectors::DataFrame(label = c("Fz", "Cz", "Pz", "Oz")), samplingRate = 256 ) # Compute PLI in alpha band (8-12 Hz) pli_matrix <- pli(pe, freq_band = c(8, 12))set.seed(123) pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(4000), nrow = 1000, ncol = 4)), rowData = S4Vectors::DataFrame(label = c("Fz", "Cz", "Pz", "Oz")), samplingRate = 256 ) # Compute PLI in alpha band (8-12 Hz) pli_matrix <- pli(pe, freq_band = c(8, 12))
Creates a heatmap visualization of an adjacency or connectivity matrix.
plotAdjacencyMatrix( adjacency, node_names = NULL, symmetric = TRUE, color_palette = "default", show_values = FALSE, title = "Connectivity Matrix" )plotAdjacencyMatrix( adjacency, node_names = NULL, symmetric = TRUE, color_palette = "default", show_values = FALSE, title = "Connectivity Matrix" )
adjacency |
An adjacency matrix or connectivity result. |
node_names |
Optional vector of node names. |
symmetric |
If TRUE, only shows lower triangle. |
color_palette |
Color palette: "default", "viridis", "heat", or custom. |
show_values |
If TRUE, displays values in cells. |
title |
Plot title. |
A ggplot object.
set.seed(123) adj <- matrix(runif(16), 4, 4) adj <- (adj + t(adj)) / 2 diag(adj) <- 1 plotAdjacencyMatrix(adj, node_names = c("Fz", "Cz", "Pz", "Oz"))set.seed(123) adj <- matrix(runif(16), 4, 4) adj <- (adj + t(adj)) / 2 diag(adj) <- 1 plotAdjacencyMatrix(adj, node_names = c("Fz", "Cz", "Pz", "Oz"))
Creates a visualization of time-varying connectivity.
plotDynamicConnectivity( dyn_conn, node_pair = "mean", title = "Dynamic Connectivity" )plotDynamicConnectivity( dyn_conn, node_pair = "mean", title = "Dynamic Connectivity" )
dyn_conn |
Result from slidingWindowConnectivity(). |
node_pair |
Vector of two node indices to plot, or "mean" for average. |
title |
Plot title. |
A ggplot object.
set.seed(123) pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1000 * 4), nrow = 1000, ncol = 4)), samplingRate = 100 ) dyn_conn <- slidingWindowConnectivity(pe, window_size = 200, step = 50) plotDynamicConnectivity(dyn_conn, node_pair = c(1, 2))set.seed(123) pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1000 * 4), nrow = 1000, ncol = 4)), samplingRate = 100 ) dyn_conn <- slidingWindowConnectivity(pe, window_size = 200, step = 50) plotDynamicConnectivity(dyn_conn, node_pair = c(1, 2))
Generates an ERP plot from epoched data.
plotERP(x, channel = 1L, ci = 0.95, show_epochs = FALSE, epoch_alpha = 0.2)plotERP(x, channel = 1L, ci = 0.95, show_epochs = FALSE, epoch_alpha = 0.2)
x |
An epoched PhysioExperiment object. |
channel |
Integer index or character name of the channel. |
ci |
Confidence interval level (0-1). NULL for no CI. |
show_epochs |
Logical. If TRUE, shows individual epoch traces. |
epoch_alpha |
Alpha value for individual epoch traces. |
A ggplot object.
Functions for visualizing multiple channels simultaneously. Plot multiple channels (butterfly or stacked)
plotMultiChannel( x, channels = NULL, sample = 1L, style = c("butterfly", "stacked"), offset = NULL, assay_name = NULL, colors = NULL )plotMultiChannel( x, channels = NULL, sample = 1L, style = c("butterfly", "stacked"), offset = NULL, assay_name = NULL, colors = NULL )
x |
A PhysioExperiment object. |
channels |
Integer vector of channel indices to plot. If NULL, plots all. |
sample |
Integer index for the sample (for 3D data). |
style |
Plot style: "butterfly" (overlaid) or "stacked" (offset). |
offset |
Numeric offset between channels for stacked plot. |
assay_name |
Optional assay name. If NULL, uses the default assay. |
colors |
Optional color vector for channels. |
Generates a plot showing multiple channels from the signal data.
A ggplot object.
# Create example data pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(500 * 4), nrow = 500)), rowData = S4Vectors::DataFrame(label = c("Fz", "Cz", "Pz", "Oz")), samplingRate = 100 ) # Butterfly plot (all channels overlaid) plotMultiChannel(pe, style = "butterfly") # Stacked plot (channels offset vertically) plotMultiChannel(pe, style = "stacked") # Plot specific channels plotMultiChannel(pe, channels = c(1, 3), style = "butterfly")# Create example data pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(500 * 4), nrow = 500)), rowData = S4Vectors::DataFrame(label = c("Fz", "Cz", "Pz", "Oz")), samplingRate = 100 ) # Butterfly plot (all channels overlaid) plotMultiChannel(pe, style = "butterfly") # Stacked plot (channels offset vertically) plotMultiChannel(pe, style = "stacked") # Plot specific channels plotMultiChannel(pe, channels = c(1, 3), style = "butterfly")
Functions for visualizing functional connectivity networks including network graphs, adjacency matrices, and network metrics. Plot network graph
plotNetwork( adjacency, node_names = NULL, node_size = "degree", edge_threshold = 0, layout = c("circle", "spring", "grid"), node_color = "#3498db", edge_color = "#7f8c8d", title = "Network Graph" )plotNetwork( adjacency, node_names = NULL, node_size = "degree", edge_threshold = 0, layout = c("circle", "spring", "grid"), node_color = "#3498db", edge_color = "#7f8c8d", title = "Network Graph" )
adjacency |
An adjacency matrix or connectivity result. |
node_names |
Optional vector of node names. |
node_size |
Node size. Can be "degree", "betweenness", "eigenvector", or numeric. |
edge_threshold |
Minimum edge weight to display. |
layout |
Layout algorithm: "circle", "spring", or "grid". |
node_color |
Node color or vector of colors. |
edge_color |
Edge color. |
title |
Plot title. |
Creates a network graph visualization with nodes and edges.
A ggplot object.
set.seed(123) adj <- matrix(runif(16), 4, 4) adj <- (adj + t(adj)) / 2 diag(adj) <- 0 plotNetwork(adj, node_names = c("Fz", "Cz", "Pz", "Oz"))set.seed(123) adj <- matrix(runif(16), 4, 4) adj <- (adj + t(adj)) / 2 diag(adj) <- 0 plotNetwork(adj, node_names = c("Fz", "Cz", "Pz", "Oz"))
Creates a bar plot of network metrics for each node.
plotNetworkMetrics( adjacency, metrics = c("degree", "clustering", "betweenness"), node_names = NULL, title = "Network Metrics" )plotNetworkMetrics( adjacency, metrics = c("degree", "clustering", "betweenness"), node_names = NULL, title = "Network Metrics" )
adjacency |
An adjacency matrix. |
metrics |
Vector of metrics to compute: "degree", "clustering", "betweenness", "eigenvector", "local_efficiency". |
node_names |
Optional vector of node names. |
title |
Plot title. |
A ggplot object.
adj <- matrix(c(0, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0), 4, 4) plotNetworkMetrics(adj, node_names = c("Fz", "Cz", "Pz", "Oz"))adj <- matrix(c(0, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0), 4, 4) plotNetworkMetrics(adj, node_names = c("Fz", "Cz", "Pz", "Oz"))
Visualizes the temporal stability of network topology.
plotNetworkStability(stability, title = "Network Stability")plotNetworkStability(stability, title = "Network Stability")
stability |
Result from temporalStability(). |
title |
Plot title. |
A ggplot object.
set.seed(123) pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1000 * 4), nrow = 1000, ncol = 4)), samplingRate = 100 ) dyn_conn <- slidingWindowConnectivity(pe, window_size = 200, step = 50) stab <- temporalStability(dyn_conn) plotNetworkStability(stab)set.seed(123) pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1000 * 4), nrow = 1000, ncol = 4)), samplingRate = 100 ) dyn_conn <- slidingWindowConnectivity(pe, window_size = 200, step = 50) stab <- temporalStability(dyn_conn) plotNetworkStability(stab)
Generates a PSD plot for specified channels.
plotPSD(x, channels = NULL, sample = 1L, log_scale = TRUE, freq_range = NULL)plotPSD(x, channels = NULL, sample = 1L, log_scale = TRUE, freq_range = NULL)
x |
A PhysioExperiment object. |
channels |
Integer vector of channel indices. If NULL, plots all. |
sample |
Integer index for the sample (for 3D data). |
log_scale |
Logical. If TRUE, uses log scale for power. |
freq_range |
Numeric vector of length 2 specifying frequency range. |
A ggplot object.
Generates a simple line plot for the selected channel and sample from the default assay. Supports both 2D (time x channel) and 3D (time x channel x sample) assay arrays.
plotSignal(x, channel = 1L, sample = 1L, assay_name = NULL)plotSignal(x, channel = 1L, sample = 1L, assay_name = NULL)
x |
A |
channel |
Integer index for the channel. |
sample |
Integer index for the sample (only used for 3D arrays). |
assay_name |
Optional assay name. If NULL, uses the default assay. |
A ggplot object.
Creates a visualization of a spectrogram result.
plotSpectrogram(spec, freq_range = NULL, log_power = TRUE)plotSpectrogram(spec, freq_range = NULL, log_power = TRUE)
spec |
Spectrogram result from spectrogram(). |
freq_range |
Optional frequency range to display. |
log_power |
If TRUE, displays log power. |
A ggplot object.
pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1000 * 4), nrow = 1000)), samplingRate = 250 ) # Compute spectrogram spec <- spectrogram(pe, channel = 1) # Plot with frequency range filter plotSpectrogram(spec, freq_range = c(1, 50))pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1000 * 4), nrow = 1000)), samplingRate = 250 ) # Compute spectrogram spec <- spectrogram(pe, channel = 1) # Plot with frequency range filter plotSpectrogram(spec, freq_range = c(1, 50))
Visualizes SPM analysis results with significance thresholds.
plotSPM( x, time_axis = NULL, show_threshold = TRUE, show_clusters = TRUE, title = NULL )plotSPM( x, time_axis = NULL, show_threshold = TRUE, show_clusters = TRUE, title = NULL )
x |
An spm_result object. |
time_axis |
Optional time axis values. |
show_threshold |
Logical; if TRUE, shows significance threshold. |
show_clusters |
Logical; if TRUE, highlights significant clusters. |
title |
Plot title. |
A ggplot object.
# Create and plot SPM result set.seed(123) g1 <- matrix(rnorm(100 * 10), nrow = 100) g2 <- matrix(rnorm(100 * 10), nrow = 100) g2[40:60, ] <- g2[40:60, ] + 1.5 pe <- PhysioExperiment( assays = list(values = cbind(g1, g2)), samplingRate = 100 ) result <- spmTTest(pe, group1 = 1:10, group2 = 11:20) plotSPM(result)# Create and plot SPM result set.seed(123) g1 <- matrix(rnorm(100 * 10), nrow = 100) g2 <- matrix(rnorm(100 * 10), nrow = 100) g2[40:60, ] <- g2[40:60, ] + 1.5 pe <- PhysioExperiment( assays = list(values = cbind(g1, g2)), samplingRate = 100 ) result <- spmTTest(pe, group1 = 1:10, group2 = 11:20) plotSPM(result)
Functions for plotting scalp topography maps showing the spatial distribution of signal values across electrode positions. Plot topographic map (scalp topography)
plotTopomap( x, values = NULL, time = NULL, channel_values = NULL, assay_name = NULL, resolution = 100L, contours = TRUE, head_shape = TRUE, electrodes = TRUE, palette = "RdBu", limits = NULL, title = NULL )plotTopomap( x, values = NULL, time = NULL, channel_values = NULL, assay_name = NULL, resolution = 100L, contours = TRUE, head_shape = TRUE, electrodes = TRUE, palette = "RdBu", limits = NULL, title = NULL )
x |
A PhysioExperiment object with electrode positions. |
values |
Optional numeric vector of values to plot. If NULL, uses values from the specified time point. |
time |
Time point in seconds to extract values (if values is NULL). |
channel_values |
Named vector of channel values (alternative to values). |
assay_name |
Optional assay name. If NULL, uses the default assay. |
resolution |
Grid resolution for interpolation. Default is 100. |
contours |
Logical. If TRUE, adds contour lines. Default is TRUE |
head_shape |
Logical. If TRUE, draws head outline. Default is TRUE. |
electrodes |
Logical. If TRUE, shows electrode positions. Default is TRUE. |
palette |
Color palette name or vector of colors. |
limits |
Numeric vector of length 2 for color scale limits. |
title |
Plot title. If NULL, auto-generated. |
Creates a 2D topographic map showing the spatial distribution of values across electrode positions on the scalp.
A ggplot object.
# Create example with 10-20 electrode positions pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), rowData = S4Vectors::DataFrame(label = c("Fz", "Cz", "Pz", "Oz")), samplingRate = 100 ) # Apply 10-20 montage to get electrode positions pe <- applyMontage(pe, "10-20") # Plot topographic map at time = 0.5s plotTopomap(pe, time = 0.5) # Plot with custom values plotTopomap(pe, values = c(1, 0.5, -0.5, -1))# Create example with 10-20 electrode positions pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), rowData = S4Vectors::DataFrame(label = c("Fz", "Cz", "Pz", "Oz")), samplingRate = 100 ) # Apply 10-20 montage to get electrode positions pe <- applyMontage(pe, "10-20") # Plot topographic map at time = 0.5s plotTopomap(pe, time = 0.5) # Plot with custom values plotTopomap(pe, values = c(1, 0.5, -0.5, -1))
Creates a series of topographic maps across time.
plotTopomapSeries(x, times, ...)plotTopomapSeries(x, times, ...)
x |
A PhysioExperiment object with electrode positions. |
times |
Numeric vector of time points to plot. |
... |
Additional arguments passed to plotTopomap. |
A list of ggplot objects.
## Not run: pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), rowData = S4Vectors::DataFrame(label = c("Fz", "Cz", "Pz", "Oz")), samplingRate = 100 ) pe <- applyMontage(pe, "10-20") # Create topomaps at multiple time points plots <- plotTopomapSeries(pe, times = c(0.1, 0.2, 0.3, 0.4)) ## End(Not run)## Not run: pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), rowData = S4Vectors::DataFrame(label = c("Fz", "Cz", "Pz", "Oz")), samplingRate = 100 ) pe <- applyMontage(pe, "10-20") # Create topomaps at multiple time points plots <- plotTopomapSeries(pe, times = c(0.1, 0.2, 0.3, 0.4)) ## End(Not run)
Calculates the Phase Locking Value between channel pairs, measuring the consistency of phase difference across time.
plv(x, freq_band, channels = NULL, assay_name = NULL)plv(x, freq_band, channels = NULL, assay_name = NULL)
x |
A PhysioExperiment object. |
freq_band |
Numeric vector of length 2 specifying frequency band (Hz). |
channels |
Integer vector of channel indices. |
assay_name |
Input assay name. |
PLV measures the consistency of the phase difference between two signals. A value of 1 indicates perfect phase locking, while 0 indicates random phase relationship.
The signals are first bandpass filtered to the specified frequency band, then the analytic signal is computed using the Hilbert transform.
A matrix of PLV values (channel x channel), values 0-1.
set.seed(123) pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(4000), nrow = 1000, ncol = 4)), rowData = S4Vectors::DataFrame(label = c("Fz", "Cz", "Pz", "Oz")), samplingRate = 256 ) # Compute PLV in alpha band (8-12 Hz) plv_matrix <- plv(pe, freq_band = c(8, 12))set.seed(123) pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(4000), nrow = 1000, ncol = 4)), rowData = S4Vectors::DataFrame(label = c("Fz", "Cz", "Pz", "Oz")), samplingRate = 256 ) # Compute PLV in alpha band (8-12 Hz) plv_matrix <- plv(pe, freq_band = c(8, 12))
Print SPM result
## S3 method for class 'spm_result' print(x, ...)## S3 method for class 'spm_result' print(x, ...)
Query experiments from database
queryExperiments(con, subject_id = NULL, task = NULL, date_range = NULL)queryExperiments(con, subject_id = NULL, task = NULL, date_range = NULL)
con |
A DuckDB connection. |
subject_id |
Optional filter by subject. |
task |
Optional filter by task. |
date_range |
Optional date range (vector of 2 dates). |
A data.frame of matching experiments.
## Not run: con <- connectDatabase("experiments.duckdb") # Query all experiments all_exps <- queryExperiments(con) # Filter by subject sub01_exps <- queryExperiments(con, subject_id = "sub01") # Filter by task rest_exps <- queryExperiments(con, task = "rest") # Filter by date range recent <- queryExperiments(con, date_range = c("2024-01-01", "2024-12-31") ) disconnectDatabase(con) ## End(Not run)## Not run: con <- connectDatabase("experiments.duckdb") # Query all experiments all_exps <- queryExperiments(con) # Filter by subject sub01_exps <- queryExperiments(con, subject_id = "sub01") # Filter by task rest_exps <- queryExperiments(con, task = "rest") # Filter by date range recent <- queryExperiments(con, date_range = c("2024-01-01", "2024-12-31") ) disconnectDatabase(con) ## End(Not run)
Concatenates two PhysioExperiment objects along the time axis.
rbindPhysio(x, y)rbindPhysio(x, y)
x |
A PhysioExperiment object. |
y |
A PhysioExperiment object to concatenate. |
Combined PhysioExperiment object.
pe1 <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), samplingRate = 100 ) pe2 <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), samplingRate = 100 ) # Concatenate in time pe_concat <- rbindPhysio(pe1, pe2) length(pe_concat) # 200pe1 <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), samplingRate = 100 ) pe2 <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), samplingRate = 100 ) # Concatenate in time pe_concat <- rbindPhysio(pe1, pe2) length(pe_concat) # 200
Reads a BDF file and returns a PhysioExperiment object. BDF is a 24-bit extension of the EDF format used by BioSemi systems.
readBDF(path, channels = NULL, start_time = NULL, end_time = NULL)readBDF(path, channels = NULL, start_time = NULL, end_time = NULL)
path |
Path to the BDF file. |
channels |
Optional character vector of channel names to load. If NULL, all channels are loaded. |
start_time |
Optional start time in seconds for reading a subset. |
end_time |
Optional end time in seconds for reading a subset. |
BDF (BioSemi Data Format) is a 24-bit variant of EDF used by BioSemi acquisition systems. The main differences from EDF are:
24-bit data resolution (vs 16-bit in EDF)
Header starts with 0xFF followed by "BIOSEMI"
Digital range is -8388608 to 8388607
A PhysioExperiment object.
## Not run: # Read a BDF file pe <- readBDF("recording.bdf") # Read only specific channels pe <- readBDF("recording.bdf", channels = c("A1", "A2", "B1", "B2")) ## End(Not run)## Not run: # Read a BDF file pe <- readBDF("recording.bdf") # Read only specific channels pe <- readBDF("recording.bdf", channels = c("A1", "A2", "B1", "B2")) ## End(Not run)
Functions for reading and writing data in BIDS (Brain Imaging Data Structure) format. Supports BIDS-EEG and BIDS-iEEG specifications. Read PhysioExperiment from BIDS dataset
readBIDS( bids_root, subject, session = NULL, task, run = NULL, modality = c("eeg", "ieeg"), load_events = TRUE )readBIDS( bids_root, subject, session = NULL, task, run = NULL, modality = c("eeg", "ieeg"), load_events = TRUE )
bids_root |
Path to the BIDS dataset root directory. |
subject |
Subject identifier (without 'sub-' prefix). |
session |
Session identifier (without 'ses-' prefix). Optional. |
task |
Task name. |
run |
Run number. Optional. |
modality |
Data modality: "eeg" or "ieeg". |
load_events |
If TRUE, loads events from the events.tsv file. |
Reads EEG/iEEG data from a BIDS-compliant directory structure.
A PhysioExperiment object.
## Not run: # Read EEG data from BIDS dataset pe <- readBIDS("path/to/bids", subject = "01", task = "rest") # Read with session and run specified pe <- readBIDS("path/to/bids", subject = "01", session = "01", task = "oddball", run = 1, modality = "eeg") # Read without loading events pe <- readBIDS("path/to/bids", subject = "02", task = "rest", load_events = FALSE) ## End(Not run)## Not run: # Read EEG data from BIDS dataset pe <- readBIDS("path/to/bids", subject = "01", task = "rest") # Read with session and run specified pe <- readBIDS("path/to/bids", subject = "01", session = "01", task = "oddball", run = 1, modality = "eeg") # Read without loading events pe <- readBIDS("path/to/bids", subject = "02", task = "rest", load_events = FALSE) ## End(Not run)
Functions for reading and writing BrainVision format files (.vhdr/.vmrk/.eeg). BrainVision is one of the official BIDS-EEG formats and is widely supported by EEG analysis software (MNE-Python, EEGLAB, FieldTrip, etc.). Read PhysioExperiment from BrainVision files
readBrainVision(path, channels = NULL)readBrainVision(path, channels = NULL)
path |
Path to the .vhdr header file. |
channels |
Optional character vector of channel names to load. If NULL, loads all channels. |
Reads EEG data from BrainVision format files. The format consists of three files: a header file (.vhdr), a marker file (.vmrk), and a binary data file (.eeg).
A PhysioExperiment object.
## Not run: pe <- readBrainVision("recording.vhdr") ## End(Not run)## Not run: pe <- readBrainVision("recording.vhdr") ## End(Not run)
Functions for reading and writing signal data in CSV/TSV format. Supports both wide format (time x channels) and long format. Read PhysioExperiment from CSV file
readCSV( path, format = c("wide", "long"), time_col = NULL, channel_cols = NULL, sampling_rate = NULL, sep = ",", header = TRUE, ... )readCSV( path, format = c("wide", "long"), time_col = NULL, channel_cols = NULL, sampling_rate = NULL, sep = ",", header = TRUE, ... )
path |
Path to the CSV file. |
format |
Data format: "wide" (time x channels) or "long" (stacked). |
time_col |
Name of the time column. If NULL, assumes first column or generates time from sampling rate. |
channel_cols |
For wide format, column names/indices to use as channels. If NULL, uses all non-time columns. |
sampling_rate |
Sampling rate in Hz. Required if time column is not present. |
sep |
Column separator. Default is ",". |
header |
Logical. If TRUE, first row contains column names. |
... |
Additional arguments passed to read.csv/read.table. |
Reads physiological signal data from a CSV file.
A PhysioExperiment object.
## Not run: # Read wide-format CSV with time column pe <- readCSV("signals.csv", time_col = "time", sampling_rate = 256) # Read without time column (generate from sampling rate) pe <- readCSV("signals.csv", sampling_rate = 256) # Read TSV file pe <- readCSV("signals.tsv", sep = "\t", sampling_rate = 256) ## End(Not run)## Not run: # Read wide-format CSV with time column pe <- readCSV("signals.csv", time_col = "time", sampling_rate = 256) # Read without time column (generate from sampling rate) pe <- readCSV("signals.csv", sampling_rate = 256) # Read TSV file pe <- readCSV("signals.tsv", sep = "\t", sampling_rate = 256) ## End(Not run)
Functions for reading European Data Format (EDF/EDF+) files commonly used for EEG, PSG, and other physiological recordings. Read EDF/EDF+ file
readEDF(path, channels = NULL, start_time = NULL, end_time = NULL)readEDF(path, channels = NULL, start_time = NULL, end_time = NULL)
path |
Path to the EDF file. |
channels |
Optional character vector of channel names to load. If NULL, all channels are loaded. |
start_time |
Optional start time in seconds for reading a subset. |
end_time |
Optional end time in seconds for reading a subset. |
Reads an EDF or EDF+ file and returns a PhysioExperiment object.
EDF (European Data Format) is a standard file format for storing multichannel physiological signals. EDF+ extends this with annotations and discontinuous recordings.
The function parses the EDF header to extract:
Channel labels and types
Sampling rates (may differ per channel)
Physical dimensions (units)
Recording start date/time
If channels have different sampling rates, data is resampled to the highest rate.
A PhysioExperiment object.
## Not run: # Read an EDF file pe <- readEDF("recording.edf") # Read only specific channels pe <- readEDF("recording.edf", channels = c("Fp1", "Fp2", "C3", "C4")) # Read a time window (10 to 60 seconds) pe <- readEDF("recording.edf", start_time = 10, end_time = 60) ## End(Not run)## Not run: # Read an EDF file pe <- readEDF("recording.edf") # Read only specific channels pe <- readEDF("recording.edf", channels = c("Fp1", "Fp2", "C3", "C4")) # Read a time window (10 to 60 seconds) pe <- readEDF("recording.edf", start_time = 10, end_time = 60) ## End(Not run)
Reads electrode positions from a CSV file with x, y, z coordinates.
readElectrodePositionsCSV( path, name_col = "name", x_col = "x", y_col = "y", z_col = "z", sep = ",", ... )readElectrodePositionsCSV( path, name_col = "name", x_col = "x", y_col = "y", z_col = "z", sep = ",", ... )
path |
Path to the CSV file. |
name_col |
Name of the electrode name column. |
x_col |
Name of the x coordinate column. |
y_col |
Name of the y coordinate column. |
z_col |
Name of the z coordinate column. |
sep |
Column separator. |
... |
Additional arguments passed to read.csv. |
A data.frame with electrode positions.
## Not run: # Read electrode positions positions <- readElectrodePositionsCSV("electrodes.csv") # Apply to PhysioExperiment pe <- setElectrodePositions(pe, positions) ## End(Not run)## Not run: # Read electrode positions positions <- readElectrodePositionsCSV("electrodes.csv") # Apply to PhysioExperiment pe <- setElectrodePositions(pe, positions) ## End(Not run)
Reads event markers from a CSV file with onset, duration, and type columns.
readEventsCSV( path, onset_col = "onset", duration_col = "duration", type_col = "type", value_col = "value", sep = ",", ... )readEventsCSV( path, onset_col = "onset", duration_col = "duration", type_col = "type", value_col = "value", sep = ",", ... )
path |
Path to the CSV file. |
onset_col |
Name of the onset column (in seconds). |
duration_col |
Name of the duration column. |
type_col |
Name of the event type column. |
value_col |
Name of the event value column. |
sep |
Column separator. |
... |
Additional arguments passed to read.csv. |
A PhysioEvents object.
## Not run: # Read events from CSV events <- readEventsCSV("events.csv") # Add to PhysioExperiment pe <- setEvents(pe, events) ## End(Not run)## Not run: # Read events from CSV events <- readEventsCSV("events.csv") # Add to PhysioExperiment pe <- setEvents(pe, events) ## End(Not run)
Functions for reading and writing GDF format files. GDF is designed to overcome limitations of EDF and is commonly used in BCI research. Supports GDF version 1.x and 2.x. Read PhysioExperiment from GDF file
readGDF(path, channels = NULL, start_time = NULL, end_time = NULL)readGDF(path, channels = NULL, start_time = NULL, end_time = NULL)
path |
Path to the GDF file. |
channels |
Optional integer vector of channel indices or character vector of channel names to load. If NULL, loads all channels. |
start_time |
Optional start time in seconds for selective loading. |
end_time |
Optional end time in seconds for selective loading. |
Reads physiological signal data from a GDF (General Data Format) file. GDF is an extension of EDF with improved features including better event support, more data types, and subject information.
A PhysioExperiment object.
## Not run: pe <- readGDF("recording.gdf") pe <- readGDF("recording.gdf", channels = c("Fz", "Cz", "Pz")) ## End(Not run)## Not run: pe <- readGDF("recording.gdf") pe <- readGDF("recording.gdf", channels = c("Fz", "Cz", "Pz")) ## End(Not run)
Functions for reading and writing MATLAB .mat files. Requires the R.matlab package. Read PhysioExperiment from MATLAB .mat file
readMAT( path, data_var = NULL, sr_var = NULL, channel_var = NULL, event_var = NULL, transpose = FALSE )readMAT( path, data_var = NULL, sr_var = NULL, channel_var = NULL, event_var = NULL, transpose = FALSE )
path |
Path to the .mat file. |
data_var |
Name of the variable containing signal data. If NULL, attempts to auto-detect. |
sr_var |
Name of the variable containing sampling rate. |
channel_var |
Name of the variable containing channel labels. |
event_var |
Name of the variable containing events. |
transpose |
Logical. If TRUE, transposes the data matrix. |
Reads physiological signal data from a MATLAB .mat file. Supports both standard .mat files and EEGLAB .set structures.
The function attempts to auto-detect the data structure if variable names are not specified. It looks for common variable names used in EEG toolboxes:
data, EEG.data, signal, X for signal data
srate, fs, Fs, samplingRate for sampling rate
chanlocs, channels, labels for channel information
event, events, EEG.event for events
A PhysioExperiment object.
## Not run: # Read MATLAB file with auto-detection pe <- readMAT("eeg_data.mat") # Specify variable names pe <- readMAT("data.mat", data_var = "signal", sr_var = "fs") # Read EEGLAB format pe <- readMAT("EEG.set", data_var = "EEG") ## End(Not run)## Not run: # Read MATLAB file with auto-detection pe <- readMAT("eeg_data.mat") # Specify variable names pe <- readMAT("data.mat", data_var = "signal", sr_var = "fs") # Read EEGLAB format pe <- readMAT("EEG.set", data_var = "EEG") ## End(Not run)
Reads a PhysioExperiment object from HDF5 format. By default, returns DelayedArray-backed assays for out-of-memory processing.
readPhysioHDF5(path, as_delayed = TRUE)readPhysioHDF5(path, as_delayed = TRUE)
path |
Path to the HDF5 file. |
as_delayed |
Logical. If TRUE (default), returns DelayedArray-backed assays. If FALSE, loads data into memory. |
A PhysioExperiment object.
## Not run: # Read HDF5 file with DelayedArray backend (out-of-memory) pe <- readPhysioHDF5("data.h5") isHDF5Backed(pe) # TRUE # Read HDF5 file into memory pe_mem <- readPhysioHDF5("data.h5", as_delayed = FALSE) isHDF5Backed(pe_mem) # FALSE ## End(Not run)## Not run: # Read HDF5 file with DelayedArray backend (out-of-memory) pe <- readPhysioHDF5("data.h5") isHDF5Backed(pe) # TRUE # Read HDF5 file into memory pe_mem <- readPhysioHDF5("data.h5", as_delayed = FALSE) isHDF5Backed(pe_mem) # FALSE ## End(Not run)
Loads HDF5-backed assays into memory as regular arrays.
realizeHDF5(x, assays = NULL)realizeHDF5(x, assays = NULL)
x |
A PhysioExperiment object. |
assays |
Optional character vector of assay names to realize. If NULL, realizes all assays. |
A PhysioExperiment object with in-memory assays.
## Not run: # Load HDF5-backed data pe <- readPhysioHDF5("data.h5") # Realize all assays to memory pe_mem <- realizeHDF5(pe) # Realize only specific assays pe_partial <- realizeHDF5(pe, assays = c("raw", "filtered")) ## End(Not run)## Not run: # Load HDF5-backed data pe <- readPhysioHDF5("data.h5") # Realize all assays to memory pe_mem <- realizeHDF5(pe) # Realize only specific assays pe_partial <- realizeHDF5(pe, assays = c("raw", "filtered")) ## End(Not run)
Stores experiment metadata and optionally signal data in the database.
registerExperiment( con, x, experiment_id = NULL, subject_id = NULL, session_id = NULL, task = NULL, store_signals = FALSE, chunk_size = 10000L )registerExperiment( con, x, experiment_id = NULL, subject_id = NULL, session_id = NULL, task = NULL, store_signals = FALSE, chunk_size = 10000L )
con |
A DuckDB connection. |
x |
A PhysioExperiment object. |
experiment_id |
Unique identifier for the experiment. |
subject_id |
Subject identifier. |
session_id |
Session identifier. |
task |
Task name. |
store_signals |
If TRUE, stores signal data in chunks. |
chunk_size |
Number of samples per chunk for signal storage. |
The experiment_id.
## Not run: con <- connectDatabase() initPhysioSchema(con) # Create sample data pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(10000), nrow = 1000, ncol = 10)), samplingRate = 256 ) # Register experiment (metadata only) exp_id <- registerExperiment(con, pe, subject_id = "sub01", task = "rest" ) # Register with signal data exp_id <- registerExperiment(con, pe, subject_id = "sub02", task = "oddball", store_signals = TRUE ) disconnectDatabase(con) ## End(Not run)## Not run: con <- connectDatabase() initPhysioSchema(con) # Create sample data pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(10000), nrow = 1000, ncol = 10)), samplingRate = 256 ) # Register experiment (metadata only) exp_id <- registerExperiment(con, pe, subject_id = "sub01", task = "rest" ) # Register with signal data exp_id <- registerExperiment(con, pe, subject_id = "sub02", task = "oddball", store_signals = TRUE ) disconnectDatabase(con) ## End(Not run)
Identifies and optionally removes epochs with artifacts.
rejectBadEpochs( x, threshold = 100, method = c("amplitude", "gradient", "variance"), remove = TRUE )rejectBadEpochs( x, threshold = 100, method = c("amplitude", "gradient", "variance"), remove = TRUE )
x |
An epoched PhysioExperiment object. |
threshold |
Amplitude threshold for rejection. |
method |
Detection method: "amplitude", "gradient", or "variance". |
remove |
If TRUE, removes bad epochs. If FALSE, returns indices only. |
If remove=TRUE, modified object. If remove=FALSE, indices of bad epochs.
Remove events from a PhysioExperiment object
removeEvents(x, type = NULL, indices = NULL)removeEvents(x, type = NULL, indices = NULL)
x |
A PhysioExperiment object. |
type |
Optional event types to remove. If NULL, removes all events. |
indices |
Optional integer indices of events to remove. |
The modified PhysioExperiment object.
Rename channels
renameChannels(x, old_names, new_names)renameChannels(x, old_names, new_names)
x |
A PhysioExperiment object. |
old_names |
Character vector of current names. |
new_names |
Character vector of new names. |
Modified PhysioExperiment object.
pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), colData = S4Vectors::DataFrame(label = c("Fz", "Cz", "Pz", "Oz")), samplingRate = 100 ) # Rename channels pe <- renameChannels(pe, c("Fz", "Cz"), c("F3", "C3")) channelNames(pe)pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), colData = S4Vectors::DataFrame(label = c("Fz", "Cz", "Pz", "Oz")), samplingRate = 100 ) # Rename channels pe <- renameChannels(pe, c("Fz", "Cz"), c("F3", "C3")) channelNames(pe)
Creates a new assay with NA values handled according to the specified method.
replaceNA( x, method = "interpolate", input_assay = NULL, output_assay = "na_handled" )replaceNA( x, method = "interpolate", input_assay = NULL, output_assay = "na_handled" )
x |
A PhysioExperiment object. |
method |
Method for handling NA (see handleNA). |
input_assay |
Input assay name. If NULL, uses default assay. |
output_assay |
Output assay name. Default is "na_handled". |
Modified PhysioExperiment with new assay.
pe <- PhysioExperiment( assays = list(raw = matrix(c(1, NA, 3, NA, 5, 6), nrow = 3)), samplingRate = 100 ) # Interpolate NA values pe <- replaceNA(pe, method = "interpolate")pe <- PhysioExperiment( assays = list(raw = matrix(c(1, NA, 3, NA, 5, 6), nrow = 3)), samplingRate = 100 ) # Interpolate NA values pe <- replaceNA(pe, method = "interpolate")
Functions for changing the reference electrode in EEG recordings. Re-referencing is a common preprocessing step that affects the spatial distribution of the signal. Re-reference EEG data
rereference( x, ref_type = c("average", "channel", "channels", "REST"), ref_channels = NULL, exclude = NULL, input_assay = NULL, output_assay = "rereferenced", keep_ref = TRUE )rereference( x, ref_type = c("average", "channel", "channels", "REST"), ref_channels = NULL, exclude = NULL, input_assay = NULL, output_assay = "rereferenced", keep_ref = TRUE )
x |
A PhysioExperiment object. |
ref_type |
Type of re-referencing: "average" (common average reference), "channel" (single channel), "channels" (average of specified channels), or "REST" (Reference Electrode Standardization Technique). |
ref_channels |
For "channel" or "channels" type, the channel name(s) or index/indices to use as reference. |
exclude |
Channels to exclude from average reference calculation (e.g., non-EEG channels like EOG, EMG). |
input_assay |
Input assay name. If NULL, uses default assay. |
output_assay |
Output assay name. Default is "rereferenced". |
keep_ref |
Logical. If TRUE, keeps the original reference channel(s) in the output (zeroed). If FALSE, removes them. |
Changes the reference electrode for EEG recordings. Supports common re-referencing schemes including average reference, linked mastoids, and single electrode reference.
Re-referencing transforms the data by subtracting a reference signal from each channel. The choice of reference affects the spatial distribution and interpretation of the signal.
Average reference ("average"): Subtracts the mean of all channels at each time point. This is commonly used for high-density EEG and provides a reference-independent measure, but requires good spatial sampling.
Single channel reference ("channel"): Subtracts the signal from a specified electrode. Common choices include Cz, linked mastoids (A1+A2)/2, or nose reference.
Multi-channel reference ("channels"): Subtracts the average of multiple specified channels. Useful for linked mastoids or other custom references.
A PhysioExperiment object with re-referenced data.
# Create example EEG data set.seed(123) pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1000), nrow = 100, ncol = 10)), rowData = S4Vectors::DataFrame( label = c("Fp1", "Fp2", "F3", "F4", "C3", "C4", "P3", "P4", "O1", "O2"), type = rep("EEG", 10) ), samplingRate = 256 ) # Apply average reference pe_avg <- rereference(pe, ref_type = "average") # Re-reference to a single channel (Cz) pe_cz <- rereference(pe, ref_type = "channel", ref_channels = "C3") # Re-reference to linked mastoids (if available) # pe_linked <- rereference(pe, ref_type = "channels", # ref_channels = c("M1", "M2"))# Create example EEG data set.seed(123) pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1000), nrow = 100, ncol = 10)), rowData = S4Vectors::DataFrame( label = c("Fp1", "Fp2", "F3", "F4", "C3", "C4", "P3", "P4", "O1", "O2"), type = rep("EEG", 10) ), samplingRate = 256 ) # Apply average reference pe_avg <- rereference(pe, ref_type = "average") # Re-reference to a single channel (Cz) pe_cz <- rereference(pe, ref_type = "channel", ref_channels = "C3") # Re-reference to linked mastoids (if available) # pe_linked <- rereference(pe, ref_type = "channels", # ref_channels = c("M1", "M2"))
Functions for resampling signal data to different sampling rates. Resample signal data
resample( x, target_rate, method = c("linear", "spline", "fft"), assay_name = NULL, output_assay = "resampled" )resample( x, target_rate, method = c("linear", "spline", "fft"), assay_name = NULL, output_assay = "resampled" )
x |
A PhysioExperiment object. |
target_rate |
Target sampling rate in Hz. |
method |
Resampling method: "linear" (default), "spline", or "fft". |
assay_name |
Optional assay name. If NULL, uses the default assay. |
output_assay |
Name for the output assay. Default is "resampled". |
Resamples the signal data to a target sampling rate using interpolation.
A new PhysioExperiment object with resampled data.
Resolve an EventQuery to get filtered events
resolveQuery(q)resolveQuery(q)
q |
An EventQuery object |
Data frame of filtered events
Convert sample indices to times
samplesToTime(x, samples)samplesToTime(x, samples)
x |
A PhysioExperiment object. |
samples |
Integer vector of sample indices. |
Numeric vector of times in seconds.
These helper functions expose common slots and derived quantities for
PhysioExperiment objects.
Get or set sampling rate
samplingRate(x)samplingRate(x)
x |
A PhysioExperiment object. |
value |
Numeric scalar for the new sampling rate in Hz. |
The sampling rate in Hz.
# Create example data pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(100), nrow = 10)), samplingRate = 250 ) # Get sampling rate samplingRate(pe) # Set sampling rate samplingRate(pe) <- 500 samplingRate(pe)# Create example data pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(100), nrow = 10)), samplingRate = 250 ) # Get sampling rate samplingRate(pe) # Set sampling rate samplingRate(pe) <- 500 samplingRate(pe)
Set sampling rate for a specific assay
setAssaySamplingRate(x, assay_name, rate)setAssaySamplingRate(x, assay_name, rate)
x |
A PhysioExperiment object. |
assay_name |
Name of the assay. |
rate |
Sampling rate for the assay. |
Modified PhysioExperiment object.
Assigns types (EEG, EMG, EOG, etc.) to channels.
setChannelTypes(x, types)setChannelTypes(x, types)
x |
A PhysioExperiment object. |
types |
Named character vector or list mapping channel names/indices to types. If unnamed, applies types in order. |
Modified PhysioExperiment object.
pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), colData = S4Vectors::DataFrame(label = c("Fz", "EOG1", "EMG1", "Oz")), samplingRate = 100 ) # Set all channels to same type pe <- setChannelTypes(pe, "EEG") # Set specific channel types by name pe <- setChannelTypes(pe, c(EOG1 = "EOG", EMG1 = "EMG"))pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), colData = S4Vectors::DataFrame(label = c("Fz", "EOG1", "EMG1", "Oz")), samplingRate = 100 ) # Set all channels to same type pe <- setChannelTypes(pe, "EEG") # Set specific channel types by name pe <- setChannelTypes(pe, c(EOG1 = "EOG", EMG1 = "EMG"))
Assigns physical units to channels.
setChannelUnits(x, units)setChannelUnits(x, units)
x |
A PhysioExperiment object. |
units |
Character vector or named list of units. |
Modified PhysioExperiment object.
pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), samplingRate = 100 ) # Set all channels to same unit pe <- setChannelUnits(pe, "uV")pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), samplingRate = 100 ) # Set all channels to same unit pe <- setChannelUnits(pe, "uV")
Assigns 3D electrode positions to channels.
setElectrodePositions(x, positions)setElectrodePositions(x, positions)
x |
A PhysioExperiment object. |
positions |
A data.frame or matrix with columns x, y, z and rows matching channels. Row names should match channel names. |
Modified PhysioExperiment object.
pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(300), nrow = 100, ncol = 3)), colData = S4Vectors::DataFrame(label = c("Fz", "Cz", "Pz")), samplingRate = 100 ) # Set electrode positions positions <- data.frame( x = c(0, 0, 0), y = c(0.71, 0, -0.71), z = c(0.71, 1, 0.71) ) pe <- setElectrodePositions(pe, positions)pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(300), nrow = 100, ncol = 3)), colData = S4Vectors::DataFrame(label = c("Fz", "Cz", "Pz")), samplingRate = 100 ) # Set electrode positions positions <- data.frame( x = c(0, 0, 0), y = c(0.71, 0, -0.71), z = c(0.71, 1, 0.71) ) pe <- setElectrodePositions(pe, positions)
Set events for a PhysioExperiment object
setEvents(x, events)setEvents(x, events)
x |
A PhysioExperiment object. |
events |
A PhysioEvents object or a data.frame with columns: onset, duration, type, value. |
The modified PhysioExperiment object.
pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1000), nrow = 100)), samplingRate = 100 ) # Set events using PhysioEvents object events <- PhysioEvents(onset = c(1, 2, 3), type = "stimulus") pe <- setEvents(pe, events) # Set events using data.frame pe <- setEvents(pe, data.frame(onset = c(1, 2), type = "response"))pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1000), nrow = 100)), samplingRate = 100 ) # Set events using PhysioEvents object events <- PhysioEvents(onset = c(1, 2, 3), type = "stimulus") pe <- setEvents(pe, events) # Set events using data.frame pe <- setEvents(pe, data.frame(onset = c(1, 2), type = "response"))
Records the reference electrode used for the recording.
setReference(x, reference)setReference(x, reference)
x |
A PhysioExperiment object. |
reference |
Character string naming the reference electrode. |
Modified PhysioExperiment object.
pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), samplingRate = 100 ) # Set reference electrode pe <- setReference(pe, "average") getReference(pe) # "average"pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), samplingRate = 100 ) # Set reference electrode pe <- setReference(pe, "average") getReference(pe) # "average"
Show method for PhysioEvents
## S4 method for signature 'PhysioEvents' show(object)## S4 method for signature 'PhysioEvents' show(object)
object |
A PhysioEvents object. |
Displays a summary of the PhysioExperiment object.
## S4 method for signature 'PhysioExperiment' show(object)## S4 method for signature 'PhysioExperiment' show(object)
object |
A PhysioExperiment object. |
pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), colData = S4Vectors::DataFrame(label = c("Fz", "Cz", "Pz", "Oz")), samplingRate = 100 ) pe # Displays summarype <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), colData = S4Vectors::DataFrame(label = c("Fz", "Cz", "Pz", "Oz")), samplingRate = 100 ) pe # Displays summary
Computes connectivity matrices over sliding time windows.
slidingWindowConnectivity( x, window_size = 256L, step = 64L, method = c("correlation", "coherence", "plv"), ... )slidingWindowConnectivity( x, window_size = 256L, step = 64L, method = c("correlation", "coherence", "plv"), ... )
x |
A PhysioExperiment object. |
window_size |
Window size in samples. |
step |
Step size in samples. |
method |
Connectivity method: "correlation", "coherence", or "plv". |
... |
Additional arguments passed to connectivity function. |
A list with time-varying connectivity matrices.
set.seed(123) pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1000 * 4), nrow = 1000, ncol = 4)), samplingRate = 100 ) dyn_conn <- slidingWindowConnectivity(pe, window_size = 200, step = 50)set.seed(123) pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1000 * 4), nrow = 1000, ncol = 4)), samplingRate = 100 ) dyn_conn <- slidingWindowConnectivity(pe, window_size = 200, step = 50)
Calculates the small-world coefficient (sigma) of a network.
smallWorldness(adjacency, n_rand = 100, n_cores = NULL)smallWorldness(adjacency, n_rand = 100, n_cores = NULL)
adjacency |
An adjacency matrix. |
n_rand |
Number of random networks for comparison. |
n_cores |
Number of cores for parallel processing. Default NULL uses sequential processing. |
A list with small-worldness metrics.
# Create a small-world-like network set.seed(123) n <- 20 adj <- matrix(0, n, n) for (i in 1:n) { adj[i, ((i) %% n) + 1] <- 1 adj[i, ((i + 1) %% n) + 1] <- 1 } adj <- adj + t(adj) adj[adj > 0] <- 1 # Add some random long-range connections adj[sample(which(adj == 0 & row(adj) < col(adj)), 5)] <- 1 adj <- adj + t(adj) adj[adj > 0] <- 1 diag(adj) <- 0 sw <- smallWorldness(adj, n_rand = 10)# Create a small-world-like network set.seed(123) n <- 20 adj <- matrix(0, n, n) for (i in 1:n) { adj[i, ((i) %% n) + 1] <- 1 adj[i, ((i + 1) %% n) + 1] <- 1 } adj <- adj + t(adj) adj[adj > 0] <- 1 # Add some random long-range connections adj[sample(which(adj == 0 & row(adj) < col(adj)), 5)] <- 1 adj <- adj + t(adj) adj[adj > 0] <- 1 diag(adj) <- 0 sw <- smallWorldness(adj, n_rand = 10)
Performs spectral clustering on the network.
spectralClustering(adjacency, n_clusters = 2, normalized = TRUE)spectralClustering(adjacency, n_clusters = 2, normalized = TRUE)
adjacency |
An adjacency matrix. |
n_clusters |
Number of clusters. |
normalized |
If TRUE, uses normalized Laplacian. |
A list with cluster assignments and spectral embedding.
# Create block-structured network adj <- matrix(0, 6, 6) adj[1:3, 1:3] <- 1 adj[4:6, 4:6] <- 1 adj[3, 4] <- adj[4, 3] <- 0.5 diag(adj) <- 0 clusters <- spectralClustering(adj, n_clusters = 2)# Create block-structured network adj <- matrix(0, 6, 6) adj[1:3, 1:3] <- 1 adj[4:6, 4:6] <- 1 adj[3, 4] <- adj[4, 3] <- 0.5 diag(adj) <- 0 clusters <- spectralClustering(adj, n_clusters = 2)
Computes eigenvalues and eigenvectors of the graph Laplacian.
spectralDecomposition(adjacency, normalized = TRUE, n_components = NULL)spectralDecomposition(adjacency, normalized = TRUE, n_components = NULL)
adjacency |
An adjacency matrix. |
normalized |
If TRUE, uses normalized Laplacian. |
n_components |
Number of components to return. If NULL, returns all. |
A list with eigenvalues and eigenvectors.
adj <- matrix(c(0, 1, 1, 1, 0, 1, 1, 1, 0), 3, 3) spec <- spectralDecomposition(adj)adj <- matrix(c(0, 1, 1, 1, 0, 1, 1, 1, 0), 3, 3) spec <- spectralDecomposition(adj)
Functions for time-frequency analysis including wavelet transforms, spectrograms, and band power extraction. Compute spectrogram (Short-Time Fourier Transform)
spectrogram( x, window_size = 256L, overlap = 0.5, window_type = c("hanning", "hamming", "blackman", "rectangular"), channel = 1L, sample = 1L )spectrogram( x, window_size = 256L, overlap = 0.5, window_type = c("hanning", "hamming", "blackman", "rectangular"), channel = 1L, sample = 1L )
x |
A PhysioExperiment object. |
window_size |
Window size in samples. |
overlap |
Overlap between windows (0-1). |
window_type |
Window function: "hanning", "hamming", "blackman", or "rectangular". |
channel |
Channel index to analyze. |
sample |
Sample index (for 3D data). |
Computes the spectrogram using STFT.
A list containing:
power: Power spectrogram matrix (frequency x time)
frequencies: Frequency vector
times: Time vector
# Create example data pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1000 * 4), nrow = 1000)), samplingRate = 250 ) # Compute spectrogram for channel 1 spec <- spectrogram(pe, channel = 1) # Plot spectrogram plotSpectrogram(spec, freq_range = c(1, 40))# Create example data pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1000 * 4), nrow = 1000)), samplingRate = 250 ) # Compute spectrogram for channel 1 spec <- spectrogram(pe, channel = 1) # Plot spectrogram plotSpectrogram(spec, freq_range = c(1, 40))
Performs SPM F-test for comparing multiple groups.
spmAnova(x, groups, alpha = 0.05)spmAnova(x, groups, alpha = 0.05)
x |
A PhysioExperiment object or matrix (time x observations). |
groups |
Factor or list indicating group membership. |
alpha |
Significance level. |
A list of class "spm_result" containing F-statistics and clusters.
# Three-group comparison set.seed(123) g1 <- matrix(rnorm(100 * 8), nrow = 100) g2 <- matrix(rnorm(100 * 8), nrow = 100) + 0.5 g3 <- matrix(rnorm(100 * 8), nrow = 100) + 1.0 data <- cbind(g1, g2, g3) groups <- factor(rep(c("A", "B", "C"), each = 8)) pe <- PhysioExperiment(assays = list(values = data), samplingRate = 100) result <- spmAnova(pe, groups = groups)# Three-group comparison set.seed(123) g1 <- matrix(rnorm(100 * 8), nrow = 100) g2 <- matrix(rnorm(100 * 8), nrow = 100) + 0.5 g3 <- matrix(rnorm(100 * 8), nrow = 100) + 1.0 data <- cbind(g1, g2, g3) groups <- factor(rep(c("A", "B", "C"), each = 8)) pe <- PhysioExperiment(assays = list(values = data), samplingRate = 100) result <- spmAnova(pe, groups = groups)
Performs SPM analysis for paired/repeated measures data.
spmPairedTTest(x, condition1, condition2, alpha = 0.05, two_tailed = TRUE)spmPairedTTest(x, condition1, condition2, alpha = 0.05, two_tailed = TRUE)
x |
A PhysioExperiment object or matrix (time x observations). |
condition1 |
Indices for first condition. |
condition2 |
Indices for second condition. |
alpha |
Significance level. |
two_tailed |
Logical; if TRUE, performs two-tailed test. |
A list of class "spm_result".
# Pre-post intervention comparison set.seed(123) pre <- matrix(rnorm(100 * 15), nrow = 100) post <- pre + 0.8 # Effect across all time points post[30:50, ] <- post[30:50, ] + 0.5 # Additional effect data <- cbind(pre, post) pe <- PhysioExperiment(assays = list(values = data), samplingRate = 100) result <- spmPairedTTest(pe, condition1 = 1:15, condition2 = 16:30)# Pre-post intervention comparison set.seed(123) pre <- matrix(rnorm(100 * 15), nrow = 100) post <- pre + 0.8 # Effect across all time points post[30:50, ] <- post[30:50, ] + 0.5 # Additional effect data <- cbind(pre, post) pe <- PhysioExperiment(assays = list(values = data), samplingRate = 100) result <- spmPairedTTest(pe, condition1 = 1:15, condition2 = 16:30)
Functions for statistical analysis of continuous waveform data using Statistical Parametric Mapping (SPM) methodology adapted from neuroimaging. These methods test hypotheses over entire waveforms rather than discrete points. SPM t-test for waveform comparison
spmTTest(x, group1 = NULL, group2 = NULL, alpha = 0.05, two_tailed = TRUE)spmTTest(x, group1 = NULL, group2 = NULL, alpha = 0.05, two_tailed = TRUE)
x |
A PhysioExperiment object or matrix (time x observations). |
group1 |
Indices for first group (for two-sample test). |
group2 |
Indices for second group. If NULL, performs one-sample test. |
alpha |
Significance level (default: 0.05). |
two_tailed |
Logical; if TRUE, performs two-tailed test. |
Performs a t-test at each time point and computes SPMt statistic with Random Field Theory (RFT) correction for multiple comparisons.
SPM analyzes continuous biomechanical waveforms (e.g., joint angles, moments) by computing t-statistics at each time point and using Random Field Theory to control family-wise error rate across the entire waveform.
A list of class "spm_result" containing:
t |
T-statistic at each time point |
threshold |
Critical threshold from RFT |
clusters |
Significant clusters (start, end, extent, p-value) |
p_values |
Pointwise p-values |
alpha |
Significance level used |
Pataky TC (2012). One-dimensional statistical parametric mapping in Python. Computer Methods in Biomechanics and Biomedical Engineering.
# Create example gait data (100 time points x 20 subjects) set.seed(123) # Group 1: normal gait g1 <- matrix(rnorm(100 * 10), nrow = 100, ncol = 10) # Group 2: altered gait (effect at 40-60% of cycle) g2 <- matrix(rnorm(100 * 10), nrow = 100, ncol = 10) g2[40:60, ] <- g2[40:60, ] + 1.5 data <- cbind(g1, g2) pe <- PhysioExperiment( assays = list(values = data), samplingRate = 100 ) # Two-sample SPM t-test result <- spmTTest(pe, group1 = 1:10, group2 = 11:20) print(result)# Create example gait data (100 time points x 20 subjects) set.seed(123) # Group 1: normal gait g1 <- matrix(rnorm(100 * 10), nrow = 100, ncol = 10) # Group 2: altered gait (effect at 40-60% of cycle) g2 <- matrix(rnorm(100 * 10), nrow = 100, ncol = 10) g2[40:60, ] <- g2[40:60, ] + 1.5 data <- cbind(g1, g2) pe <- PhysioExperiment( assays = list(values = data), samplingRate = 100 ) # Two-sample SPM t-test result <- spmTTest(pe, group1 = 1:10, group2 = 11:20) print(result)
Starts the API server in the background, allowing R to remain interactive. This is useful for development and testing.
startAPIServer(port = 8000L, host = "127.0.0.1", quiet = FALSE)startAPIServer(port = 8000L, host = "127.0.0.1", quiet = FALSE)
port |
Integer. Port number for the API server. |
host |
Character. Host address to bind to. |
quiet |
Logical. Suppress startup messages. |
A plumber background process handle that can be used to stop
the server with $kill().
Computes summary statistics for each channel.
## S4 method for signature 'PhysioExperiment' summary(object, ...)## S4 method for signature 'PhysioExperiment' summary(object, ...)
object |
A PhysioExperiment object. |
... |
Additional arguments (not used). |
A data.frame with summary statistics.
pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), colData = S4Vectors::DataFrame(label = c("Fz", "Cz", "Pz", "Oz")), samplingRate = 100 ) summary(pe)pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), colData = S4Vectors::DataFrame(label = c("Fz", "Cz", "Pz", "Oz")), samplingRate = 100 ) summary(pe)
Calculates how stable the network topology is over time.
temporalStability(dyn_conn, metric = c("correlation", "distance"))temporalStability(dyn_conn, metric = c("correlation", "distance"))
dyn_conn |
Result from slidingWindowConnectivity(). |
metric |
Stability metric: "correlation" or "distance". |
A list with stability metrics.
set.seed(123) pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1000 * 4), nrow = 1000, ncol = 4)), samplingRate = 100 ) dyn_conn <- slidingWindowConnectivity(pe, window_size = 200, step = 50) stability <- temporalStability(dyn_conn)set.seed(123) pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1000 * 4), nrow = 1000, ncol = 4)), samplingRate = 100 ) dyn_conn <- slidingWindowConnectivity(pe, window_size = 200, step = 50) stability <- temporalStability(dyn_conn)
Thresholds a connectivity matrix to achieve a target network density.
thresholdNetwork(connectivity, density = 0.2, absolute = TRUE)thresholdNetwork(connectivity, density = 0.2, absolute = TRUE)
connectivity |
A connectivity matrix. |
density |
Target density (proportion of edges to keep, 0-1). |
absolute |
If TRUE, uses absolute values for ranking. |
A thresholded adjacency matrix.
set.seed(123) pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(500 * 4), nrow = 500, ncol = 4)), samplingRate = 100 ) conn <- correlationMatrix(pe) # Keep top 30% of connections adj <- thresholdNetwork(conn$correlation, density = 0.3)set.seed(123) pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(500 * 4), nrow = 500, ncol = 4)), samplingRate = 100 ) conn <- correlationMatrix(pe) # Keep top 30% of connections adj <- thresholdNetwork(conn$correlation, density = 0.3)
Computes a time vector for the default assay using the object's sampling rate.
timeIndex(x)timeIndex(x)
x |
A |
Numeric vector of time points in seconds.
Convert event times to sample indices
timeToSamples(x, times)timeToSamples(x, times)
x |
A PhysioExperiment object. |
times |
Numeric vector of times in seconds. |
Integer vector of sample indices.
Functions for statistical analysis of physiological signal data, including t-tests, ANOVA, cluster-based permutation tests, and effect sizes. Pointwise t-test across epochs
tTestEpochs( x, condition1 = NULL, condition2 = NULL, mu = 0, paired = FALSE, alternative = c("two.sided", "less", "greater"), var.equal = FALSE )tTestEpochs( x, condition1 = NULL, condition2 = NULL, mu = 0, paired = FALSE, alternative = c("two.sided", "less", "greater"), var.equal = FALSE )
x |
An epoched PhysioExperiment object (4D data). |
condition1 |
Indices or logical vector for first condition epochs. |
condition2 |
Indices or logical vector for second condition epochs. If NULL, performs one-sample t-test against mu. |
mu |
Value to test against for one-sample t-test (default: 0). |
paired |
Logical; if TRUE, performs paired t-test. |
alternative |
Alternative hypothesis: "two.sided", "less", or "greater". |
var.equal |
Logical; if TRUE, assumes equal variances. |
Performs t-tests at each time point and channel, comparing epochs against a baseline or between two conditions.
A list containing:
t_values |
Matrix of t-statistics (time x channel) |
p_values |
Matrix of p-values (time x channel) |
df |
Degrees of freedom |
n1, n2
|
Sample sizes for each condition |
# Create example epoched data set.seed(123) epochs <- array(rnorm(100 * 4 * 20 * 1), dim = c(100, 4, 20, 1)) pe <- PhysioExperiment( assays = list(epoched = epochs), samplingRate = 100 ) # One-sample t-test against zero result <- tTestEpochs(pe) # Two-sample t-test comparing conditions result2 <- tTestEpochs(pe, condition1 = 1:10, condition2 = 11:20)# Create example epoched data set.seed(123) epochs <- array(rnorm(100 * 4 * 20 * 1), dim = c(100, 4, 20, 1)) pe <- PhysioExperiment( assays = list(epoched = epochs), samplingRate = 100 ) # One-sample t-test against zero result <- tTestEpochs(pe) # Two-sample t-test comparing conditions result2 <- tTestEpochs(pe, condition1 = 1:10, condition2 = 11:20)
Performs basic validation of BIDS compliance.
validateBIDS(bids_root)validateBIDS(bids_root)
bids_root |
Path to the BIDS dataset root. |
A list with validation results.
## Not run: # Validate a BIDS dataset result <- validateBIDS("path/to/bids") if (result$valid) { message("Dataset is BIDS-compliant") } else { message("Validation errors: ", paste(result$errors, collapse = ", ")) } ## End(Not run)## Not run: # Validate a BIDS dataset result <- validateBIDS("path/to/bids") if (result$valid) { message("Dataset is BIDS-compliant") } else { message("Validation errors: ", paste(result$errors, collapse = ", ")) } ## End(Not run)
Computes the continuous wavelet transform using Morlet wavelets.
waveletTransform( x, frequencies = seq(1, 40, by = 1), n_cycles = 7, channel = 1L, sample = 1L )waveletTransform( x, frequencies = seq(1, 40, by = 1), n_cycles = 7, channel = 1L, sample = 1L )
x |
A PhysioExperiment object. |
frequencies |
Numeric vector of frequencies to analyze. |
n_cycles |
Number of wavelet cycles (can be scalar or vector). |
channel |
Channel index to analyze. |
sample |
Sample index (for 3D data). |
A list containing:
power: Power matrix (frequency x time)
phase: Phase matrix (frequency x time)
frequencies: Frequency vector
times: Time vector
pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(500 * 4), nrow = 500)), samplingRate = 100 ) # Compute wavelet transform (1-30 Hz) wt <- waveletTransform(pe, frequencies = seq(1, 30), channel = 1) # Access power and phase dim(wt$power) # frequency x timepe <- PhysioExperiment( assays = list(raw = matrix(rnorm(500 * 4), nrow = 500)), samplingRate = 100 ) # Compute wavelet transform (1-30 Hz) wt <- waveletTransform(pe, frequencies = seq(1, 30), channel = 1) # Access power and phase dim(wt$power) # frequency x time
Calculates the weighted Phase Lag Index, which is less sensitive to noise than standard PLI.
wPLI(x, freq_band, channels = NULL, assay_name = NULL)wPLI(x, freq_band, channels = NULL, assay_name = NULL)
x |
A PhysioExperiment object. |
freq_band |
Numeric vector of length 2 specifying frequency band (Hz). |
channels |
Integer vector of channel indices. |
assay_name |
Input assay name. |
wPLI weights the contribution of each phase difference by the magnitude of the imaginary component, reducing the influence of noise sources.
A matrix of wPLI values (channel x channel), values 0-1.
set.seed(123) pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(4000), nrow = 1000, ncol = 4)), samplingRate = 256 ) # Compute wPLI in theta band (4-8 Hz) wpli_matrix <- wPLI(pe, freq_band = c(4, 8))set.seed(123) pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(4000), nrow = 1000, ncol = 4)), samplingRate = 256 ) # Compute wPLI in theta band (4-8 Hz) wpli_matrix <- wPLI(pe, freq_band = c(4, 8))
Writes a single assay to an existing HDF5 file.
writeAssayHDF5(x, path, assay_name, compression_level = 6L)writeAssayHDF5(x, path, assay_name, compression_level = 6L)
x |
A PhysioExperiment object. |
path |
Path to the HDF5 file. |
assay_name |
Name of the assay to write. |
compression_level |
Compression level (0-9). |
Invisible NULL.
## Not run: # Add a new processed assay to an existing HDF5 file pe <- readPhysioHDF5("data.h5") pe <- butterworthFilter(pe, low = 1, high = 30, type = "pass") # Write the filtered assay back to the HDF5 file writeAssayHDF5(pe, "data.h5", "filtered") ## End(Not run)## Not run: # Add a new processed assay to an existing HDF5 file pe <- readPhysioHDF5("data.h5") pe <- butterworthFilter(pe, low = 1, high = 30, type = "pass") # Write the filtered assay back to the HDF5 file writeAssayHDF5(pe, "data.h5", "filtered") ## End(Not run)
Writes a PhysioExperiment object to BDF format (24-bit resolution).
writeBDF(x, path, patient_id = "X", recording_id = "X")writeBDF(x, path, patient_id = "X", recording_id = "X")
x |
A PhysioExperiment object. |
path |
Output file path. |
patient_id |
Patient identification string. |
recording_id |
Recording identification string. |
BDF is a 24-bit extension of EDF providing higher resolution than the standard 16-bit EDF format. It is commonly used with BioSemi acquisition systems but can be used for any high-resolution physiological data.
Invisible NULL.
## Not run: pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(25600), nrow = 2560, ncol = 10)), colData = S4Vectors::DataFrame(label = paste0("Ch", 1:10)), samplingRate = 256 ) writeBDF(pe, "output.bdf") ## End(Not run)## Not run: pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(25600), nrow = 2560, ncol = 10)), colData = S4Vectors::DataFrame(label = paste0("Ch", 1:10)), samplingRate = 256 ) writeBDF(pe, "output.bdf") ## End(Not run)
Writes data in BIDS-compliant directory structure.
writeBIDS( x, bids_root, subject, session = NULL, task, run = NULL, modality = c("eeg", "ieeg"), overwrite = FALSE )writeBIDS( x, bids_root, subject, session = NULL, task, run = NULL, modality = c("eeg", "ieeg"), overwrite = FALSE )
x |
A PhysioExperiment object. |
bids_root |
Path to the BIDS dataset root directory. |
subject |
Subject identifier (without 'sub-' prefix). |
session |
Session identifier (without 'ses-' prefix). Optional. |
task |
Task name. |
run |
Run number. Optional. |
modality |
Data modality: "eeg" or "ieeg". |
overwrite |
If TRUE, overwrites existing files. |
Invisible path to the created files.
## Not run: # Create a PhysioExperiment pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(25600), nrow = 2560, ncol = 10)), rowData = S4Vectors::DataFrame(label = paste0("Ch", 1:10)), samplingRate = 256 ) # Export to BIDS format writeBIDS(pe, "path/to/bids", subject = "01", task = "rest") # With session and run writeBIDS(pe, "path/to/bids", subject = "01", session = "01", task = "oddball", run = 1) ## End(Not run)## Not run: # Create a PhysioExperiment pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(25600), nrow = 2560, ncol = 10)), rowData = S4Vectors::DataFrame(label = paste0("Ch", 1:10)), samplingRate = 256 ) # Export to BIDS format writeBIDS(pe, "path/to/bids", subject = "01", task = "rest") # With session and run writeBIDS(pe, "path/to/bids", subject = "01", session = "01", task = "oddball", run = 1) ## End(Not run)
Saves a PhysioExperiment object to BrainVision format (three files: .vhdr header, .vmrk markers, .eeg binary data).
writeBrainVision( x, path, overwrite = FALSE, binary_format = c("IEEE_FLOAT_32", "INT_16", "INT_32"), assay_name = NULL )writeBrainVision( x, path, overwrite = FALSE, binary_format = c("IEEE_FLOAT_32", "INT_16", "INT_32"), assay_name = NULL )
x |
A PhysioExperiment object. |
path |
Output path (without extension, or with .vhdr extension). |
overwrite |
Logical. If TRUE, overwrites existing files. |
binary_format |
Binary format for data: "IEEE_FLOAT_32" (default), "INT_16", or "INT_32". |
assay_name |
Assay to export. If NULL, uses default assay. |
Invisible NULL.
## Not run: pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1000), nrow = 100, ncol = 10)), colData = S4Vectors::DataFrame(label = paste0("Ch", 1:10)), samplingRate = 256 ) writeBrainVision(pe, "output") ## End(Not run)## Not run: pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1000), nrow = 100, ncol = 10)), colData = S4Vectors::DataFrame(label = paste0("Ch", 1:10)), samplingRate = 256 ) writeBrainVision(pe, "output") ## End(Not run)
Writes physiological signal data to a CSV file.
writeCSV( x, path, format = c("wide", "long"), include_time = TRUE, assay_name = NULL, sep = ",", ... )writeCSV( x, path, format = c("wide", "long"), include_time = TRUE, assay_name = NULL, sep = ",", ... )
x |
A PhysioExperiment object. |
path |
Output file path. |
format |
Output format: "wide" (time x channels) or "long". |
include_time |
Logical. If TRUE, includes a time column. |
assay_name |
Assay to export. If NULL, uses default assay. |
sep |
Column separator. Default is ",". |
... |
Additional arguments passed to write.csv/write.table. |
Invisible path to the created file.
# Create example data pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), rowData = S4Vectors::DataFrame(label = c("Fz", "Cz", "Pz", "Oz")), samplingRate = 100 ) # Write to temporary CSV file tmp <- tempfile(fileext = ".csv") writeCSV(pe, tmp) # Write in long format writeCSV(pe, tmp, format = "long") # Clean up unlink(tmp)# Create example data pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), rowData = S4Vectors::DataFrame(label = c("Fz", "Cz", "Pz", "Oz")), samplingRate = 100 ) # Write to temporary CSV file tmp <- tempfile(fileext = ".csv") writeCSV(pe, tmp) # Write in long format writeCSV(pe, tmp, format = "long") # Clean up unlink(tmp)
Writes a PhysioExperiment object to EDF format.
writeEDF(x, path, patient_id = "X", recording_id = "X")writeEDF(x, path, patient_id = "X", recording_id = "X")
x |
A PhysioExperiment object. |
path |
Output file path. |
patient_id |
Patient identification string. |
recording_id |
Recording identification string. |
Invisible NULL.
## Not run: # Create a PhysioExperiment with EEG-like data pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(25600), nrow = 2560, ncol = 10)), rowData = S4Vectors::DataFrame(label = paste0("Ch", 1:10)), samplingRate = 256 ) # Export to EDF format writeEDF(pe, "output.edf", patient_id = "Subject01", recording_id = "Session1") ## End(Not run)## Not run: # Create a PhysioExperiment with EEG-like data pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(25600), nrow = 2560, ncol = 10)), rowData = S4Vectors::DataFrame(label = paste0("Ch", 1:10)), samplingRate = 256 ) # Export to EDF format writeEDF(pe, "output.edf", patient_id = "Subject01", recording_id = "Session1") ## End(Not run)
Writes electrode positions from a PhysioExperiment to CSV.
writeElectrodePositionsCSV(x, path, sep = ",", ...)writeElectrodePositionsCSV(x, path, sep = ",", ...)
x |
A PhysioExperiment object with electrode positions. |
path |
Output file path. |
sep |
Column separator. |
... |
Additional arguments passed to write.csv. |
Invisible path to the created file.
pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), rowData = S4Vectors::DataFrame(label = c("Fz", "Cz", "Pz", "Oz")), samplingRate = 100 ) pe <- applyMontage(pe, "10-20") # Write electrode positions tmp <- tempfile(fileext = ".csv") writeElectrodePositionsCSV(pe, tmp) # Clean up unlink(tmp)pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), rowData = S4Vectors::DataFrame(label = c("Fz", "Cz", "Pz", "Oz")), samplingRate = 100 ) pe <- applyMontage(pe, "10-20") # Write electrode positions tmp <- tempfile(fileext = ".csv") writeElectrodePositionsCSV(pe, tmp) # Clean up unlink(tmp)
Writes PhysioEvents to a CSV file.
writeEventsCSV(events, path, sep = ",", ...)writeEventsCSV(events, path, sep = ",", ...)
events |
A PhysioEvents object. |
path |
Output file path. |
sep |
Column separator. |
... |
Additional arguments passed to write.csv. |
Invisible path to the created file.
# Create events events <- PhysioEvents( onset = c(1.0, 2.5, 4.0), duration = c(0.5, 0.5, 0.5), type = c("stimulus", "stimulus", "response"), value = c("A", "B", "correct") ) # Write to temporary file tmp <- tempfile(fileext = ".csv") writeEventsCSV(events, tmp) # Clean up unlink(tmp)# Create events events <- PhysioEvents( onset = c(1.0, 2.5, 4.0), duration = c(0.5, 0.5, 0.5), type = c("stimulus", "stimulus", "response"), value = c("A", "B", "correct") ) # Write to temporary file tmp <- tempfile(fileext = ".csv") writeEventsCSV(events, tmp) # Clean up unlink(tmp)
Saves a PhysioExperiment object to GDF (General Data Format) version 2.x.
writeGDF( x, path, patient_id = "", recording_id = "", overwrite = FALSE, assay_name = NULL )writeGDF( x, path, patient_id = "", recording_id = "", overwrite = FALSE, assay_name = NULL )
x |
A PhysioExperiment object. |
path |
Output file path. |
patient_id |
Patient identifier string. |
recording_id |
Recording identifier string. |
overwrite |
Logical. If TRUE, overwrites existing file. |
assay_name |
Assay to export. If NULL, uses default assay. |
Invisible NULL.
## Not run: pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1000), nrow = 100, ncol = 10)), colData = S4Vectors::DataFrame(label = paste0("Ch", 1:10)), samplingRate = 256 ) writeGDF(pe, "output.gdf") ## End(Not run)## Not run: pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1000), nrow = 100, ncol = 10)), colData = S4Vectors::DataFrame(label = paste0("Ch", 1:10)), samplingRate = 256 ) writeGDF(pe, "output.gdf") ## End(Not run)
Saves a PhysioExperiment object to MATLAB .mat format.
writeMAT( x, path, data_var = "data", include_metadata = TRUE, eeglab = FALSE, assay_name = NULL )writeMAT( x, path, data_var = "data", include_metadata = TRUE, eeglab = FALSE, assay_name = NULL )
x |
A PhysioExperiment object. |
path |
Output file path. |
data_var |
Name for the data variable in the .mat file. |
include_metadata |
Logical. If TRUE, includes metadata variables. |
eeglab |
Logical. If TRUE, exports in EEGLAB-compatible structure. |
assay_name |
Assay to export. If NULL, uses default assay. |
Invisible NULL.
## Not run: pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1000), nrow = 100, ncol = 10)), rowData = S4Vectors::DataFrame(label = paste0("Ch", 1:10)), samplingRate = 256 ) # Write to .mat file writeMAT(pe, "output.mat") # Custom variable name writeMAT(pe, "output.mat", data_var = "EEG_data") # EEGLAB-compatible format writeMAT(pe, "output.mat", eeglab = TRUE) ## End(Not run)## Not run: pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1000), nrow = 100, ncol = 10)), rowData = S4Vectors::DataFrame(label = paste0("Ch", 1:10)), samplingRate = 256 ) # Write to .mat file writeMAT(pe, "output.mat") # Custom variable name writeMAT(pe, "output.mat", data_var = "EEG_data") # EEGLAB-compatible format writeMAT(pe, "output.mat", eeglab = TRUE) ## End(Not run)
These helper functions provide a lightweight interface to serialise and
deserialise PhysioExperiment objects to RDS files. They act as placeholders
for richer IO backends that can be developed later.
writePhysio(x, path) readPhysio(path)writePhysio(x, path) readPhysio(path)
x |
A |
path |
Path to an |
readPhysio() returns a PhysioExperiment instance; writePhysio()
returns the input object invisibly.
# Create a PhysioExperiment object pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1000), nrow = 100, ncol = 10)), samplingRate = 256 ) # Write to a temporary file tmp <- tempfile(fileext = ".rds") writePhysio(pe, tmp) # Read it back pe_loaded <- readPhysio(tmp) samplingRate(pe_loaded) # Clean up unlink(tmp)# Create a PhysioExperiment object pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1000), nrow = 100, ncol = 10)), samplingRate = 256 ) # Write to a temporary file tmp <- tempfile(fileext = ".rds") writePhysio(pe, tmp) # Read it back pe_loaded <- readPhysio(tmp) samplingRate(pe_loaded) # Clean up unlink(tmp)
Functions for reading and writing PhysioExperiment objects to HDF5 format, supporting out-of-memory operations for large datasets. Write PhysioExperiment to HDF5
writePhysioHDF5( x, path, overwrite = FALSE, chunk_dims = NULL, compression_level = 6L )writePhysioHDF5( x, path, overwrite = FALSE, chunk_dims = NULL, compression_level = 6L )
x |
A PhysioExperiment object. |
path |
Path to the output HDF5 file. |
overwrite |
Logical. If TRUE, overwrites existing file. |
chunk_dims |
Optional chunk dimensions for HDF5 storage. |
compression_level |
Compression level (0-9). Default is 6. |
Saves a PhysioExperiment object to HDF5 format, enabling out-of-memory access for large datasets.
Invisible NULL.
## Not run: # Create a large PhysioExperiment pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1e6), nrow = 1e5, ncol = 10)), samplingRate = 1000 ) # Save to HDF5 with compression writePhysioHDF5(pe, "data.h5", compression_level = 6) # Overwrite existing file writePhysioHDF5(pe, "data.h5", overwrite = TRUE) ## End(Not run)## Not run: # Create a large PhysioExperiment pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1e6), nrow = 1e5, ncol = 10)), samplingRate = 1000 ) # Save to HDF5 with compression writePhysioHDF5(pe, "data.h5", compression_level = 6) # Overwrite existing file writePhysioHDF5(pe, "data.h5", overwrite = TRUE) ## End(Not run)