| Title: | Input and Output Functions for 'PhysioExperiment' Objects |
|---|---|
| Description: | Provides input and output capabilities for 'SummarizedExperiment'-derived physiological signal containers. Supported formats include 'EDF' and 'EDF+', 'BDF', 'GDF', 'BrainVision', 'HDF5', 'BIDS', comma-separated values, and 'MATLAB' files, together with 'DuckDB' database integration. Out-of-memory processing of large datasets is available through delayed 'HDF5' arrays. |
| Authors: | Yusuke Matsui [aut, cre] |
| Maintainer: | Yusuke Matsui <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.2.10 |
| Built: | 2026-10-03 13:42:24 UTC |
| Source: | https://github.com/x-biosignal/PhysioIO |
Combines a main recording and a _physio recording into a
MultiPhysioExperiment, using the physio's StartTime as its
clock offset. The two keep their own sampling rates.
attachBIDSPhysio(main, physio)attachBIDSPhysio(main, physio)
main |
A |
physio |
A |
Detects transitions of the low-16-bit trigger value to a new non-zero code
and returns them as a PhysioEvents: each rising transition is an event
whose onset is the transition time (seconds) and whose value is the trigger
code.
bdfTriggerEvents(status, sampling_rate)bdfTriggerEvents(status, sampling_rate)
status |
Integer vector of raw Status-channel digital values (as from
|
sampling_rate |
Sampling rate of the Status channel in Hz. |
A PhysioEvents object.
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.
Raasveldt M, Muehleisen H (2019). "DuckDB: an embeddable analytical database." Proceedings of the 2019 International Conference on Management of Data (SIGMOD). doi:10.1145/3299869.3320212
initPhysioSchema, registerExperiment,
queryExperiments
# DuckDB is an optional dependency; guard the example so it only runs # when the package is installed. if (requireNamespace("duckdb", quietly = TRUE)) { tf <- tempfile(fileext = ".duckdb") con <- connectDatabase(tf) # Always disconnect when done disconnectDatabase(con) unlink(tf) }# DuckDB is an optional dependency; guard the example so it only runs # when the package is installed. if (requireNamespace("duckdb", quietly = TRUE)) { tf <- tempfile(fileext = ".duckdb") con <- connectDatabase(tf) # Always disconnect when done disconnectDatabase(con) unlink(tf) }
Get database statistics
dbStats(con)dbStats(con)
con |
A DuckDB connection. |
A list with database statistics.
Raasveldt M, Muehleisen H (2019). "DuckDB: an embeddable analytical database." Proceedings of the 2019 International Conference on Management of Data (SIGMOD). doi:10.1145/3299869.3320212
connectDatabase, initPhysioSchema,
queryExperiments
# DuckDB is an optional dependency; guard the example so it only runs # when the package is installed. if (requireNamespace("duckdb", quietly = TRUE)) { tf <- tempfile(fileext = ".duckdb") con <- connectDatabase(tf) initPhysioSchema(con) stats <- dbStats(con) stats$n_experiments disconnectDatabase(con) unlink(tf) }# DuckDB is an optional dependency; guard the example so it only runs # when the package is installed. if (requireNamespace("duckdb", quietly = TRUE)) { tf <- tempfile(fileext = ".duckdb") con <- connectDatabase(tf) initPhysioSchema(con) stats <- dbStats(con) stats$n_experiments disconnectDatabase(con) unlink(tf) }
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.
Raasveldt M, Muehleisen H (2019). "DuckDB: an embeddable analytical database." Proceedings of the 2019 International Conference on Management of Data (SIGMOD). doi:10.1145/3299869.3320212
registerExperiment, loadExperiment,
queryExperiments
# DuckDB is an optional dependency; guard the example so it only runs # when the package is installed. if (requireNamespace("duckdb", quietly = TRUE)) { tf <- tempfile(fileext = ".duckdb") con <- connectDatabase(tf) initPhysioSchema(con) pe <- PhysioExperiment( assays = list(raw = matrix(0, nrow = 100, ncol = 3)), colData = S4Vectors::DataFrame(label = c("Fp1", "Fp2", "Cz")), samplingRate = 256 ) registerExperiment(con, pe, experiment_id = "demo1", subject_id = "sub01") # Remove the experiment and all related records deleteExperiment(con, "demo1") disconnectDatabase(con) unlink(tf) }# DuckDB is an optional dependency; guard the example so it only runs # when the package is installed. if (requireNamespace("duckdb", quietly = TRUE)) { tf <- tempfile(fileext = ".duckdb") con <- connectDatabase(tf) initPhysioSchema(con) pe <- PhysioExperiment( assays = list(raw = matrix(0, nrow = 100, ncol = 3)), colData = S4Vectors::DataFrame(label = c("Fp1", "Fp2", "Cz")), samplingRate = 256 ) registerExperiment(con, pe, experiment_id = "demo1", subject_id = "sub01") # Remove the experiment and all related records deleteExperiment(con, "demo1") disconnectDatabase(con) unlink(tf) }
Convenience dispatcher: routes a figshare, Zenodo or Mendeley Data DOI (or
the bare doi.org URL) to downloadFigshare(), downloadZenodo() or
downloadMendeley(). A figshare collection DOI is rejected with a pointer
to figshareCollectionArticles().
downloadFromDOI(doi, dest = ".", ...)downloadFromDOI(doi, dest = ".", ...)
doi |
A DOI such as |
dest |
Destination directory (created if needed). Default |
... |
Passed to the underlying downloader (e.g. |
The download-info data frame from the underlying function, invisibly.
downloadFigshare(), downloadZenodo(), downloadMendeley(),
figshareCollectionArticles()
## Not run: downloadFromDOI("10.5281/zenodo.3374790", dest = tempdir()) ## End(Not run)## Not run: downloadFromDOI("10.5281/zenodo.3374790", dest = tempdir()) ## End(Not run)
Downloads the files of a Mendeley Data dataset into dest, verifying each
against the SHA-256 hash Mendeley reports.
downloadMendeley( dataset_id, dest = ".", files = NULL, version = NULL, access_token = Sys.getenv("MENDELEY_TOKEN", ""), verify_hash = TRUE, overwrite = FALSE, quiet = TRUE, folder_id = "root", api_url = "https://data.mendeley.com/public-api" )downloadMendeley( dataset_id, dest = ".", files = NULL, version = NULL, access_token = Sys.getenv("MENDELEY_TOKEN", ""), verify_hash = TRUE, overwrite = FALSE, quiet = TRUE, folder_id = "root", api_url = "https://data.mendeley.com/public-api" )
dataset_id |
Mendeley dataset id (or a full DOI/URL). |
dest |
Destination directory (created if needed). Default |
files |
Optional character vector of file names; restricts the download
to those files (default |
version |
Optional integer dataset version; |
access_token |
Mendeley OAuth bearer token; defaults to the
|
verify_hash |
Logical; if |
overwrite |
Logical; re-download files already present in |
quiet |
Logical; suppress the per-file download progress (default
|
folder_id |
Folder to download from (default |
api_url |
Mendeley Data public API base URL. |
Unlike figshare and Zenodo, Mendeley Data exposes dataset and file
metadata publicly (see mendeleyDatasetFiles()) but requires an OAuth
access token to download the file bytes. Supply the token via
access_token or the MENDELEY_TOKEN environment variable; obtain one
through the Mendeley Data API (an OAuth2 application). Without a token this
function errors early and points you at mendeleyDatasetFiles() for the
public manifest.
The dataset_id is the Mendeley Data identifier – the alphanumeric part of
a Mendeley DOI 10.17632/<id>.<version> or a
data.mendeley.com/datasets/<id>/<version> URL.
A data frame (one row per file) with columns name, path, size,
checksum, algo ("sha256") and checksum_ok, invisibly.
mendeleyDatasetFiles(), downloadFigshare(), downloadZenodo(),
downloadFromDOI()
## Not run: # metadata is public: mendeleyDatasetFiles("mzpz22x58x") # bytes need a token: downloadMendeley("mzpz22x58x", dest = tempdir(), access_token = Sys.getenv("MENDELEY_TOKEN")) ## End(Not run)## Not run: # metadata is public: mendeleyDatasetFiles("mzpz22x58x") # bytes need a token: downloadMendeley("mzpz22x58x", dest = tempdir(), access_token = Sys.getenv("MENDELEY_TOKEN")) ## End(Not run)
Downloads the .hea, .dat and (optionally) annotation files of a
record from a PhysioNet database into dest.
downloadPhysioNet( record, database, dest = ".", annotator = "atr", base_url = "https://physionet.org/files" )downloadPhysioNet( record, database, dest = ".", annotator = "atr", base_url = "https://physionet.org/files" )
record |
Record name (e.g. |
database |
PhysioNet database slug (e.g. |
dest |
Destination directory (created if needed). |
annotator |
Optional annotation extension(s) to fetch (e.g.
|
base_url |
PhysioNet base URL. |
The paths of the downloaded files, invisibly.
Downloads the files of a public Zenodo record into dest via the Zenodo
public REST API, optionally verifying each file against the MD5 checksum
Zenodo reports. No authentication is used, so only open/public records are
reachable. Both the legacy file-array response and the newer InvenioRDM
files.entries response are handled.
downloadZenodo( record_id, dest = ".", files = NULL, verify_md5 = TRUE, overwrite = FALSE, quiet = TRUE, api_url = "https://zenodo.org/api" )downloadZenodo( record_id, dest = ".", files = NULL, verify_md5 = TRUE, overwrite = FALSE, quiet = TRUE, api_url = "https://zenodo.org/api" )
record_id |
Zenodo record ID (numeric or character). |
dest |
Destination directory (created if needed). Default |
files |
Optional character vector of file names; restricts the download
to those files (default |
verify_md5 |
Logical; if |
overwrite |
Logical; re-download files already present in |
quiet |
Logical; suppress the per-file download progress (default
|
api_url |
Zenodo REST API base URL. |
The record_id is the numeric identifier of a Zenodo record – the trailing
number of a Zenodo DOI or URL (e.g. 3374790 in 10.5281/zenodo.3374790).
Note that a Zenodo concept DOI resolves to the latest version; pass a
specific version's record ID to pin a version.
A data frame (one row per file) with columns name, path, size,
checksum, algo ("md5") and checksum_ok (TRUE/FALSE, or NA
when no checksum was available), invisibly.
downloadFigshare(), downloadMendeley(), downloadFromDOI(),
downloadPhysioNet()
## Not run: info <- downloadZenodo(3374790, dest = tempdir()) info$path ## End(Not run)## Not run: info <- downloadZenodo(3374790, dest = tempdir()) info$path ## End(Not run)
Inverse of toMNE(): reads the signal matrix, channel names/types, sampling
rate, electrode montage and annotations from an MNE Raw object into a
PhysioExperiment. The import is recorded in the object's provenance.
fromMNE(raw)fromMNE(raw)
raw |
An MNE |
A PhysioExperiment with the signal in the "raw" assay.
if (hasMNE()) { pe <- PhysioExperiment( assays = S4Vectors::SimpleList(raw = matrix(rnorm(300), 100, 3)), colData = S4Vectors::DataFrame(label = c("Fp1", "Fp2", "Cz"), type = rep("eeg", 3)), samplingRate = 100) pe2 <- fromMNE(toMNE(pe)) }if (hasMNE()) { pe <- PhysioExperiment( assays = S4Vectors::SimpleList(raw = matrix(rnorm(300), 100, 3)), colData = S4Vectors::DataFrame(label = c("Fp1", "Fp2", "Cz"), type = rep("eeg", 3)), samplingRate = 100) pe2 <- fromMNE(toMNE(pe)) }
Is the Python mne module available?
hasMNE()hasMNE()
TRUE if reticulate and the Python mne module are
both available, otherwise FALSE.
pyMNEVersion(), toMNE(), fromMNE()
hasMNE()hasMNE()
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.
Raasveldt M, Muehleisen H (2019). "DuckDB: an embeddable analytical database." Proceedings of the 2019 International Conference on Management of Data (SIGMOD). doi:10.1145/3299869.3320212
connectDatabase, registerExperiment,
dbStats
# DuckDB is an optional dependency; guard the example so it only runs # when the package is installed. if (requireNamespace("duckdb", quietly = TRUE)) { tf <- tempfile(fileext = ".duckdb") con <- connectDatabase(tf) initPhysioSchema(con) # Freshly created schema has no experiments yet dbStats(con)$n_experiments disconnectDatabase(con) unlink(tf) }# DuckDB is an optional dependency; guard the example so it only runs # when the package is installed. if (requireNamespace("duckdb", quietly = TRUE)) { tf <- tempfile(fileext = ".duckdb") con <- connectDatabase(tf) initPhysioSchema(con) # Freshly created schema has no experiments yet dbStats(con)$n_experiments disconnectDatabase(con) unlink(tf) }
Tests whether the default assay of a PhysioExperiment is stored as an HDF5-backed DelayedArray.
isHDF5Backed(x)isHDF5Backed(x)
x |
A PhysioExperiment object. |
Logical scalar; TRUE if the default assay inherits from
HDF5Array or DelayedArray, FALSE otherwise.
The HDF Group (1997-2024). "Hierarchical Data Format, version 5." https://www.hdfgroup.org/HDF5/
readPhysioHDF5, writePhysioHDF5,
realizeHDF5
# 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
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).
Gorgolewski KJ, et al. (2016). "The brain imaging data structure, a format for organizing and describing outputs of neuroimaging experiments." Scientific Data, 3, 160044. doi:10.1038/sdata.2016.44
listBIDSSubjects, readBIDS,
validateBIDS
# Write a BIDS dataset with a session, then list sessions for the subject pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), colData = S4Vectors::DataFrame(label = c("Fz", "Cz", "Pz", "Oz")), samplingRate = 100 ) bids_root <- file.path(tempdir(), "bids-session-demo") writeBIDS(pe, bids_root, subject = "01", session = "baseline", task = "rest") listBIDSSessions(bids_root, subject = "01") unlink(bids_root, recursive = TRUE)# Write a BIDS dataset with a session, then list sessions for the subject pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), colData = S4Vectors::DataFrame(label = c("Fz", "Cz", "Pz", "Oz")), samplingRate = 100 ) bids_root <- file.path(tempdir(), "bids-session-demo") writeBIDS(pe, bids_root, subject = "01", session = "baseline", task = "rest") listBIDSSessions(bids_root, subject = "01") unlink(bids_root, recursive = TRUE)
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).
Gorgolewski KJ, et al. (2016). "The brain imaging data structure, a format for organizing and describing outputs of neuroimaging experiments." Scientific Data, 3, 160044. doi:10.1038/sdata.2016.44
listBIDSSessions, readBIDS,
validateBIDS
# Write a minimal BIDS dataset, then list its subjects pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), colData = S4Vectors::DataFrame(label = c("Fz", "Cz", "Pz", "Oz")), samplingRate = 100 ) bids_root <- file.path(tempdir(), "bids-list-demo") writeBIDS(pe, bids_root, subject = "01", task = "rest") listBIDSSubjects(bids_root) unlink(bids_root, recursive = TRUE)# Write a minimal BIDS dataset, then list its subjects pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), colData = S4Vectors::DataFrame(label = c("Fz", "Cz", "Pz", "Oz")), samplingRate = 100 ) bids_root <- file.path(tempdir(), "bids-list-demo") writeBIDS(pe, bids_root, subject = "01", task = "rest") listBIDSSubjects(bids_root) unlink(bids_root, recursive = TRUE)
List the records in a WFDB RECORDS file
listWFDBRecords(path)listWFDBRecords(path)
path |
Path (or URL) to a PhysioNet |
Character vector of record names.
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.
Raasveldt M, Muehleisen H (2019). "DuckDB: an embeddable analytical database." Proceedings of the 2019 International Conference on Management of Data (SIGMOD). doi:10.1145/3299869.3320212
registerExperiment, queryExperiments,
deleteExperiment
# DuckDB is an optional dependency; guard the example so it only runs # when the package is installed. if (requireNamespace("duckdb", quietly = TRUE)) { tf <- tempfile(fileext = ".duckdb") con <- connectDatabase(tf) initPhysioSchema(con) pe <- PhysioExperiment( assays = list(raw = matrix(0, nrow = 100, ncol = 3)), colData = S4Vectors::DataFrame(label = c("Fp1", "Fp2", "Cz")), samplingRate = 256 ) registerExperiment(con, pe, experiment_id = "demo1", subject_id = "sub01", task = "rest", store_signals = TRUE) # Reconstruct the object, with signal data pe2 <- loadExperiment(con, "demo1", load_signals = TRUE) disconnectDatabase(con) unlink(tf) }# DuckDB is an optional dependency; guard the example so it only runs # when the package is installed. if (requireNamespace("duckdb", quietly = TRUE)) { tf <- tempfile(fileext = ".duckdb") con <- connectDatabase(tf) initPhysioSchema(con) pe <- PhysioExperiment( assays = list(raw = matrix(0, nrow = 100, ncol = 3)), colData = S4Vectors::DataFrame(label = c("Fp1", "Fp2", "Cz")), samplingRate = 256 ) registerExperiment(con, pe, experiment_id = "demo1", subject_id = "sub01", task = "rest", store_signals = TRUE) # Reconstruct the object, with signal data pe2 <- loadExperiment(con, "demo1", load_signals = TRUE) disconnectDatabase(con) unlink(tf) }
Harmonize clinical codes across sites
mapClinicalCodes( x, mapping, code_col = "scale_name", mapped_col = "scale_name_std", from_col = "from", to_col = "to", unmatched = c("keep", "na", "drop") )mapClinicalCodes( x, mapping, code_col = "scale_name", mapped_col = "scale_name_std", from_col = "from", to_col = "to", unmatched = c("keep", "na", "drop") )
x |
Clinical metadata data frame. |
mapping |
Code mapping, either:
|
code_col |
Source code column in |
mapped_col |
Output mapped code column. |
from_col |
Source column in mapping data.frame. |
to_col |
Target column in mapping data.frame. |
unmatched |
Behavior for unmatched codes: |
Data frame with mapped_col appended.
Goldberger AL, et al. (2000). "PhysioBank, PhysioToolkit, and PhysioNet: components of a new research resource for complex physiologic signals." Circulation, 101(23), e215-e220. doi:10.1161/01.CIR.101.23.e215
readClinicalMetadataCSV,
validateClinicalMetadata
df <- data.frame(scale_name = c("fim_total", "Berg"), stringsAsFactors = FALSE) map <- c(fim_total = "FIM", Berg = "BBS") mapClinicalCodes(df, map, code_col = "scale_name")df <- data.frame(scale_name = c("fim_total", "Berg"), stringsAsFactors = FALSE) map <- c(fim_total = "FIM", Berg = "BBS") mapClinicalCodes(df, map, code_col = "scale_name")
Returns the public file manifest of a Mendeley Data dataset – file names,
sizes, SHA-256 hashes and content ids – via the Mendeley Data public REST
API. This metadata is available without authentication; downloading the
file bytes, however, requires an OAuth token (see downloadMendeley()).
mendeleyDatasetFiles( dataset_id, version = NULL, folder_id = "root", api_url = "https://data.mendeley.com/public-api" )mendeleyDatasetFiles( dataset_id, version = NULL, folder_id = "root", api_url = "https://data.mendeley.com/public-api" )
dataset_id |
Mendeley dataset id (or a full DOI/URL). |
version |
Optional integer dataset version; |
folder_id |
Folder to list (default |
api_url |
Mendeley Data public API base URL. |
The dataset_id is the Mendeley Data dataset identifier – the alphanumeric
component of a Mendeley DOI 10.17632/<id>.<version> or a
data.mendeley.com/datasets/<id>/<version> URL (both are tolerated).
A data frame with columns name, size, sha256, content_id and
version, one row per file.
downloadMendeley(), downloadFromDOI()
## Not run: files <- mendeleyDatasetFiles("mzpz22x58x") # latest version files[, c("name", "size", "sha256")] ## End(Not run)## Not run: files <- mendeleyDatasetFiles("mzpz22x58x") # latest version files[, c("name", "size", "sha256")] ## End(Not run)
Version of the available Python mne module
pyMNEVersion()pyMNEVersion()
The mne.__version__ string, or NA_character_ when
mne is not available.
pyMNEVersion()pyMNEVersion()
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.
Raasveldt M, Muehleisen H (2019). "DuckDB: an embeddable analytical database." Proceedings of the 2019 International Conference on Management of Data (SIGMOD). doi:10.1145/3299869.3320212
registerExperiment, loadExperiment,
dbStats
# DuckDB is an optional dependency; guard the example so it only runs # when the package is installed. if (requireNamespace("duckdb", quietly = TRUE)) { tf <- tempfile(fileext = ".duckdb") con <- connectDatabase(tf) initPhysioSchema(con) pe <- PhysioExperiment( assays = list(raw = matrix(0, nrow = 100, ncol = 3)), colData = S4Vectors::DataFrame(label = c("Fp1", "Fp2", "Cz")), samplingRate = 256 ) registerExperiment(con, pe, experiment_id = "demo1", subject_id = "sub01", task = "rest") # Query all experiments, or filter by subject / task all_exps <- queryExperiments(con) sub01_exps <- queryExperiments(con, subject_id = "sub01") disconnectDatabase(con) unlink(tf) }# DuckDB is an optional dependency; guard the example so it only runs # when the package is installed. if (requireNamespace("duckdb", quietly = TRUE)) { tf <- tempfile(fileext = ".duckdb") con <- connectDatabase(tf) initPhysioSchema(con) pe <- PhysioExperiment( assays = list(raw = matrix(0, nrow = 100, ncol = 3)), colData = S4Vectors::DataFrame(label = c("Fp1", "Fp2", "Cz")), samplingRate = 256 ) registerExperiment(con, pe, experiment_id = "demo1", subject_id = "sub01", task = "rest") # Query all experiments, or filter by subject / task all_exps <- queryExperiments(con) sub01_exps <- queryExperiments(con, subject_id = "sub01") disconnectDatabase(con) unlink(tf) }
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, resample = FALSE, status = TRUE )readBDF( path, channels = NULL, start_time = NULL, end_time = NULL, resample = FALSE, status = TRUE )
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. Note
that BDF subsetting is record-granular: |
end_time |
Optional end time in seconds for reading a subset. |
resample |
Logical. If |
status |
Logical. If |
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, or a
MultiPhysioExperiment when native rates differ
and resample = FALSE.
# Round-trip a small recording through a temporary BDF file pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), colData = S4Vectors::DataFrame(label = c("A1", "A2", "B1", "B2")), samplingRate = 100 ) tmp <- tempfile(fileext = ".bdf") writeBDF(pe, tmp) # Read the file back pe_in <- readBDF(tmp) # Read only specific channels pe_sub <- readBDF(tmp, channels = c("A1", "B1")) unlink(tmp)# Round-trip a small recording through a temporary BDF file pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), colData = S4Vectors::DataFrame(label = c("A1", "A2", "B1", "B2")), samplingRate = 100 ) tmp <- tempfile(fileext = ".bdf") writeBDF(pe, tmp) # Read the file back pe_in <- readBDF(tmp) # Read only specific channels pe_sub <- readBDF(tmp, channels = c("A1", "B1")) unlink(tmp)
Returns the raw digital values of the "Status" channel. The low 16
bits of each value are the stimulus trigger inputs.
readBDFStatus(path)readBDFStatus(path)
path |
Path to a BDF file. |
A list with values (integer status words) and fs (the
Status channel sampling rate), or NULL if the file has no Status
channel.
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.
Gorgolewski KJ, et al. (2016). "The brain imaging data structure, a format for organizing and describing outputs of neuroimaging experiments." Scientific Data, 3, 160044. doi:10.1038/sdata.2016.44
writeBIDS, validateBIDS,
readEDF, listBIDSSubjects
# Write a minimal BIDS dataset to a temporary directory, then read it back pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), colData = S4Vectors::DataFrame(label = c("Fz", "Cz", "Pz", "Oz")), samplingRate = 100 ) bids_root <- file.path(tempdir(), "bids-demo") writeBIDS(pe, bids_root, subject = "01", task = "rest") # Read EEG data back from the BIDS dataset pe_in <- readBIDS(bids_root, subject = "01", task = "rest") dim(SummarizedExperiment::assay(pe_in, "raw")) unlink(bids_root, recursive = TRUE)# Write a minimal BIDS dataset to a temporary directory, then read it back pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), colData = S4Vectors::DataFrame(label = c("Fz", "Cz", "Pz", "Oz")), samplingRate = 100 ) bids_root <- file.path(tempdir(), "bids-demo") writeBIDS(pe, bids_root, subject = "01", task = "rest") # Read EEG data back from the BIDS dataset pe_in <- readBIDS(bids_root, subject = "01", task = "rest") dim(SummarizedExperiment::assay(pe_in, "raw")) unlink(bids_root, recursive = TRUE)
Read the derivative recordings of a subject
readBIDSDerivatives(deriv_root, subject, session = NULL)readBIDSDerivatives(deriv_root, subject, session = NULL)
deriv_root |
Derivative dataset root. |
subject |
Subject label. |
session |
Optional session label. |
A named list of PhysioExperiment objects, one per
desc-<label> derivative found for the subject.
Read a Motion-BIDS recording
readBIDSMotion( bids_root, subject, task, session = NULL, run = NULL, tracking_system = NULL )readBIDSMotion( bids_root, subject, task, session = NULL, run = NULL, tracking_system = NULL )
bids_root |
BIDS dataset root. |
subject, task
|
Subject and task labels. |
session, run
|
Optional session label and run number. |
tracking_system |
Optional tracking-system label to disambiguate. |
A PhysioExperiment with the motion data, colData
carrying tracked_point/component/units, and the sampling rate.
Read a BIDS continuous physiological recording
readBIDSPhysio(path)readBIDSPhysio(path)
path |
Path to the |
A PhysioExperiment with the physio signals; StartTime
is stored in metadata()$bids_start_time.
writeBIDSPhysio, attachBIDSPhysio
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.
# Round-trip a small recording through temporary BrainVision files pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), colData = S4Vectors::DataFrame(label = c("Fz", "Cz", "Pz", "Oz")), samplingRate = 100 ) base <- tempfile() writeBrainVision(pe, base) pe_in <- readBrainVision(paste0(base, ".vhdr")) dim(SummarizedExperiment::assay(pe_in, "raw")) unlink(paste0(base, c(".vhdr", ".vmrk", ".eeg")))# Round-trip a small recording through temporary BrainVision files pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), colData = S4Vectors::DataFrame(label = c("Fz", "Cz", "Pz", "Oz")), samplingRate = 100 ) base <- tempfile() writeBrainVision(pe, base) pe_in <- readBrainVision(paste0(base, ".vhdr")) dim(SummarizedExperiment::assay(pe_in, "raw")) unlink(paste0(base, c(".vhdr", ".vmrk", ".eeg")))
Utilities for loading and validating clinical assessment metadata so
physiological sessions can be linked with EDC/EHR variables using
subject_id and visit_id.
Read clinical metadata from CSV
readClinicalMetadataCSV( path, col_map = NULL, required_cols = c("subject_id", "visit_id", "scale_name", "scale_score"), date_cols = c("assessment_date", "visit_date"), validate = TRUE, sep = ",", header = TRUE, ... )readClinicalMetadataCSV( path, col_map = NULL, required_cols = c("subject_id", "visit_id", "scale_name", "scale_score"), date_cols = c("assessment_date", "visit_date"), validate = TRUE, sep = ",", header = TRUE, ... )
path |
Path to the CSV/TSV file. |
col_map |
Optional named character vector for renaming columns. Names are source columns and values are target column names. |
required_cols |
Required columns for validation. |
date_cols |
Columns to parse as Date ( |
validate |
Logical; run |
sep |
Field separator, default |
header |
Logical, default |
... |
Additional arguments passed to |
Data frame containing standardized clinical metadata.
Goldberger AL, et al. (2000). "PhysioBank, PhysioToolkit, and PhysioNet: components of a new research resource for complex physiologic signals." Circulation, 101(23), e215-e220. doi:10.1161/01.CIR.101.23.e215
validateClinicalMetadata,
mapClinicalCodes, readCSV
tmp <- tempfile(fileext = ".csv") write.csv(data.frame( sid = "S01", vid = "V01", scale_name = "FIM", scale_score = 90, assessment_date = "2026-01-10" ), tmp, row.names = FALSE) df <- readClinicalMetadataCSV( tmp, col_map = c(sid = "subject_id", vid = "visit_id") ) unlink(tmp)tmp <- tempfile(fileext = ".csv") write.csv(data.frame( sid = "S01", vid = "V01", scale_name = "FIM", scale_score = 90, assessment_date = "2026-01-10" ), tmp, row.names = FALSE) df <- readClinicalMetadataCSV( tmp, col_map = c(sid = "subject_id", vid = "visit_id") ) unlink(tmp)
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.
Wickham H (2014). "Tidy Data." Journal of Statistical Software, 59(10), 1-23. doi:10.18637/jss.v059.i10
writeCSV, readEventsCSV,
readEDF, readMAT
# Write a wide-format CSV, then read it back pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), colData = S4Vectors::DataFrame(label = c("Fz", "Cz", "Pz", "Oz")), samplingRate = 100 ) tmp <- tempfile(fileext = ".csv") writeCSV(pe, tmp) # Read using the written time column pe_in <- readCSV(tmp, time_col = "time") # Read without a time column (generate time from sampling rate) pe_sr <- readCSV(tmp, channel_cols = c("Fz", "Cz", "Pz", "Oz"), sampling_rate = 100) unlink(tmp)# Write a wide-format CSV, then read it back pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), colData = S4Vectors::DataFrame(label = c("Fz", "Cz", "Pz", "Oz")), samplingRate = 100 ) tmp <- tempfile(fileext = ".csv") writeCSV(pe, tmp) # Read using the written time column pe_in <- readCSV(tmp, time_col = "time") # Read without a time column (generate time from sampling rate) pe_sr <- readCSV(tmp, channel_cols = c("Fz", "Cz", "Pz", "Oz"), sampling_rate = 100) unlink(tmp)
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, resample = FALSE )readEDF( path, channels = NULL, start_time = NULL, end_time = NULL, resample = FALSE )
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. |
resample |
Logical. If |
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 native sampling rates, the rates are preserved by
returning a MultiPhysioExperiment (one stream per rate); pass
resample = TRUE for the legacy single-rate behaviour.
A PhysioExperiment
with the EDF signal data in the "raw" assay, or - when channels have
differing native rates and resample = FALSE - a
MultiPhysioExperiment. Channel metadata
(label, transducer, physical dimensions, digital/physical min/max) are
stored in colData, and recording metadata in metadata.
Kemp, B., et al. (1992). "A simple format for exchange of digitized polygraphic recordings." Electroencephalography and Clinical Neurophysiology, 82(5), 391-393. doi:10.1016/0013-4694(92)90009-7
writeEDF, readBIDS,
readPhysioHDF5, readCSV
# Round-trip a small recording through a temporary EDF file pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), colData = S4Vectors::DataFrame(label = c("Fp1", "Fp2", "C3", "C4")), samplingRate = 100 ) tmp <- tempfile(fileext = ".edf") writeEDF(pe, tmp) # Read the whole file back pe_in <- readEDF(tmp) dim(SummarizedExperiment::assay(pe_in, "raw")) # Read only specific channels pe_sub <- readEDF(tmp, channels = c("Fp1", "C3")) unlink(tmp)# Round-trip a small recording through a temporary EDF file pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), colData = S4Vectors::DataFrame(label = c("Fp1", "Fp2", "C3", "C4")), samplingRate = 100 ) tmp <- tempfile(fileext = ".edf") writeEDF(pe, tmp) # Read the whole file back pe_in <- readEDF(tmp) dim(SummarizedExperiment::assay(pe_in, "raw")) # Read only specific channels pe_sub <- readEDF(tmp, channels = c("Fp1", "C3")) unlink(tmp)
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.
Wickham H (2014). "Tidy Data." Journal of Statistical Software, 59(10), 1-23. doi:10.18637/jss.v059.i10
writeElectrodePositionsCSV, readCSV,
readBIDS
# Write electrode positions to a temporary CSV, then read them back pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), colData = S4Vectors::DataFrame(label = c("Fz", "Cz", "Pz", "Oz")), samplingRate = 100 ) pe <- applyMontage(pe, "10-20") tmp <- tempfile(fileext = ".csv") writeElectrodePositionsCSV(pe, tmp) positions <- readElectrodePositionsCSV(tmp) unlink(tmp)# Write electrode positions to a temporary CSV, then read them back pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), colData = S4Vectors::DataFrame(label = c("Fz", "Cz", "Pz", "Oz")), samplingRate = 100 ) pe <- applyMontage(pe, "10-20") tmp <- tempfile(fileext = ".csv") writeElectrodePositionsCSV(pe, tmp) positions <- readElectrodePositionsCSV(tmp) unlink(tmp)
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.
Wickham H (2014). "Tidy Data." Journal of Statistical Software, 59(10), 1-23. doi:10.18637/jss.v059.i10
writeEventsCSV, readCSV,
readBIDS
# Write events to a temporary CSV, then read them back 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") ) tmp <- tempfile(fileext = ".csv") writeEventsCSV(events, tmp) events_in <- readEventsCSV(tmp) unlink(tmp)# Write events to a temporary CSV, then read them back 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") ) tmp <- tempfile(fileext = ".csv") writeEventsCSV(events, tmp) events_in <- readEventsCSV(tmp) unlink(tmp)
Reads a raw FIFF file into a PhysioExperiment. The native parser reads
the FIFF tag stream directly (channel info, sampling rate and data buffers).
For files the native path cannot handle, and when the Python mne module
is available through reticulate, it can fall back to
mne.io.read_raw_fif().
readFIF(path, backend = c("auto", "native", "mne"))readFIF(path, backend = c("auto", "native", "mne"))
path |
Path to a |
backend |
One of |
A PhysioExperiment with calibrated signal values in the
"raw" assay, channel labels/types/units in colData, and the
sampling rate set.
FIFF file format (Elekta Neuromag); MNE-Python read_raw_fif.
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.
# Round-trip a small recording through a temporary GDF file pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(300), nrow = 100, ncol = 3)), colData = S4Vectors::DataFrame(label = c("Fz", "Cz", "Pz")), samplingRate = 100 ) tmp <- tempfile(fileext = ".gdf") writeGDF(pe, tmp) pe_in <- readGDF(tmp) pe_sub <- readGDF(tmp, channels = c("Fz", "Cz")) unlink(tmp)# Round-trip a small recording through a temporary GDF file pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(300), nrow = 100, ncol = 3)), colData = S4Vectors::DataFrame(label = c("Fz", "Cz", "Pz")), samplingRate = 100 ) tmp <- tempfile(fileext = ".gdf") writeGDF(pe, tmp) pe_in <- readGDF(tmp) pe_sub <- readGDF(tmp, channels = c("Fz", "Cz")) unlink(tmp)
Reads physiological signal data from a MATLAB .mat file. Supports both standard .mat files and EEGLAB .set structures.
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. |
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.
MathWorks (2024). "MAT-File Format." Technical documentation. https://www.mathworks.com/help/matlab/import_export/mat-file-versions.html
writeMAT, readEDF,
readCSV, readPhysioHDF5
# 'R.matlab' is an optional dependency; guard the round-trip example so it # only runs when the package is installed. if (requireNamespace("R.matlab", quietly = TRUE)) { pe <- PhysioExperiment( assays = list(raw = matrix(0, nrow = 100, ncol = 3)), colData = S4Vectors::DataFrame(label = c("Fp1", "Fp2", "Cz")), samplingRate = 256 ) tf <- tempfile(fileext = ".mat") writeMAT(pe, tf) pe2 <- readMAT(tf) unlink(tf) }# 'R.matlab' is an optional dependency; guard the round-trip example so it # only runs when the package is installed. if (requireNamespace("R.matlab", quietly = TRUE)) { pe <- PhysioExperiment( assays = list(raw = matrix(0, nrow = 100, ncol = 3)), colData = S4Vectors::DataFrame(label = c("Fp1", "Fp2", "Cz")), samplingRate = 256 ) tf <- tempfile(fileext = ".mat") writeMAT(pe, tf) pe2 <- readMAT(tf) unlink(tf) }
Inverse of writeParquet(): reconstructs a PhysioExperiment (or
MultiPhysioExperiment) from a directory written by writeParquet().
readParquet(dir)readParquet(dir)
dir |
A directory written by |
A PhysioExperiment or MultiPhysioExperiment.
if (requireNamespace("arrow", quietly = TRUE)) { pe <- PhysioExperiment( assays = S4Vectors::SimpleList(raw = matrix(rnorm(30), 10, 3)), samplingRate = 256) d <- tempfile("pe-parquet") writeParquet(pe, d) readParquet(d) }if (requireNamespace("arrow", quietly = TRUE)) { pe <- PhysioExperiment( assays = S4Vectors::SimpleList(raw = matrix(rnorm(30), 10, 3)), samplingRate = 256) d <- tempfile("pe-parquet") writeParquet(pe, d) readParquet(d) }
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. When
as_delayed = TRUE, assays are HDF5Array objects enabling
out-of-memory access; when FALSE, assays are standard in-memory
arrays.
The HDF Group (1997-2024). "Hierarchical Data Format, version 5." https://www.hdfgroup.org/HDF5/
writePhysioHDF5, isHDF5Backed,
realizeHDF5, writeAssayHDF5
# Write a small PhysioExperiment to a temporary HDF5 file pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1000), nrow = 100, ncol = 10)), samplingRate = 100 ) tmp <- tempfile(fileext = ".h5") writePhysioHDF5(pe, tmp) # Read it back with the DelayedArray backend (out-of-memory) pe_delayed <- readPhysioHDF5(tmp) isHDF5Backed(pe_delayed) # TRUE # Read it back into memory pe_mem <- readPhysioHDF5(tmp, as_delayed = FALSE) isHDF5Backed(pe_mem) # FALSE unlink(tmp)# Write a small PhysioExperiment to a temporary HDF5 file pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1000), nrow = 100, ncol = 10)), samplingRate = 100 ) tmp <- tempfile(fileext = ".h5") writePhysioHDF5(pe, tmp) # Read it back with the DelayedArray backend (out-of-memory) pe_delayed <- readPhysioHDF5(tmp) isHDF5Backed(pe_delayed) # TRUE # Read it back into memory pe_mem <- readPhysioHDF5(tmp, as_delayed = FALSE) isHDF5Backed(pe_mem) # FALSE unlink(tmp)
Inverse of writeProv. The format is auto-detected from the file
contents (PROV-N text, PROV JSON-LD, or PROV-JSON).
readProv(path)readProv(path)
path |
Path to a PROV document written by |
A provenance data.frame with the same columns as
provenance.
pe <- PhysioExperiment( S4Vectors::SimpleList(raw = matrix(rnorm(20), 10, 2)), samplingRate = 100) pe <- logStep(pe, "import") tf <- tempfile(fileext = ".json") writeProv(pe, tf) readProv(tf)pe <- PhysioExperiment( S4Vectors::SimpleList(raw = matrix(rnorm(20), 10, 2)), samplingRate = 100) pe <- logStep(pe, "import") tf <- tempfile(fileext = ".json") writeProv(pe, tf) readProv(tf)
Reads a WFDB record's header (.hea) and interleaved signal file
(.dat) into a PhysioExperiment. Storage formats 16, 61, 80,
212, 24 and 32 are supported.
readWFDB(record)readWFDB(record)
record |
Path to the record with or without extension (e.g.
|
A PhysioExperiment with physical signal values in the
"raw" assay, channel labels/units/gain in colData, and the
sampling rate set.
Moody, G. B. & Mark, R. G. (2001). The impact of the MIT-BIH Arrhythmia Database. IEEE Eng. Med. Biol., 20(3), 45-50.
Parses a WFDB binary annotation file (MIT format) into a
PhysioEvents: each annotation's sample number becomes the event
onset (in samples), its beat symbol the event type, and any
auxiliary string the event value.
readWFDBAnnotation(path)readWFDBAnnotation(path)
path |
Path to the annotation file (e.g. |
A PhysioEvents object (onset in samples).
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 the specified assays realized as in-memory arrays.
The HDF Group (1997-2024). "Hierarchical Data Format, version 5." https://www.hdfgroup.org/HDF5/
readPhysioHDF5, writePhysioHDF5,
isHDF5Backed
# Write and read back HDF5-backed data pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1000), nrow = 100, ncol = 10)), samplingRate = 100 ) tmp <- tempfile(fileext = ".h5") writePhysioHDF5(pe, tmp) pe_delayed <- readPhysioHDF5(tmp) # Realize all assays to memory pe_mem <- realizeHDF5(pe_delayed) isHDF5Backed(pe_mem) # FALSE unlink(tmp)# Write and read back HDF5-backed data pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1000), nrow = 100, ncol = 10)), samplingRate = 100 ) tmp <- tempfile(fileext = ".h5") writePhysioHDF5(pe, tmp) pe_delayed <- readPhysioHDF5(tmp) # Realize all assays to memory pe_mem <- realizeHDF5(pe_delayed) isHDF5Backed(pe_mem) # FALSE unlink(tmp)
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, parquet_dir = NULL )registerExperiment( con, x, experiment_id = NULL, subject_id = NULL, session_id = NULL, task = NULL, store_signals = FALSE, chunk_size = 10000L, parquet_dir = NULL )
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. |
parquet_dir |
Optional directory for a Parquet backend. When supplied,
the experiment is written with |
The experiment_id.
Raasveldt M, Muehleisen H (2019). "DuckDB: an embeddable analytical database." Proceedings of the 2019 International Conference on Management of Data (SIGMOD). doi:10.1145/3299869.3320212
loadExperiment, queryExperiments,
deleteExperiment, initPhysioSchema
# DuckDB is an optional dependency; guard the example so it only runs # when the package is installed. if (requireNamespace("duckdb", quietly = TRUE)) { tf <- tempfile(fileext = ".duckdb") con <- connectDatabase(tf) initPhysioSchema(con) # Build a small deterministic PhysioExperiment pe <- PhysioExperiment( assays = list(raw = matrix(0, nrow = 100, ncol = 3)), colData = S4Vectors::DataFrame(label = c("Fp1", "Fp2", "Cz")), samplingRate = 256 ) exp_id <- registerExperiment(con, pe, experiment_id = "demo1", subject_id = "sub01", task = "rest") disconnectDatabase(con) unlink(tf) }# DuckDB is an optional dependency; guard the example so it only runs # when the package is installed. if (requireNamespace("duckdb", quietly = TRUE)) { tf <- tempfile(fileext = ".duckdb") con <- connectDatabase(tf) initPhysioSchema(con) # Build a small deterministic PhysioExperiment pe <- PhysioExperiment( assays = list(raw = matrix(0, nrow = 100, ncol = 3)), colData = S4Vectors::DataFrame(label = c("Fp1", "Fp2", "Cz")), samplingRate = 256 ) exp_id <- registerExperiment(con, pe, experiment_id = "demo1", subject_id = "sub01", task = "rest") disconnectDatabase(con) unlink(tf) }
Creates (or replaces) a DuckDB view over an assay Parquet file written by
writeParquet(), using DuckDB's read_parquet() so that aggregates are
computed directly over the file without loading it into R. The view columns
are ch1, ch2, ... (one per channel).
registerParquetAssay(con, dir, view_name = "signals", assay = NULL)registerParquetAssay(con, dir, view_name = "signals", assay = NULL)
con |
A DuckDB connection (from |
dir |
A directory written by |
view_name |
Name of the DuckDB view to create (default |
assay |
Assay to expose; defaults to the manifest's default assay. |
The view_name, invisibly.
writeParquet(), registerExperiment()
Builds an mne.io.RawArray from a PhysioExperiment: channel
names, channel types and sampling rate populate the mne.Info; any
electrode positions (getElectrodePositions()) become a
DigMontage; and any events (getEvents()) become
mne.Annotations. The signal matrix is passed through unchanged, so
fromMNE(toMNE(x)) reproduces it exactly.
toMNE(x, assay = NULL)toMNE(x, assay = NULL)
x |
A |
assay |
Assay to export (default: the object's default assay). |
Channel types not recognised by MNE are mapped to "misc" (and are
lower-cased to MNE's convention). Channel names must be unique. An event's
type and (when present) value are packed into the annotation
description so both survive the round-trip; a missing (NA) value
becomes "" because MNE annotations cannot represent NA. Events
whose onset falls outside the recording are dropped by MNE (with a warning).
An mne.io.RawArray Python object.
Gramfort A, et al. (2013). "MEG and EEG data analysis with MNE-Python." Frontiers in Neuroscience, 7, 267.
if (hasMNE()) { pe <- PhysioExperiment( assays = S4Vectors::SimpleList(raw = matrix(rnorm(300), 100, 3)), colData = S4Vectors::DataFrame(label = c("Fp1", "Fp2", "Cz"), type = rep("eeg", 3)), samplingRate = 100) raw <- toMNE(pe) }if (hasMNE()) { pe <- PhysioExperiment( assays = S4Vectors::SimpleList(raw = matrix(rnorm(300), 100, 3)), colData = S4Vectors::DataFrame(label = c("Fp1", "Fp2", "Cz"), type = rep("eeg", 3)), samplingRate = 100) raw <- toMNE(pe) }
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.
Gorgolewski KJ, et al. (2016). "The brain imaging data structure, a format for organizing and describing outputs of neuroimaging experiments." Scientific Data, 3, 160044. doi:10.1038/sdata.2016.44
readBIDS, writeBIDS,
listBIDSSubjects
# Write a minimal BIDS dataset, then validate it pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), colData = S4Vectors::DataFrame(label = c("Fz", "Cz", "Pz", "Oz")), samplingRate = 100 ) bids_root <- file.path(tempdir(), "bids-validate-demo") writeBIDS(pe, bids_root, subject = "01", task = "rest") result <- validateBIDS(bids_root) result$valid unlink(bids_root, recursive = TRUE)# Write a minimal BIDS dataset, then validate it pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), colData = S4Vectors::DataFrame(label = c("Fz", "Cz", "Pz", "Oz")), samplingRate = 100 ) bids_root <- file.path(tempdir(), "bids-validate-demo") writeBIDS(pe, bids_root, subject = "01", task = "rest") result <- validateBIDS(bids_root) result$valid unlink(bids_root, recursive = TRUE)
Validate clinical metadata
validateClinicalMetadata( x, required_cols = c("subject_id", "visit_id", "scale_name", "scale_score"), allowed_source_system = c("EDC", "EHR", "paper_crf"), allowed_assessor_role = c("PT", "OT", "MD", "RN", "researcher"), strict = FALSE )validateClinicalMetadata( x, required_cols = c("subject_id", "visit_id", "scale_name", "scale_score"), allowed_source_system = c("EDC", "EHR", "paper_crf"), allowed_assessor_role = c("PT", "OT", "MD", "RN", "researcher"), strict = FALSE )
x |
Data frame created from EDC/EHR exports. |
required_cols |
Required columns that must exist and be non-missing. |
allowed_source_system |
Allowed values for |
allowed_assessor_role |
Allowed values for |
strict |
Logical; stop when validation fails. |
A list with validation details and an overall valid flag.
Goldberger AL, et al. (2000). "PhysioBank, PhysioToolkit, and PhysioNet: components of a new research resource for complex physiologic signals." Circulation, 101(23), e215-e220. doi:10.1161/01.CIR.101.23.e215
readClinicalMetadataCSV,
mapClinicalCodes, validateBIDS
df <- data.frame( subject_id = "S01", visit_id = "V01", scale_name = "FIM", scale_score = 88, assessment_date = "2026-01-01", stringsAsFactors = FALSE ) validateClinicalMetadata(df)df <- data.frame( subject_id = "S01", visit_id = "V01", scale_name = "FIM", scale_score = 88, assessment_date = "2026-01-01", stringsAsFactors = FALSE ) validateClinicalMetadata(df)
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 |
Character string naming the assay to write. |
compression_level |
Integer compression level (0-9). |
Invisible NULL. The assay is written to the HDF5 file as a
side effect.
The HDF Group (1997-2024). "Hierarchical Data Format, version 5." https://www.hdfgroup.org/HDF5/
writePhysioHDF5, readPhysioHDF5,
realizeHDF5
# Create a PhysioExperiment and write it to a temporary HDF5 file pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1000), nrow = 100, ncol = 10)), samplingRate = 100 ) tmp <- tempfile(fileext = ".h5") writePhysioHDF5(pe, tmp) # Add a second assay to the object and write only that assay to the file SummarizedExperiment::assay(pe, "scaled") <- SummarizedExperiment::assay(pe, "raw") * 2 writeAssayHDF5(pe, tmp, "scaled") unlink(tmp)# Create a PhysioExperiment and write it to a temporary HDF5 file pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1000), nrow = 100, ncol = 10)), samplingRate = 100 ) tmp <- tempfile(fileext = ".h5") writePhysioHDF5(pe, tmp) # Add a second assay to the object and write only that assay to the file SummarizedExperiment::assay(pe, "scaled") <- SummarizedExperiment::assay(pe, "raw") * 2 writeAssayHDF5(pe, tmp, "scaled") unlink(tmp)
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.
pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1000), nrow = 100, ncol = 10)), colData = S4Vectors::DataFrame(label = paste0("Ch", 1:10)), samplingRate = 100 ) tmp <- tempfile(fileext = ".bdf") writeBDF(pe, tmp) unlink(tmp)pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1000), nrow = 100, ncol = 10)), colData = S4Vectors::DataFrame(label = paste0("Ch", 1:10)), samplingRate = 100 ) tmp <- tempfile(fileext = ".bdf") writeBDF(pe, tmp) unlink(tmp)
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.
Gorgolewski KJ, et al. (2016). "The brain imaging data structure, a format for organizing and describing outputs of neuroimaging experiments." Scientific Data, 3, 160044. doi:10.1038/sdata.2016.44
readBIDS, writeEDF,
listBIDSSubjects, validateBIDS
# Create a PhysioExperiment pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1000), nrow = 100, ncol = 10)), colData = S4Vectors::DataFrame(label = paste0("Ch", 1:10)), samplingRate = 100 ) # Export to a BIDS dataset in a temporary directory bids_root <- file.path(tempdir(), "bids-write-demo") writeBIDS(pe, bids_root, subject = "01", task = "rest") unlink(bids_root, recursive = TRUE)# Create a PhysioExperiment pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1000), nrow = 100, ncol = 10)), colData = S4Vectors::DataFrame(label = paste0("Ch", 1:10)), samplingRate = 100 ) # Export to a BIDS dataset in a temporary directory bids_root <- file.path(tempdir(), "bids-write-demo") writeBIDS(pe, bids_root, subject = "01", task = "rest") unlink(bids_root, recursive = TRUE)
Writes x as a derivative under deriv_root with a
desc-<label> entity, and a derivative dataset_description.json
whose GeneratedBy is populated from the object's provenance
(provenance). The signals are stored as a gzipped
_physio.tsv.gz plus JSON.
writeBIDSDerivative( x, deriv_root, subject, task, desc, session = NULL, run = NULL, pipeline_name = NULL, overwrite = FALSE )writeBIDSDerivative( x, deriv_root, subject, task, desc, session = NULL, run = NULL, pipeline_name = NULL, overwrite = FALSE )
x |
A |
deriv_root |
Derivative dataset root (e.g.
|
subject, task, session, run
|
BIDS entities. |
desc |
The |
pipeline_name |
Name recorded in |
overwrite |
Overwrite existing files (default |
The written data path, invisibly.
Writes a motion-capture PhysioExperiment in the BIDS motion
datatype (Jeung et al. 2023): a headerless _motion.tsv, a
_channels.tsv carrying tracked_point/component, and a
_motion.json sidecar with SamplingFrequency and
TrackingSystemName.
writeBIDSMotion( x, bids_root, subject, task, session = NULL, run = NULL, tracking_system = "unspecified", overwrite = FALSE )writeBIDSMotion( x, bids_root, subject, task, session = NULL, run = NULL, tracking_system = "unspecified", overwrite = FALSE )
x |
A |
bids_root |
BIDS dataset root. |
subject, task
|
Subject label and task label. |
session, run
|
Optional session label and run number. |
tracking_system |
Tracking-system label (the |
overwrite |
Overwrite existing files (default |
The data directory path, invisibly.
Jeung, S., et al. (2023). Motion-BIDS. Scientific Data.
Writes a gzipped _physio.tsv.gz (headerless, columns defined in the
JSON) plus a _physio.json sidecar with SamplingFrequency,
StartTime and Columns.
writeBIDSPhysio( x, bids_root, subject, task, session = NULL, run = NULL, start_time = 0, overwrite = FALSE )writeBIDSPhysio( x, bids_root, subject, task, session = NULL, run = NULL, start_time = 0, overwrite = FALSE )
x |
A |
bids_root, subject, task, session, run
|
BIDS entities. |
start_time |
Recording start time relative to the main recording, in
seconds (BIDS |
overwrite |
Overwrite existing files (default |
The written .tsv.gz path, invisibly.
readBIDSPhysio, attachBIDSPhysio
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.
pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1000), nrow = 100, ncol = 10)), colData = S4Vectors::DataFrame(label = paste0("Ch", 1:10)), samplingRate = 100 ) base <- tempfile() writeBrainVision(pe, base) unlink(paste0(base, c(".vhdr", ".vmrk", ".eeg")))pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1000), nrow = 100, ncol = 10)), colData = S4Vectors::DataFrame(label = paste0("Ch", 1:10)), samplingRate = 100 ) base <- tempfile() writeBrainVision(pe, base) unlink(paste0(base, c(".vhdr", ".vmrk", ".eeg")))
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.
Wickham H (2014). "Tidy Data." Journal of Statistical Software, 59(10), 1-23. doi:10.18637/jss.v059.i10
readCSV, writeEventsCSV,
writeEDF, writePhysioHDF5
# Create example data pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), colData = 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)), colData = 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. The EDF file is written to path as a
side effect.
Kemp, B., et al. (1992). "A simple format for exchange of digitized polygraphic recordings." Electroencephalography and Clinical Neurophysiology, 82(5), 391-393. doi:10.1016/0013-4694(92)90009-7
readEDF, writeBIDS,
writePhysioHDF5, writeCSV
# Create a PhysioExperiment with EEG-like data pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1000), nrow = 100, ncol = 10)), colData = S4Vectors::DataFrame(label = paste0("Ch", 1:10)), samplingRate = 100 ) # Export to EDF format in a temporary file tmp <- tempfile(fileext = ".edf") writeEDF(pe, tmp, patient_id = "Subject01", recording_id = "Session1") unlink(tmp)# Create a PhysioExperiment with EEG-like data pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1000), nrow = 100, ncol = 10)), colData = S4Vectors::DataFrame(label = paste0("Ch", 1:10)), samplingRate = 100 ) # Export to EDF format in a temporary file tmp <- tempfile(fileext = ".edf") writeEDF(pe, tmp, patient_id = "Subject01", recording_id = "Session1") unlink(tmp)
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.
Wickham H (2014). "Tidy Data." Journal of Statistical Software, 59(10), 1-23. doi:10.18637/jss.v059.i10
readElectrodePositionsCSV, writeCSV,
writeBIDS
pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(400), nrow = 100, ncol = 4)), colData = 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)), colData = 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.
Wickham H (2014). "Tidy Data." Journal of Statistical Software, 59(10), 1-23. doi:10.18637/jss.v059.i10
readEventsCSV, writeCSV,
writeBIDS
# 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.
pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1000), nrow = 100, ncol = 10)), colData = S4Vectors::DataFrame(label = paste0("Ch", 1:10)), samplingRate = 100 ) tmp <- tempfile(fileext = ".gdf") writeGDF(pe, tmp) unlink(tmp)pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1000), nrow = 100, ncol = 10)), colData = S4Vectors::DataFrame(label = paste0("Ch", 1:10)), samplingRate = 100 ) tmp <- tempfile(fileext = ".gdf") writeGDF(pe, tmp) unlink(tmp)
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.
MathWorks (2024). "MAT-File Format." Technical documentation. https://www.mathworks.com/help/matlab/import_export/mat-file-versions.html
readMAT, writeCSV,
writeEDF, writePhysioHDF5
# 'R.matlab' is an optional dependency; guard the example so it only runs # when the package is installed. if (requireNamespace("R.matlab", quietly = TRUE)) { pe <- PhysioExperiment( assays = list(raw = matrix(0, nrow = 100, ncol = 10)), colData = S4Vectors::DataFrame(label = paste0("Ch", seq_len(10))), samplingRate = 256 ) tf <- tempfile(fileext = ".mat") writeMAT(pe, tf) unlink(tf) }# 'R.matlab' is an optional dependency; guard the example so it only runs # when the package is installed. if (requireNamespace("R.matlab", quietly = TRUE)) { pe <- PhysioExperiment( assays = list(raw = matrix(0, nrow = 100, ncol = 10)), colData = S4Vectors::DataFrame(label = paste0("Ch", seq_len(10))), samplingRate = 256 ) tf <- tempfile(fileext = ".mat") writeMAT(pe, tf) unlink(tf) }
Serialises a PhysioExperiment (or MultiPhysioExperiment) to a
directory of Apache Parquet tables and JSON sidecars. Each assay is stored
as a columnar Parquet table (one column per channel), and colData,
rowData, events, metadata, provenance and per-assay sampling rates are
stored alongside so that readParquet() reproduces the object exactly.
writeParquet(x, dir, overwrite = FALSE)writeParquet(x, dir, overwrite = FALSE)
x |
A |
dir |
Output directory (created if absent). |
overwrite |
Overwrite a non-empty directory (default |
Parquet is a columnar, self-describing format that DuckDB can query in place
via read_parquet(), enabling out-of-core aggregation over the assays
without loading them into R (see registerParquetAssay()).
A MultiPhysioExperiment is written as a streams/ sub-directory (one
Parquet dataset per stream) plus its common clock (t0, reference rate,
per-stream offsets).
The output dir, invisibly.
Apache Software Foundation. "Apache Parquet." https://parquet.apache.org/.
readParquet(), registerParquetAssay(), writePhysioHDF5()
if (requireNamespace("arrow", quietly = TRUE)) { pe <- PhysioExperiment( assays = S4Vectors::SimpleList(raw = matrix(rnorm(30), 10, 3)), colData = S4Vectors::DataFrame(label = c("Fp1", "Fp2", "Cz")), samplingRate = 256) d <- tempfile("pe-parquet") writeParquet(pe, d) pe2 <- readParquet(d) }if (requireNamespace("arrow", quietly = TRUE)) { pe <- PhysioExperiment( assays = S4Vectors::SimpleList(raw = matrix(rnorm(30), 10, 3)), colData = S4Vectors::DataFrame(label = c("Fp1", "Fp2", "Cz")), samplingRate = 256) d <- tempfile("pe-parquet") writeParquet(pe, d) pe2 <- readParquet(d) }
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 object.
writePhysio() returns the input object invisibly.
Wickham, H. (2014). "Tidy Data." Journal of Statistical Software, 59(10), 1-23. doi:10.18637/jss.v059.i10
readEDF, readPhysioHDF5,
readCSV, readMAT
# 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 integer vector specifying chunk dimensions for
HDF5 storage. If |
compression_level |
Integer compression level (0-9). Default is 6. |
Saves a PhysioExperiment object to HDF5 format, enabling out-of-memory access for large datasets.
Invisible NULL. The HDF5 file is written to path as
a side effect.
The HDF Group (1997-2024). "Hierarchical Data Format, version 5." https://www.hdfgroup.org/HDF5/
readPhysioHDF5, isHDF5Backed,
realizeHDF5, writeAssayHDF5
# Create a PhysioExperiment pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1000), nrow = 100, ncol = 10)), samplingRate = 100 ) # Save to a temporary HDF5 file with compression tmp <- tempfile(fileext = ".h5") writePhysioHDF5(pe, tmp, compression_level = 6) # Overwrite the existing file writePhysioHDF5(pe, tmp, overwrite = TRUE) unlink(tmp)# Create a PhysioExperiment pe <- PhysioExperiment( assays = list(raw = matrix(rnorm(1000), nrow = 100, ncol = 10)), samplingRate = 100 ) # Save to a temporary HDF5 file with compression tmp <- tempfile(fileext = ".h5") writePhysioHDF5(pe, tmp, compression_level = 6) # Overwrite the existing file writePhysioHDF5(pe, tmp, overwrite = TRUE) unlink(tmp)
Writes the provenance / audit trail of a PhysioExperiment (or a
provenance data.frame from provenance) to a
W3C PROV document. Three interchange syntaxes are supported: PROV-JSON
(default), PROV in JSON-LD, and PROV-N. The document round-trips exactly
through readProv.
writeProv(x, path, format = c("prov-json", "json-ld", "prov-n"))writeProv(x, path, format = c("prov-json", "json-ld", "prov-n"))
x |
A |
path |
Output file path. |
format |
One of |
path, invisibly.
W3C PROV-JSON (Huynh et al. 2013); PROV-O; PROV-N.
pe <- PhysioExperiment( S4Vectors::SimpleList(raw = matrix(rnorm(20), 10, 2)), samplingRate = 100) pe <- logStep(pe, "filterSignals", params = list(low = 1, high = 40)) tf <- tempfile(fileext = ".json") writeProv(pe, tf) readProv(tf)$activitype <- PhysioExperiment( S4Vectors::SimpleList(raw = matrix(rnorm(20), 10, 2)), samplingRate = 100) pe <- logStep(pe, "filterSignals", params = list(low = 1, high = 40)) tf <- tempfile(fileext = ".json") writeProv(pe, tf) readProv(tf)$activity
Writes a PhysioExperiment to a WFDB record (.hea + .dat).
writeWFDB(x, record, format = 16L, gain = 200, baseline = 0)writeWFDB(x, record, format = 16L, gain = 200, baseline = 0)
x |
A |
record |
Output record path (without extension). |
format |
WFDB storage format: one of 16, 61, 80, 212, 24, 32. |
gain |
ADC gain (units per ADU); a scalar or one per channel. |
baseline |
ADC baseline value (raw value for 0 physical); scalar or per channel. |
record, invisibly.
Writes a PhysioEvents object (onset in samples, type = beat
symbol, value = auxiliary string) to a WFDB binary annotation file.
writeWFDBAnnotation(events, path)writeWFDBAnnotation(events, path)
events |
A |
path |
Output annotation file path. |
path, invisibly.