| Title: | Work with 'BIDS' (Brain Imaging Data Structure) Projects |
|---|---|
| Description: | Tools for working with 'BIDS' (Brain Imaging Data Structure) formatted neuroimaging datasets. The package provides functionality for reading and querying 'BIDS'-compliant projects, creating mock 'BIDS' datasets for testing, and extracting preprocessed data from 'fMRIPrep' derivatives. It supports searching and filtering 'BIDS' files by various entities such as subject, session, task, and run to streamline neuroimaging data workflows. See Gorgolewski et al. (2016) <doi:10.1038/sdata.2016.44> for the 'BIDS' specification. |
| Authors: | Bradley Buchsbaum [aut, cre] (ORCID: <https://orcid.org/0000-0002-1108-4866>) |
| Maintainer: | Bradley Buchsbaum <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.4.0 |
| Built: | 2026-06-03 03:07:27 UTC |
| Source: | https://github.com/bbuchsbaum/bidser |
Anatomical parser constructor
anat_parser()anat_parser()
An anatomical BIDS parser object for parsing anatomical files
# Create an anatomical parser parser <- anat_parser() # Parse an anatomical file result <- parse(parser, "sub-01_T1w.nii.gz")# Create an anatomical parser parser <- anat_parser() # Parse an anatomical file result <- parse(parser, "sub-01_T1w.nii.gz")
Coerce to a BIDS URI object
as_bids_uri(x, ...) ## S3 method for class 'character' as_bids_uri(x, ...) ## S3 method for class 'bids_uri' as_bids_uri(x, ...)as_bids_uri(x, ...) ## S3 method for class 'character' as_bids_uri(x, ...) ## S3 method for class 'bids_uri' as_bids_uri(x, ...)
x |
A character scalar BIDS URI string, or a |
... |
Additional arguments passed to methods. |
A bids_uri object.
u <- as_bids_uri("bids::sub-01/anat/sub-01_T1w.nii.gz") u$dataset_name # "" u$relative_path # "sub-01/anat/sub-01_T1w.nii.gz"u <- as_bids_uri("bids::sub-01/anat/sub-01_T1w.nii.gz") u$dataset_name # "" u$relative_path # "sub-01/anat/sub-01_T1w.nii.gz"
This function performs a simple, lightweight check of common BIDS requirements:
Checks that participants.tsv and dataset_description.json exist at the root.
Ensures all subject directories begin with sub-.
If sessions are present, ensures that session directories begin with ses-.
bids_check_compliance(x, schema_check = TRUE, schema_version = "1.10.0") bids_check_compliance(x, schema_check = TRUE, schema_version = "1.10.0")bids_check_compliance(x, schema_check = TRUE, schema_version = "1.10.0") bids_check_compliance(x, schema_check = TRUE, schema_version = "1.10.0")
x |
A |
schema_check |
Logical. Whether to run schema validation (default |
schema_version |
Character. BIDS schema version to use (default |
Note: This is not a full BIDS validator. For complete validation, use the official BIDS validator.
A list with compliance check results including passed, issues,
warnings, participants_source, and schema_checked.
A list with:
passed (logical): TRUE if all checks passed, FALSE otherwise.
issues (character vector): Descriptions of any issues found.
tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) compliance <- bids_check_compliance(proj) # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) })tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) compliance <- bids_check_compliance(proj) # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) })
Constructs a parser_spec list suitable for passing to
register_datatype. Standard BIDS entity keys are recognised
automatically and filled with canonical regex patterns and ordering; unknown
keys fall back to [A-Za-z0-9]+ and are appended after standard ones.
bids_datatype_spec( type, entities = c("sub", "ses"), required = "sub", suffixes = list() )bids_datatype_spec( type, entities = c("sub", "ses"), required = "sub", suffixes = list() )
type |
Non-empty character string naming the datatype (e.g.
|
entities |
Character vector of BIDS entity keys to include (e.g.
|
required |
Character vector of entity keys that are required
(non-optional). Defaults to |
suffixes |
Named list mapping kind strings to one or more file
extensions. Each value may be a single string or a character vector
(e.g. |
A parser_spec list with elements keystruc,
kinds, and type, ready for gen_parser and
register_datatype.
spec <- bids_datatype_spec( type = "dwi", entities = c("sub", "ses", "acq", "run"), suffixes = list( dwi = c(".nii.gz", ".nii", ".bvec", ".bval", ".json"), sbref = c(".nii.gz", ".nii") ) ) ## Not run: register_datatype("dwi", spec = spec, parser_fn = gen_parser(spec), folder = "dwi", scope = "raw") ## End(Not run)spec <- bids_datatype_spec( type = "dwi", entities = c("sub", "ses", "acq", "run"), suffixes = list( dwi = c(".nii.gz", ".nii", ".bvec", ".bval", ".json"), sbref = c(".nii.gz", ".nii") ) ) ## Not run: register_datatype("dwi", spec = spec, parser_fn = gen_parser(spec), folder = "dwi", scope = "raw") ## End(Not run)
This function creates a heatmap visualization of a BIDS project, where the x-axis represents subjects and the y-axis represents tasks by run. Each cell in the heatmap is colored by file size, providing an intuitive view of data completeness and size distribution across the project. This is particularly useful for quality control and identifying missing data.
bids_heatmap( x, interactive = TRUE, color_scheme = "viridis", file_type = "func", highlight_missing = TRUE, text_size = 2.5, rotate_labels = TRUE )bids_heatmap( x, interactive = TRUE, color_scheme = "viridis", file_type = "func", highlight_missing = TRUE, text_size = 2.5, rotate_labels = TRUE )
x |
A |
interactive |
Logical. Whether to create an interactive plot (default TRUE) |
color_scheme |
Character. Name of the color palette to use (default "viridis") |
file_type |
Character. Type of files to visualize (default "func") |
highlight_missing |
Logical. Whether to highlight missing data points (default TRUE) |
text_size |
Numeric. Size of text labels (default 2.5) |
rotate_labels |
Logical. Whether to rotate the axis labels (default TRUE) |
A plot object (ggplot2 or plotly depending on interactive parameter)
# Create a basic interactive heatmap for a BIDS dataset tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) bids_heatmap(proj) # Create a static heatmap with custom settings bids_heatmap(proj, interactive = FALSE, color_scheme = "plasma", text_size = 3, rotate_labels = FALSE) # Visualize anatomical data with missing data highlighted bids_heatmap(proj, file_type = "anat", highlight_missing = TRUE, color_scheme = "magma") # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) })# Create a basic interactive heatmap for a BIDS dataset tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) bids_heatmap(proj) # Create a static heatmap with custom settings bids_heatmap(proj, interactive = FALSE, color_scheme = "plasma", text_size = 3, rotate_labels = FALSE) # Visualize anatomical data with missing data highlighted bids_heatmap(proj, file_type = "anat", highlight_missing = TRUE, color_scheme = "magma") # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) })
Creates a lightweight on-disk index of files and parsed BIDS entities. The index is stored as an RDS file and does not change user-facing query semantics; it simply provides a cached tabular representation of the project.
bids_index(x, rebuild = FALSE, persist = TRUE)bids_index(x, rebuild = FALSE, persist = TRUE)
x |
A |
rebuild |
If |
persist |
If |
A tibble describing indexed files.
tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) idx <- bids_index(proj, persist = FALSE) print(idx) # Example datasets are cached; leave the cache in place. }, error = function(e) message("Example requires internet: ", e$message))tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) idx <- bids_index(proj, persist = FALSE) print(idx) # Example datasets are cached; leave the cache in place. }, error = function(e) message("Example requires internet: ", e$message))
These functions create parsers for different types of BIDS files using regex-based pattern matching instead of parser combinators. Create a parser for a generic BIDS file
bids_parser()bids_parser()
This parser tries to match against various known parsers (anat, func, fmriprep anat/func).
A BIDS parser object that can parse various types of BIDS files
# Create a generic BIDS parser parser <- bids_parser() # Parse different types of files anat_result <- parse(parser, "sub-01_T1w.nii.gz") func_result <- parse(parser, "sub-01_task-rest_bold.nii.gz") prep_result <- parse(parser, "sub-01_task-rest_space-MNI152NLin2009cAsym_desc-preproc_bold.nii.gz")# Create a generic BIDS parser parser <- bids_parser() # Parse different types of files anat_result <- parse(parser, "sub-01_T1w.nii.gz") func_result <- parse(parser, "sub-01_task-rest_bold.nii.gz") prep_result <- parse(parser, "sub-01_task-rest_space-MNI152NLin2009cAsym_desc-preproc_bold.nii.gz")
This function creates a BIDS project object from a directory containing BIDS-formatted neuroimaging data. It can optionally load preprocessed derivatives from fMRIPrep. The function validates the basic BIDS structure and provides methods for accessing raw and preprocessed data, querying subjects, sessions, and tasks, reading event files, and checking BIDS compliance.
bids_project( path = ".", fmriprep = FALSE, prep_dir = "derivatives/fmriprep", strict_participants = TRUE, derivatives = c("auto", "legacy", "none"), pipelines = NULL, index = c("auto", "none"), index_path = NULL )bids_project( path = ".", fmriprep = FALSE, prep_dir = "derivatives/fmriprep", strict_participants = TRUE, derivatives = c("auto", "legacy", "none"), pipelines = NULL, index = c("auto", "none"), index_path = NULL )
path |
Character string. The file path to the root of the BIDS project. Defaults to the current directory ("."). |
fmriprep |
Logical. Whether to load the fMRIPrep derivatives folder hierarchy. Defaults to FALSE. This remains available as a legacy compatibility switch for existing fMRIPrep-oriented workflows. |
prep_dir |
Character string. The location of the fMRIPrep subfolder relative
to the derivatives directory. Defaults to "derivatives/fmriprep". New code
should prefer |
strict_participants |
Logical. If TRUE (default), require |
derivatives |
Derivatives loading mode:
|
pipelines |
Optional character vector of derivative pipeline names (or
relative roots) to include when |
index |
Whether to use an on-disk file index:
|
index_path |
Optional path for the persisted index file. Defaults to
|
A bids_project object representing the BIDS project structure. The object
provides methods for:
Accessing raw and preprocessed data files
Querying subjects, sessions, and tasks
Reading event files and confound regressors
Checking BIDS compliance
Extracting metadata from file names Returns NULL if the directory does not contain a valid BIDS dataset.
# Create a BIDS project tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) # Get all functional scans all_scans <- func_scans(proj) # Get scans for specific subjects sub_scans <- func_scans(proj, subid="0[123]") # Get scans for a specific task task_scans <- func_scans(proj, task="rest") # Get scans from specific runs run_scans <- func_scans(proj, run="0[123]") # Combine multiple filters filtered_scans <- func_scans(proj, subid="01", task="rest", run="01") # Get relative paths instead of full paths rel_scans <- func_scans(proj, full_path=FALSE) # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) })# Create a BIDS project tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) # Get all functional scans all_scans <- func_scans(proj) # Get scans for specific subjects sub_scans <- func_scans(proj, subid="0[123]") # Get scans for a specific task task_scans <- func_scans(proj, task="rest") # Get scans from specific runs run_scans <- func_scans(proj, run="0[123]") # Combine multiple filters filtered_scans <- func_scans(proj, subid="01", task="rest", run="01") # Get relative paths instead of full paths rel_scans <- func_scans(proj, full_path=FALSE) # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) })
Create a lightweight text report for a BIDS project
bids_report(x, ...)bids_report(x, ...)
x |
A |
... |
Additional arguments passed to |
An object of class bids_report.
tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) rpt <- bids_report(proj) print(rpt) # Example datasets are cached; leave the cache in place. }, error = function(e) message("Example requires internet: ", e$message))tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) rpt <- bids_report(proj) print(rpt) # Example datasets are cached; leave the cache in place. }, error = function(e) message("Example requires internet: ", e$message))
Produces a structured report payload composed from dataset summary, compliance checks, derivative pipeline discovery, and run-level variables coverage.
bids_report_data(x, ...)bids_report_data(x, ...)
x |
A |
... |
Additional arguments passed to |
A list with report-ready summary tables and metadata.
tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) rd <- bids_report_data(proj) # Example datasets are cached; leave the cache in place. }, error = function(e) message("Example requires internet: ", e$message))tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) rd <- bids_report_data(proj) # Example datasets are cached; leave the cache in place. }, error = function(e) message("Example requires internet: ", e$message))
Loads the vendored BIDS JSON schema and caches the result in the package environment so repeated calls within a session are free.
bids_schema(version = "1.10.0")bids_schema(version = "1.10.0")
version |
Character. BIDS schema version to load (default |
A named list representing the compiled schema with top-level keys
objects, rules, meta, etc.
s <- bids_schema() names(s)s <- bids_schema() names(s)
Returns the version strings for all BIDS schema JSON files shipped with this installation of bidser.
bids_schema_versions()bids_schema_versions()
Character vector of available version strings (e.g. "1.10.1").
bids_schema_versions()bids_schema_versions()
bids_subject returns a lightweight interface with helper functions
for retrieving data associated with one subject.
bids_subject returns a lightweight facade that exposes convenience
functions to work with all data associated with one subject within a
BIDS project.
This function extracts a single subject's data from a BIDS project, creating a new BIDS project object containing only that subject's files and metadata.
bids_subject(x, subid, ...) bids_subject.bids_project(x, subid, ...) bids_subject(x, subid, ...)bids_subject(x, subid, ...) bids_subject.bids_project(x, subid, ...) bids_subject(x, subid, ...)
x |
A |
subid |
Character string. The subject ID to extract (without the "sub-" prefix). |
... |
Additional arguments (not currently used). |
A list of helper functions for the subject.
A list containing subject-specific helper functions. Each function automatically filters results for the specified subject. The returned object contains the following callable functions:
events(...)Returns nested tibble with event data for this subject.
Equivalent to read_events(project, subid = "XX", ...).
Additional arguments (task, session, run, nest, etc.) can be passed.
event_files(...)Returns character vector of event file paths for this subject.
Equivalent to event_files(project, subid = "XX", ...).
Additional arguments (task, session, run, full_path, etc.) can be passed.
scans(...)Returns character vector of functional scan file paths for this subject.
Equivalent to func_scans(project, subid = "XX", ...).
Additional arguments (task, session, run, kind, full_path, etc.) can be passed.
confounds(...)Returns confound data for this subject (requires fMRIPrep derivatives).
Equivalent to read_confounds(project, subid = "XX", ...).
Additional arguments (task, session, run, cvars, npcs, etc.) can be passed.
preproc_scans(...)Returns preprocessed scan paths for this subject (requires fMRIPrep derivatives).
Equivalent to preproc_scans(project, subid = "XX", ...).
Additional arguments (task, session, run, space, variant, etc.) can be passed.
brain_mask(...)Creates brain mask for this subject (requires fMRIPrep derivatives).
Equivalent to brain_mask(project, subid = "XX", ...).
Additional arguments (thresh, etc.) can be passed.
A new bids_project object containing only the specified subject's data.
Returns NULL if the subject is not found in the project.
tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) subj <- bids_subject(proj, "01") subj$events() subj$scans() # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) }) tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) # Create subject interface for subject 01 subj <- bids_subject(proj, "01") # Get functional scan paths for this subject scan_paths <- subj$scans() print(paste("Subject 01 has", length(scan_paths), "functional scans")) # Get event file paths for this subject event_paths <- subj$event_files() print(paste("Subject 01 has", length(event_paths), "event files")) # Read event data for this subject event_data <- subj$events() print("Event data structure:") print(event_data) # You can still pass additional filtering arguments # For example, get only specific tasks: task_scans <- subj$scans(task = "balloonanalogrisktask") # Dataset cache is intentionally retained for performance. }, error = function(e) { message("Example requires internet connection: ", e$message) }) # Create a subject interface tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) # Create subject interface for subject 01 subj <- bids_subject(proj, "01") # Use the helper functions scans <- subj$scans() events <- subj$event_files() print(paste("Subject 01:", length(scans), "scans,", length(events), "events")) # Dataset cache is intentionally retained for performance. }, error = function(e) { message("Example requires internet connection: ", e$message) })tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) subj <- bids_subject(proj, "01") subj$events() subj$scans() # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) }) tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) # Create subject interface for subject 01 subj <- bids_subject(proj, "01") # Get functional scan paths for this subject scan_paths <- subj$scans() print(paste("Subject 01 has", length(scan_paths), "functional scans")) # Get event file paths for this subject event_paths <- subj$event_files() print(paste("Subject 01 has", length(event_paths), "event files")) # Read event data for this subject event_data <- subj$events() print("Event data structure:") print(event_data) # You can still pass additional filtering arguments # For example, get only specific tasks: task_scans <- subj$scans(task = "balloonanalogrisktask") # Dataset cache is intentionally retained for performance. }, error = function(e) { message("Example requires internet connection: ", e$message) }) # Create a subject interface tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) # Create subject interface for subject 01 subj <- bids_subject(proj, "01") # Use the helper functions scans <- subj$scans() events <- subj$event_files() print(paste("Subject 01:", length(scans), "scans,", length(events), "events")) # Dataset cache is intentionally retained for performance. }, error = function(e) { message("Example requires internet connection: ", e$message) })
Provides a quick summary of dataset statistics, including:
Number of subjects
Number of sessions (if applicable)
Available tasks and the number of runs per task
Total number of runs
bids_summary(x) bids_summary(x)bids_summary(x) bids_summary(x)
x |
A |
A list containing summary statistics about the BIDS dataset
A list with summary information:
n_subjects: number of participants
n_sessions: number of sessions (if any), otherwise NULL
tasks: a data frame with task and n_runs columns
total_runs: total number of runs across the dataset
tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) summary <- bids_summary(proj) # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) })tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) summary <- bids_summary(proj) # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) })
This function orchestrates the process of selecting files from a BIDS project, applying a transformation to each file, and saving the output in a new BIDS derivative directory. It leverages the existing bidser parsing and search infrastructure.
bids_transform(x, transformer, pipeline_name, ...)bids_transform(x, transformer, pipeline_name, ...)
x |
A |
transformer |
A function that performs the transformation. It must take two arguments, the input file path and the output directory, and return the output file path. The transformer is responsible for creating the output file. |
pipeline_name |
The name for the new derivative pipeline. |
... |
Additional arguments passed to |
A character vector of paths to the newly created files.
tryCatch({ ds_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds_path) # Create a simple transformer that adds a description add_desc_transformer <- function(infile, outdir) { entities <- encode(basename(infile)) entities$desc <- if (is.null(entities$desc)) "smooth6mm" else paste(entities$desc, "smooth6mm", sep="") # Generate new filename new_name <- decode_bids_entities(entities) outfile <- file.path(outdir, new_name) # For demo, just copy the file (real transformer would process it) file.copy(infile, outfile) return(outfile) } # Apply transformation to functional files for subject 01 new_files <- bids_transform(proj, add_desc_transformer, "smoothed", subid = "01", suffix = "bold.nii.gz") print(length(new_files)) }, error = function(e) { message("Example failed: ", e$message) })tryCatch({ ds_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds_path) # Create a simple transformer that adds a description add_desc_transformer <- function(infile, outdir) { entities <- encode(basename(infile)) entities$desc <- if (is.null(entities$desc)) "smooth6mm" else paste(entities$desc, "smooth6mm", sep="") # Generate new filename new_name <- decode_bids_entities(entities) outfile <- file.path(outdir, new_name) # For demo, just copy the file (real transformer would process it) file.copy(infile, outfile) return(outfile) } # Apply transformation to functional files for subject 01 new_files <- bids_transform(proj, add_desc_transformer, "smoothed", subid = "01", suffix = "bold.nii.gz") print(length(new_files)) }, error = function(e) { message("Example failed: ", e$message) })
Parses a BIDS URI string of the form bids:<dataset_name>:<relative_path>
and returns an S3 object of class bids_uri.
bids_uri(uri)bids_uri(uri)
uri |
A character scalar BIDS URI, e.g.
|
An object of class bids_uri with fields dataset_name,
relative_path, and uri.
u <- bids_uri("bids::sub-01/func/sub-01_task-rest_bold.nii.gz") u$dataset_name # "" u$relative_path # "sub-01/func/sub-01_task-rest_bold.nii.gz" # URI with a named dataset link u2 <- bids_uri("bids:deriv1:sub-01/anat/sub-01_T1w.nii.gz") u2$dataset_name # "deriv1"u <- bids_uri("bids::sub-01/func/sub-01_task-rest_bold.nii.gz") u$dataset_name # "" u$relative_path # "sub-01/func/sub-01_task-rest_bold.nii.gz" # URI with a named dataset link u2 <- bids_uri("bids:deriv1:sub-01/anat/sub-01_T1w.nii.gz") u2$dataset_name # "deriv1"
Get the BIDS version of a dataset
bids_version(x, ...) ## S3 method for class 'bids_project' bids_version(x, ...) ## S3 method for class 'mock_bids_project' bids_version(x, ...) ## S3 method for class 'bids_dataset_description' bids_version(x, ...)bids_version(x, ...) ## S3 method for class 'bids_project' bids_version(x, ...) ## S3 method for class 'mock_bids_project' bids_version(x, ...) ## S3 method for class 'bids_dataset_description' bids_version(x, ...)
x |
A |
... |
Additional arguments passed to methods. |
A character scalar BIDS version string, or NA_character_.
tryCatch({ ds001_path <- get_example_bids_dataset("ds001") desc <- read_dataset_description(ds001_path) bids_version(desc) # Example datasets are cached; leave the cache in place. }, error = function(e) message("Example requires internet: ", e$message))tryCatch({ ds001_path <- get_example_bids_dataset("ds001") desc <- read_dataset_description(ds001_path) bids_version(desc) # Example datasets are cached; leave the cache in place. }, error = function(e) message("Example requires internet: ", e$message))
This convenience function wraps create_preproc_mask() and
returns a brain mask volume for a given subject.
brain_mask(x, subid, ...) ## S3 method for class 'bids_project' brain_mask(x, subid, ...)brain_mask(x, subid, ...) ## S3 method for class 'bids_project' brain_mask(x, subid, ...)
x |
A bids_project object |
subid |
A regular expression pattern to match subject IDs |
... |
Additional arguments passed to methods |
A logical mask volume
# Download and load a BIDS project with fMRIPrep derivatives tryCatch({ ds001_deriv_path <- get_example_bids_dataset("ds000001-fmriprep") proj <- bids_project(ds001_deriv_path, fmriprep=TRUE) mask <- brain_mask(proj, subid="01") # Create mask for multiple subjects multi_mask <- brain_mask(proj, subid=".*") # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires derivatives dataset: ", e$message) })# Download and load a BIDS project with fMRIPrep derivatives tryCatch({ ds001_deriv_path <- get_example_bids_dataset("ds000001-fmriprep") proj <- bids_project(ds001_deriv_path, fmriprep=TRUE) mask <- brain_mask(proj, subid="01") # Create mask for multiple subjects multi_mask <- brain_mask(proj, subid=".*") # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires derivatives dataset: ", e$message) })
Creates a structured list or tibble containing all available data for a single subject, organized by data type. This provides a comprehensive view of all available files for a subject, useful for batch processing and pipeline ingestion.
build_subject_graph(x, subid, session = ".*", flatten = FALSE, ...) ## S3 method for class 'bids_project' build_subject_graph(x, subid, session = ".*", flatten = FALSE, ...) ## S3 method for class 'mock_bids_project' build_subject_graph(x, subid, session = ".*", flatten = FALSE, ...)build_subject_graph(x, subid, session = ".*", flatten = FALSE, ...) ## S3 method for class 'bids_project' build_subject_graph(x, subid, session = ".*", flatten = FALSE, ...) ## S3 method for class 'mock_bids_project' build_subject_graph(x, subid, session = ".*", flatten = FALSE, ...)
x |
A |
subid |
Subject identifier (with or without |
session |
Optional session filter. Default |
flatten |
Logical. If |
... |
Additional arguments passed to underlying query functions. |
If flatten = FALSE (default), a named list with class bids_subject_graph:
Subject identifier (without "sub-" prefix)
Character vector of available sessions
Named list of preprocessed EPI file paths, keyed by task.run
List with t1w and masks sublists
Named list of transform files, keyed by from_to_to format
Nested list by space, then hemisphere (L/R)
Character vector of confound file paths
If flatten = TRUE, a tibble with columns:
Type of file (epi, anat, transform, surface, confound)
File path
BIDS metadata
# Build subject graph tryCatch({ ds_path <- get_example_bids_dataset("ds000001-fmriprep") proj <- bids_project(ds_path, fmriprep = TRUE) # Get nested structure graph <- build_subject_graph(proj, "01") names(graph) # Get flat tibble flat <- build_subject_graph(proj, "01", flatten = TRUE) head(flat) # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) })# Build subject graph tryCatch({ ds_path <- get_example_bids_dataset("ds000001-fmriprep") proj <- bids_project(ds_path, fmriprep = TRUE) # Get nested structure graph <- build_subject_graph(proj, "01") names(graph) # Get flat tibble flat <- build_subject_graph(proj, "01", flatten = TRUE) head(flat) # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) })
check_confounds() reports nuisance columns that are unsuitable for model
matrices, such as zero-variance columns within a run. clean_confounds()
drops the flagged columns and stores the diagnostics on the returned object.
check_confounds(x, checks = c("zero_variance", "rank"), group_vars = NULL) clean_confounds( x, clean = c("zero_variance", "rank"), group_vars = NULL, inform = TRUE )check_confounds(x, checks = c("zero_variance", "rank"), group_vars = NULL) clean_confounds( x, clean = c("zero_variance", "rank"), group_vars = NULL, inform = TRUE )
x |
A confound table, typically a |
checks |
Character vector of checks to run. Supported values are
|
group_vars |
Optional character vector of columns defining run-level groups for flat tables. |
clean |
Character vector of cleaning operations to apply. Supported
values are |
inform |
Logical. If |
These helpers understand both nested bids_confounds objects returned by
read_confounds(..., nest = TRUE) and flat confound tables. For flat tables,
checks are run within the identifier columns present in the data
(participant_id, task, session, and run by default).
check_confounds() returns a tibble of diagnostics. clean_confounds()
returns x with flagged columns removed and a confound_diagnostics
attribute containing the same diagnostic rows.
df <- tibble::tibble( participant_id = "01", task = "rest", run = "01", cosine00 = c(1, 0, -1), cosine01 = c(0, 0, 0) ) check_confounds(df) clean_confounds(df)df <- tibble::tibble( participant_id = "01", task = "rest", run = "01", cosine00 = c(1, 0, -1), cosine01 = c(0, 0, 0) ) check_confounds(df) clean_confounds(df)
This function performs a comprehensive inspection of functional scans within a BIDS project, providing detailed summaries of scan counts and file sizes per subject and task. It helps identify potential issues such as missing scans, inconsistent file sizes, or unexpected variations in the data.
check_func_scans(x)check_func_scans(x)
x |
A |
A list containing:
scans: A tibble with details of all functional scans, including:
Subject ID
Task name
Run number
File size
Full file path
tasklist: A vector of unique tasks found in the project
scans_per_subject: A summary tibble showing the number of scans per subject
If multiple tasks are present, also includes:
scans_per_task: Summary of scan counts by task
scans_per_task_subject: Summary of scan counts by subject and task
size_per_task: Tibble with file size statistics by task
If only one task is present:
size_per_subject: Tibble with file size statistics by subject
# Check functional scans in a BIDS dataset tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) scan_check <- check_func_scans(proj) print(scan_check) # Filter for specific subjects sub01_check <- check_func_scans(proj, subid="01") # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) })# Check functional scans in a BIDS dataset tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) scan_check <- check_func_scans(proj) print(scan_check) # Filter for specific subjects sub01_check <- check_func_scans(proj, subid="01") # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) })
Clears the session-level cache of downloaded example BIDS datasets. This can be useful to free up memory or force re-download of datasets.
clear_example_bids_cache()clear_example_bids_cache()
Invisible NULL
# Clear the cache clear_example_bids_cache()# Clear the cache clear_example_bids_cache()
This function retrieves a vector of confound files from a BIDS project that match specified criteria. Confound files in BIDS derivatives (typically from fMRIPrep) contain nuisance variables that can be used for denoising fMRI data, such as motion parameters, physiological signals, and other noise components.
Searches the mock BIDS structure for files matching typical confound file patterns
(e.g., *_confounds*.tsv, *_regressors*.tsv, *_timeseries*.tsv)
within the derivatives directory.
confound_files(x, ...) ## S3 method for class 'bids_project' confound_files(x, subid = ".*", task = ".*", session = ".*", ...) ## S3 method for class 'mock_bids_project' confound_files( x, subid = ".*", task = ".*", session = ".*", run = ".*", full_path = FALSE, ... )confound_files(x, ...) ## S3 method for class 'bids_project' confound_files(x, subid = ".*", task = ".*", session = ".*", ...) ## S3 method for class 'mock_bids_project' confound_files( x, subid = ".*", task = ".*", session = ".*", run = ".*", full_path = FALSE, ... )
x |
A |
... |
Additional arguments passed to |
subid |
Regex pattern for subject IDs. Default |
task |
Regex pattern for task names. Default |
session |
Regex pattern for session IDs. Default |
run |
Regex pattern for run indices. Default |
full_path |
If |
This function assumes confound files reside in the derivatives path
specified by x$prep_dir and were defined in the file_structure
passed to create_mock_bids with fmriprep=TRUE.
A character vector of file paths to confound files matching the specified criteria. If no matching files are found, returns NULL.
A character vector of file paths
A character vector of relative or full paths to potential confound files,
or NULL if none are found.
# Get all confound files from a BIDS project with fMRIPrep derivatives tryCatch({ ds_path <- get_example_bids_dataset("ds000001-fmriprep") proj <- bids_project(ds_path, fmriprep=TRUE) conf_files <- confound_files(proj) # Get confound files for specific subjects and tasks confound_files(proj, subid="sub-01", task="balloonanalogrisktask") # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) }) # Setup mock project with a derivative confound file participants_df <- tibble::tibble(participant_id = "01") file_structure_df <- tibble::tribble( ~subid, ~session, ~datatype, ~task, ~run, ~suffix, ~fmriprep, ~desc, "01", NA, "func", "taskA", "01", "desc-confounds_timeseries.tsv", TRUE, "confounds" ) mock_proj <- create_mock_bids("ConfoundMock", participants_df, file_structure_df) # Find confound files confound_files(mock_proj) # Find for specific subject confound_files(mock_proj, subid="01")# Get all confound files from a BIDS project with fMRIPrep derivatives tryCatch({ ds_path <- get_example_bids_dataset("ds000001-fmriprep") proj <- bids_project(ds_path, fmriprep=TRUE) conf_files <- confound_files(proj) # Get confound files for specific subjects and tasks confound_files(proj, subid="sub-01", task="balloonanalogrisktask") # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) }) # Setup mock project with a derivative confound file participants_df <- tibble::tibble(participant_id = "01") file_structure_df <- tibble::tribble( ~subid, ~session, ~datatype, ~task, ~run, ~suffix, ~fmriprep, ~desc, "01", NA, "func", "taskA", "01", "desc-confounds_timeseries.tsv", TRUE, "confounds" ) mock_proj <- create_mock_bids("ConfoundMock", participants_df, file_structure_df) # Find confound files confound_files(mock_proj) # Find for specific subject confound_files(mock_proj, subid="01")
Provides predefined, version-robust groups of confound variable names as
described in the fMRIPrep documentation. These sets abstract over naming
changes between fMRIPrep releases via the internal alias resolver used by
read_confounds().
confound_set(name, n = NULL)confound_set(name, n = NULL)
name |
Character. The name of the convenience set (see list above). |
n |
Optional integer used by CompCor sets to limit the number of components (e.g., first 5 or 6). Ignored for other sets. |
In addition to exact names, wildcard patterns are supported by the confound resolver:
prefix* selects all columns that start with prefix (e.g., cosine_*,
motion_outlier_*, a_comp_cor_*).
prefix*[N] selects the first N matches (e.g., a_comp_cor_*[6]).
Suffix combinations such as _derivative1, _power2, and
_derivative1_power2 are resolved across both old and new base names
(e.g., trans_x_derivative1 also finds X_derivative1 if present).
Available sets (case-insensitive):
"motion6": 6 rigid-body motion parameters: trans_x, trans_y,
trans_z, rot_x, rot_y, rot_z.
"motion12": motion6 + first temporal derivatives (adds
*_derivative1).
"motion24": motion12 + quadratic terms of base and derivatives (adds
*_power2 and *_derivative1_power2).
"global3": global signals: csf, white_matter, global_signal.
"9p": motion6 + global3 (9 parameters total).
"36p": motion24 + global3 plus their derivatives and quadratics
(i.e., the canonical 36-parameter set).
"acompcor": anatomical CompCor components (a_comp_cor_*). Use n to
cap the number of components retained, e.g., n = 6 -> a_comp_cor_*[6].
"tcompcor": temporal CompCor components (t_comp_cor_*). Supports n as
above.
"compcor": both anatomical and temporal CompCor (applies n to each
family if provided).
"cosine": discrete cosine-basis regressors (matches both cosine_* and cosine*).
"outliers": outlier/censoring covariates including
framewise_displacement, rmsd (if present), motion_outlier_*, and
non_steady_state_outlier*.
"dvars": DVARS family: dvars, std_dvars, non_std_dvars,
vx_wisestd_dvars (resolved to whichever names exist in your dataset).
"fd": framewise displacement only (framewise_displacement).
A character vector of confound variable names and/or wildcard tokens
that can be passed to read_confounds(..., cvars = confound_set(...)).
# Common usage: 24-parameter motion set confound_set("motion24") # 36-parameter model (Satterthwaite/Friston-style) confound_set("36p") # First 6 anatomical CompCor components confound_set("acompcor", n = 6) # All cosine regressors and outlier indicators confound_set("cosine") confound_set("outliers")# Common usage: 24-parameter motion set confound_set("motion24") # 36-parameter model (Satterthwaite/Friston-style) confound_set("36p") # First 6 anatomical CompCor components confound_set("acompcor", n = 6) # All cosine regressors and outlier indicators confound_set("cosine") confound_set("outliers")
Creates a structured confound strategy object that specifies which variables
to reduce via PCA and which to keep as-is. Pass the result directly to
read_confounds(..., cvars = confound_strategy(...)).
confound_strategy( name = NULL, pca_vars = NULL, raw_vars = NULL, perc_var = -1, npcs = -1 )confound_strategy( name = NULL, pca_vars = NULL, raw_vars = NULL, perc_var = -1, npcs = -1 )
name |
Character. Name of a predefined strategy (see above), or
|
pca_vars |
Character vector of confound names/wildcards to include in
PCA reduction. Ignored when |
raw_vars |
Character vector of confound names/wildcards to keep without
reduction. Ignored when |
perc_var |
Numeric. Percentage of variance to retain from PCA (default
-1, meaning use |
npcs |
Integer. Number of PCs to retain (default -1, meaning use
|
When a strategy is passed to read_confounds, the function:
Selects the pca_vars columns and reduces them via PCA
(retaining perc_var\
Selects the raw_vars columns and keeps them unchanged.
Column-binds the PCA scores with the raw columns.
Available named strategies:
"pcabasic80"PCA over motion24 + aCompCor + tCompCor + CSF + white matter, retaining 80\ Discrete cosine regressors are appended un-reduced.
A confound_strategy object (S3 class) that can be passed as
the cvars argument to read_confounds().
# Named strategy confound_strategy("pcabasic80") # Custom strategy: PCA motion + compcor to 5 PCs, keep cosine regressors confound_strategy( pca_vars = c(confound_set("motion24"), confound_set("compcor")), raw_vars = confound_set("cosine"), npcs = 5 )# Named strategy confound_strategy("pcabasic80") # Custom strategy: PCA motion + compcor to 5 PCs, keep cosine regressors confound_strategy( pca_vars = c(confound_set("motion24"), confound_set("compcor")), raw_vars = confound_set("cosine"), npcs = 5 )
Generates an in-memory representation of a BIDS project, suitable for testing and demonstration without requiring actual data files. Can optionally create a "stub" directory structure on disk.
create_mock_bids( project_name, participants, file_structure, dataset_description = NULL, event_data = list(), confound_data = list(), create_stub = FALSE, stub_path = NULL, prep_dir = "derivatives/fmriprep" )create_mock_bids( project_name, participants, file_structure, dataset_description = NULL, event_data = list(), confound_data = list(), create_stub = FALSE, stub_path = NULL, prep_dir = "derivatives/fmriprep" )
project_name |
A character string for the project name. |
participants |
Either a |
file_structure |
A |
dataset_description |
A list representing the |
event_data |
A named list where names are the relative paths of
|
confound_data |
A named list where names are relative paths of
confound TSV files within the derivatives directory and values are
their |
create_stub |
Logical (default |
stub_path |
Character string, the path where the stub directory will be
created. Required if |
prep_dir |
Character string, the path relative to the root for derivatives
(default "derivatives/fmriprep"). This path structure will be used both in
the internal |
An object of class mock_bids_project.
# --- Example Setup --- participants_df <- tibble::tibble(participant_id = c("01", "02"), age = c(25, 30)) file_structure_df <- tibble::tribble( ~subid, ~session, ~datatype, ~task, ~run, ~suffix, ~fmriprep, ~desc, "01", NA, "anat", NA, NA, "T1w.nii.gz", FALSE, NA, "01", NA, "func", "taskA", "01", "bold.nii.gz", FALSE, NA, "01", NA, "func", "taskA", "01", "events.tsv", FALSE, NA, "02", "test", "anat", NA, NA, "T1w.nii.gz", FALSE, NA, "02", "test", "func", "taskA", "01", "bold.nii.gz", FALSE, NA, "02", "test", "func", "taskA", "01", "events.tsv", FALSE, NA, # Example derivative "01", NA, "func", "taskA", "01", "preproc_bold.nii.gz", TRUE, "preproc" ) # Define event data (paths must match generated structure) event_data_list <- list() event_data_list[["sub-01/func/sub-01_task-taskA_run-01_events.tsv"]] <- tibble::tibble( onset = c(1.0, 5.0), duration = c(0.5, 0.5), trial_type = c("condA", "condB") ) event_data_list[["sub-02/ses-test/func/sub-02_ses-test_task-taskA_run-01_events.tsv"]] <- tibble::tibble( onset = c(1.5, 5.5), duration = c(0.5, 0.5), trial_type = c("condC", "condD") ) # Create the mock project (in memory only) mock_proj <- create_mock_bids( project_name = "MockTaskA", participants = participants_df, file_structure = file_structure_df, event_data = event_data_list ) # Create the mock project and write stubs mock_proj_stub <- create_mock_bids( project_name = "MockTaskA_stub", participants = c("01", "02"), # Example using just IDs file_structure = file_structure_df, event_data = event_data_list, create_stub = TRUE, stub_path = tempdir() # Use a temporary directory for example ) # --- Using the Mock Project --- print(mock_proj) print(participants(mock_proj)) print(tasks(mock_proj)) print(sessions(mock_proj)) # Should return "test" print(func_scans(mock_proj, subid = "01")) print(event_files(mock_proj, subid = "02", session = "test")) # Read the injected event data events_sub1 <- read_events(mock_proj, subid = "01") print(events_sub1) if (nrow(events_sub1) > 0) print(tidyr::unnest(events_sub1, cols = data)) # Search for derivatives print(search_files(mock_proj, suffix = "preproc_bold.nii.gz")) # Check stub directory (if created) stub_files <- list.files(mock_proj_stub$path, recursive = TRUE) print(head(stub_files)) # Read one injected stub event file if present stub_event_path <- file.path(mock_proj_stub$path, names(event_data_list)[1]) if (file.exists(stub_event_path)) { print(readLines(stub_event_path, n = 1)) } # Cleanup is intentionally omitted in this example.# --- Example Setup --- participants_df <- tibble::tibble(participant_id = c("01", "02"), age = c(25, 30)) file_structure_df <- tibble::tribble( ~subid, ~session, ~datatype, ~task, ~run, ~suffix, ~fmriprep, ~desc, "01", NA, "anat", NA, NA, "T1w.nii.gz", FALSE, NA, "01", NA, "func", "taskA", "01", "bold.nii.gz", FALSE, NA, "01", NA, "func", "taskA", "01", "events.tsv", FALSE, NA, "02", "test", "anat", NA, NA, "T1w.nii.gz", FALSE, NA, "02", "test", "func", "taskA", "01", "bold.nii.gz", FALSE, NA, "02", "test", "func", "taskA", "01", "events.tsv", FALSE, NA, # Example derivative "01", NA, "func", "taskA", "01", "preproc_bold.nii.gz", TRUE, "preproc" ) # Define event data (paths must match generated structure) event_data_list <- list() event_data_list[["sub-01/func/sub-01_task-taskA_run-01_events.tsv"]] <- tibble::tibble( onset = c(1.0, 5.0), duration = c(0.5, 0.5), trial_type = c("condA", "condB") ) event_data_list[["sub-02/ses-test/func/sub-02_ses-test_task-taskA_run-01_events.tsv"]] <- tibble::tibble( onset = c(1.5, 5.5), duration = c(0.5, 0.5), trial_type = c("condC", "condD") ) # Create the mock project (in memory only) mock_proj <- create_mock_bids( project_name = "MockTaskA", participants = participants_df, file_structure = file_structure_df, event_data = event_data_list ) # Create the mock project and write stubs mock_proj_stub <- create_mock_bids( project_name = "MockTaskA_stub", participants = c("01", "02"), # Example using just IDs file_structure = file_structure_df, event_data = event_data_list, create_stub = TRUE, stub_path = tempdir() # Use a temporary directory for example ) # --- Using the Mock Project --- print(mock_proj) print(participants(mock_proj)) print(tasks(mock_proj)) print(sessions(mock_proj)) # Should return "test" print(func_scans(mock_proj, subid = "01")) print(event_files(mock_proj, subid = "02", session = "test")) # Read the injected event data events_sub1 <- read_events(mock_proj, subid = "01") print(events_sub1) if (nrow(events_sub1) > 0) print(tidyr::unnest(events_sub1, cols = data)) # Search for derivatives print(search_files(mock_proj, suffix = "preproc_bold.nii.gz")) # Check stub directory (if created) stub_files <- list.files(mock_proj_stub$path, recursive = TRUE) print(head(stub_files)) # Read one injected stub event file if present stub_event_path <- file.path(mock_proj_stub$path, names(event_data_list)[1]) if (file.exists(stub_event_path)) { print(readLines(stub_event_path, n = 1)) } # Cleanup is intentionally omitted in this example.
Create a preprocessing mask from BIDS data
create_preproc_mask(x, subid, thresh = 0.99, ...)create_preproc_mask(x, subid, thresh = 0.99, ...)
x |
A bids_project object |
subid |
A regular expression pattern to match subject IDs |
thresh |
Threshold value for mask creation (default: 0.99) |
... |
Additional arguments passed to methods |
A logical mask volume
# Download and load a BIDS project with fMRIPrep derivatives tryCatch({ ds001_deriv_path <- get_example_bids_dataset("ds000001-fmriprep") proj <- bids_project(ds001_deriv_path, fmriprep=TRUE) mask <- create_preproc_mask(proj, subid=".*") # Create mask for single subject sub01_mask <- create_preproc_mask(proj, subid="01") # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires derivatives dataset: ", e$message) })# Download and load a BIDS project with fMRIPrep derivatives tryCatch({ ds001_deriv_path <- get_example_bids_dataset("ds000001-fmriprep") proj <- bids_project(ds001_deriv_path, fmriprep=TRUE) mask <- create_preproc_mask(proj, subid=".*") # Create mask for single subject sub01_mask <- create_preproc_mask(proj, subid="01") # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires derivatives dataset: ", e$message) })
This function creates a binary brain mask from preprocessed functional scans
in a BIDS project. It searches for BOLD brain mask files in the fMRIPrep
derivatives directory (i.e., files in the func/ folder matching the
pattern *_desc-brain_mask.nii.gz or the older *_brainmask.nii.gz),
reads them with neuroim2, averages them, and thresholds the result to produce
a consensus binary mask.
## S3 method for class 'bids_project' create_preproc_mask( x, subid, thresh = 0.99, task = ".*", space = ".*", mask_kinds = c("brainmask", "mask"), ... )## S3 method for class 'bids_project' create_preproc_mask( x, subid, thresh = 0.99, task = ".*", space = ".*", mask_kinds = c("brainmask", "mask"), ... )
x |
A |
subid |
Regular expression to match subject IDs (e.g., |
thresh |
Threshold value between 0 and 1 (default 0.99). Voxels below this value in the averaged mask are excluded. Higher values produce more conservative masks. |
task |
Regular expression for task filtering. Defaults to |
space |
Regular expression for output-space filtering (e.g.,
|
mask_kinds |
Character vector of BIDS suffixes to search. Defaults to
both |
... |
Additional arguments passed to |
The search is restricted to functional brain masks by requiring the
task BIDS entity (anatomical masks do not carry task).
When masks from multiple output spaces are discovered the function raises an
error; pass a specific space value to disambiguate.
A logical mask volume (LogicalNeuroVol) suitable for use with
preprocessed functional data.
tryCatch({ ds_path <- get_example_bids_dataset("ds000001-fmriprep") proj <- bids_project(ds_path, fmriprep=TRUE) # Mask for one subject in a specific space mask <- create_preproc_mask(proj, subid="01", space="MNI152NLin2009cAsym") # Consensus mask across all subjects / runs all_mask <- create_preproc_mask(proj, subid=".*", space="MNI152NLin2009cAsym") # Restrict to a single task task_mask <- create_preproc_mask(proj, subid=".*", task="balloonanalogrisktask", space="MNI152NLin2009cAsym") # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires derivatives dataset: ", e$message) })tryCatch({ ds_path <- get_example_bids_dataset("ds000001-fmriprep") proj <- bids_project(ds_path, fmriprep=TRUE) # Mask for one subject in a specific space mask <- create_preproc_mask(proj, subid="01", space="MNI152NLin2009cAsym") # Consensus mask across all subjects / runs all_mask <- create_preproc_mask(proj, subid=".*", space="MNI152NLin2009cAsym") # Restrict to a single task task_mask <- create_preproc_mask(proj, subid=".*", task="balloonanalogrisktask", space="MNI152NLin2009cAsym") # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires derivatives dataset: ", e$message) })
This function is not implemented for mock_bids_project objects as they do not
contain actual image data required to create a mask.
## S3 method for class 'mock_bids_project' create_preproc_mask(x, ...)## S3 method for class 'mock_bids_project' create_preproc_mask(x, ...)
x |
A |
... |
Arguments (ignored). |
Throws an error indicating the function is not applicable to mock objects.
mock <- create_mock_bids("Test", c("01"), tibble::tibble( subid = "01", datatype = "func", suffix = "bold.nii.gz", fmriprep = FALSE )) try(create_preproc_mask(mock))mock <- create_mock_bids("Test", c("01"), tibble::tibble( subid = "01", datatype = "func", suffix = "bold.nii.gz", fmriprep = FALSE )) try(create_preproc_mask(mock))
This creates a transformer function that adds a smoothing description to BIDS filenames. This is a lightweight example - real implementations would perform actual image processing.
create_smooth_transformer(fwhm, suffix_pattern = "bold\\.nii")create_smooth_transformer(fwhm, suffix_pattern = "bold\\.nii")
fwhm |
The smoothing FWHM to add to the description. |
suffix_pattern |
Optional regex pattern to match specific file types. |
A transformer function for use with bids_transform.
# Create a smoothing transformer smooth_6mm <- create_smooth_transformer(6) # Apply it to a toy BIDS-like file path in_dir <- tempdir() out_dir <- tempdir() infile <- file.path(in_dir, "sub-01_task-rest_bold.nii.gz") file.create(infile) new_file <- smooth_6mm(infile, out_dir) basename(new_file) unlink(infile) unlink(new_file)# Create a smoothing transformer smooth_6mm <- create_smooth_transformer(6) # Apply it to a toy BIDS-like file path in_dir <- tempdir() out_dir <- tempdir() infile <- file.path(in_dir, "sub-01_task-rest_bold.nii.gz") file.create(infile) new_file <- smooth_6mm(infile, out_dir) basename(new_file) unlink(infile) unlink(new_file)
Get the dataset_description object from a BIDS project
dataset_description(x, ...) ## S3 method for class 'bids_project' dataset_description(x, ...)dataset_description(x, ...) ## S3 method for class 'bids_project' dataset_description(x, ...)
x |
A |
... |
Additional arguments passed to methods. |
A bids_dataset_description object, or NULL.
tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) desc <- dataset_description(proj) print(desc) # Example datasets are cached; leave the cache in place. }, error = function(e) message("Example requires internet: ", e$message))tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) desc <- dataset_description(proj) print(desc) # Example datasets are cached; leave the cache in place. }, error = function(e) message("Example requires internet: ", e$message))
Get fields from a BIDS dataset description
dataset_name(x, ...) dataset_type(x, ...)dataset_name(x, ...) dataset_type(x, ...)
x |
A |
... |
Additional arguments passed to methods. |
A character scalar.
This function reconstructs a BIDS filename from parsed entities, using the standard BIDS entity ordering.
decode_bids_entities(entities)decode_bids_entities(entities)
entities |
A named list of BIDS entities (from |
A character string representing the BIDS filename.
# Parse a filename and reconstruct it entities <- encode("sub-01_task-rest_run-01_bold.nii.gz") filename <- decode_bids_entities(entities) print(filename) # Modify entities and create new filename entities$desc <- "smooth6mm" new_filename <- decode_bids_entities(entities) print(new_filename)# Parse a filename and reconstruct it entities <- encode("sub-01_task-rest_run-01_bold.nii.gz") filename <- decode_bids_entities(entities) print(filename) # Modify entities and create new filename entities$desc <- "smooth6mm" new_filename <- decode_bids_entities(entities) print(new_filename)
Convenience wrapper around query_files() that restricts results to
derivative pipelines.
derivative_files(x, pipeline = NULL, ...)derivative_files(x, pipeline = NULL, ...)
x |
A |
pipeline |
Optional character vector of pipeline names to include.
When |
... |
Additional arguments passed to |
Character vector of file paths (or tibble when return = "tibble").
tryCatch({ ds_path <- get_example_bids_dataset("ds000001-fmriprep") proj <- bids_project(ds_path, fmriprep = TRUE) df <- derivative_files(proj) # Example datasets are cached; leave the cache in place. }, error = function(e) message("Example requires internet: ", e$message))tryCatch({ ds_path <- get_example_bids_dataset("ds000001-fmriprep") proj <- bids_project(ds_path, fmriprep = TRUE) df <- derivative_files(proj) # Example datasets are cached; leave the cache in place. }, error = function(e) message("Example requires internet: ", e$message))
Returns a tibble describing the derivative pipelines currently attached to a
bids_project. This is the preferred inspection entry point for new code;
legacy fmriprep / prep_dir fields remain available for compatibility.
derivative_pipelines(x)derivative_pipelines(x)
x |
A |
A tibble with one row per derivative pipeline and columns pipeline,
root, description, and source.
tryCatch({ ds_path <- get_example_bids_dataset("ds000001-fmriprep") proj <- bids_project(ds_path, fmriprep = TRUE) derivative_pipelines(proj) # Example datasets are cached; leave the cache in place. }, error = function(e) message("Example requires internet: ", e$message))tryCatch({ ds_path <- get_example_bids_dataset("ds000001-fmriprep") proj <- bids_project(ds_path, fmriprep = TRUE) derivative_pipelines(proj) # Example datasets are cached; leave the cache in place. }, error = function(e) message("Example requires internet: ", e$message))
This function parses a BIDS filename and extracts its components into a key-value list. It understands standard BIDS entities like subject, session, task, run, etc.
encode(x, ...) ## S3 method for class 'character' encode(x, ...)encode(x, ...) ## S3 method for class 'character' encode(x, ...)
x |
The filename string to encode |
... |
Additional arguments passed to methods |
A list of key-value pairs extracted from the filename
# Encode an anatomical file encode("sub-01_T1w.nii.gz") # Encode a functional file encode("sub-01_task-rest_run-01_bold.nii.gz") # Encode a file with session information encode("sub-01_ses-pre_task-rest_run-01_bold.nii.gz")# Encode an anatomical file encode("sub-01_T1w.nii.gz") # Encode a functional file encode("sub-01_task-rest_run-01_bold.nii.gz") # Encode a file with session information encode("sub-01_ses-pre_task-rest_run-01_bold.nii.gz")
This function retrieves a vector of event files (events.tsv) from a BIDS project that match specified criteria. Event files in BIDS contain trial information for task-based functional MRI data, including onset times, durations, and trial types.
Finds event files matching the given subject, task, run, and session criteria.
event_files(x, ...) ## S3 method for class 'bids_project' event_files( x, subid = ".*", task = ".*", run = ".*", session = ".*", full_path = TRUE, ... ) ## S3 method for class 'mock_bids_project' event_files( x, subid = ".*", task = ".*", run = ".*", session = ".*", full_path = TRUE, ... )event_files(x, ...) ## S3 method for class 'bids_project' event_files( x, subid = ".*", task = ".*", run = ".*", session = ".*", full_path = TRUE, ... ) ## S3 method for class 'mock_bids_project' event_files( x, subid = ".*", task = ".*", run = ".*", session = ".*", full_path = TRUE, ... )
x |
A mock_bids_project object |
... |
Additional arguments passed to internal functions |
subid |
Regex to match subject IDs (default: ".*") |
task |
Regex to match tasks (default: ".*") |
run |
Regex to match runs (default: ".*") |
session |
Regex to match sessions (default: ".*") |
full_path |
If TRUE, return full paths of files (default: TRUE) |
A character vector of file paths to event files matching the specified criteria. If no matching files are found, returns NULL.
A character vector of file paths to event files. If no matching files are found, returns an empty character vector.
# Get all event files from a BIDS project tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) event_files(proj) # Get event files for specific subjects and tasks if (length(participants(proj)) > 0) { event_files(proj, subid=participants(proj)[1], task="balloonanalogrisktask") } # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) }) # Get event files for a specific subject and task tryCatch({ ds001_path <- get_example_bids_dataset("ds001") x <- bids_project(ds001_path) files <- event_files(x, subid="01", task="balloonanalogrisktask") # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) })# Get all event files from a BIDS project tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) event_files(proj) # Get event files for specific subjects and tasks if (length(participants(proj)) > 0) { event_files(proj, subid=participants(proj)[1], task="balloonanalogrisktask") } # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) }) # Get event files for a specific subject and task tryCatch({ ds001_path <- get_example_bids_dataset("ds001") x <- bids_project(ds001_path) files <- event_files(x, subid="01", task="balloonanalogrisktask") # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) })
This function matches pairs of related files (e.g., BOLD and event files) in a BIDS project, returning a tibble with matched filenames. It's useful for verifying that corresponding files exist for each subject and task, such as ensuring every BOLD file has an associated events file.
file_pairs( x, pair = c("bold-events", "preproc-events"), task = ".*", matchon = c("run", "task"), ... )file_pairs( x, pair = c("bold-events", "preproc-events"), task = ".*", matchon = c("run", "task"), ... )
x |
A |
pair |
A character string specifying which pair of files to match. Currently supported:
|
task |
A regex pattern to filter tasks. Default is ".*" (no filter). |
matchon |
A character vector of keys to match on, usually c("run", "task"). |
... |
Additional arguments passed to internal functions. |
A tibble with columns:
subid: The subject ID
task: The task name
[type1]: The name of the first file type (e.g., "bold" or "preproc")
[type2]: The matched file of the second type (e.g., "events"), or NA if no match found
Additional columns for matched metadata (e.g., run, session)
# Create a BIDS project object tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) # Match BOLD files with their corresponding event files bold_pairs <- file_pairs(proj, pair="bold-events") # Check pairs for a specific task task_pairs <- file_pairs(proj, pair="bold-events", task="balloonanalogrisktask") # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) })# Create a BIDS project object tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) # Match BOLD files with their corresponding event files bold_pairs <- file_pairs(proj, pair="bold-events") # Check pairs for a specific task task_pairs <- file_pairs(proj, pair="bold-events", task="balloonanalogrisktask") # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) })
This function returns a flattened (non-hierarchical) representation of a BIDS project formatted as a data frame. It extracts file paths or file names from the BIDS tree structure, filtering for entries that start with "sub-" to focus on subject-level data.
flat_list(x, ...) ## S3 method for class 'bids_project' flat_list(x, full_path = TRUE, ...)flat_list(x, ...) ## S3 method for class 'bids_project' flat_list(x, full_path = TRUE, ...)
x |
the |
... |
extra args passed to methods |
full_path |
If TRUE, return full paths to files; if FALSE, return just file names (default: TRUE) |
A data frame containing either full paths to files (if full_path=TRUE) or
just the file names (if full_path=FALSE). Each row represents one file in the BIDS project.
# Get flat representation with full paths tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) flat_list(proj) # Get flat representation with just file names flat_list(proj, full_path=FALSE) # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) })# Get flat representation with full paths tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) flat_list(proj) # Get flat representation with just file names flat_list(proj, full_path=FALSE) # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) })
Fieldmap parser constructor
fmap_parser()fmap_parser()
A fieldmap BIDS parser object for parsing fieldmap files
# Create a fieldmap parser parser <- fmap_parser() # Parse a fieldmap file result <- parse(parser, "sub-01_magnitude1.nii.gz")# Create a fieldmap parser parser <- fmap_parser() # Parse a fieldmap file result <- parse(parser, "sub-01_magnitude1.nii.gz")
fMRIPrep anatomical parser constructor
fmriprep_anat_parser()fmriprep_anat_parser()
An fMRIPrep anatomical parser object for parsing preprocessed anatomical files
# Create an fMRIPrep anatomical parser parser <- fmriprep_anat_parser() # Parse a preprocessed anatomical file result <- parse(parser, "sub-01_space-MNI152NLin2009cAsym_desc-preproc_T1w.nii.gz")# Create an fMRIPrep anatomical parser parser <- fmriprep_anat_parser() # Parse a preprocessed anatomical file result <- parse(parser, "sub-01_space-MNI152NLin2009cAsym_desc-preproc_T1w.nii.gz")
fMRIPrep functional parser constructor
fmriprep_func_parser()fmriprep_func_parser()
An fMRIPrep functional parser object for parsing preprocessed functional files
# Create an fMRIPrep functional parser parser <- fmriprep_func_parser() # Parse a preprocessed functional file result <- parse(parser, "sub-01_task-rest_space-MNI152NLin2009cAsym_desc-preproc_bold.nii.gz")# Create an fMRIPrep functional parser parser <- fmriprep_func_parser() # Parse a preprocessed functional file result <- parse(parser, "sub-01_task-rest_space-MNI152NLin2009cAsym_desc-preproc_bold.nii.gz")
Functional parser constructor
func_parser()func_parser()
A functional BIDS parser object for parsing functional MRI files
# Create a functional parser parser <- func_parser() # Parse a functional file result <- parse(parser, "sub-01_task-rest_run-01_bold.nii.gz")# Create a functional parser parser <- func_parser() # Parse a functional file result <- parse(parser, "sub-01_task-rest_run-01_bold.nii.gz")
This function extracts functional scan files from a BIDS project that match specified criteria such as subject ID, task name, run number, and session. It can return either full paths or relative paths to the files.
func_scans(x, ...) ## S3 method for class 'mock_bids_project' func_scans( x, subid = ".*", task = ".*", run = ".*", session = ".*", kind = "bold", suffix = "nii(\\.gz)?$", full_path = TRUE, ... )func_scans(x, ...) ## S3 method for class 'mock_bids_project' func_scans( x, subid = ".*", task = ".*", run = ".*", session = ".*", kind = "bold", suffix = "nii(\\.gz)?$", full_path = TRUE, ... )
x |
A mock_bids_project object |
... |
Additional arguments passed to search_files |
subid |
Regex to match subject IDs (default: ".*") |
task |
Regex to match tasks (default: ".*") |
run |
Regex to match runs (default: ".*") |
session |
Regex to match sessions (default: ".*") |
kind |
Type of functional data (default: "bold") |
suffix |
Regex pattern for file suffix (default: "nii(\.gz)?$") |
full_path |
If TRUE, return full file paths (default: TRUE) |
A character vector of file paths to functional scans matching the criteria. Returns NULL if no matching files are found.
# Create a BIDS project object tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) # Get all functional scans all_scans <- func_scans(proj) # Get scans for specific subjects if (length(participants(proj)) > 0) { sub_scans <- func_scans(proj, subid=participants(proj)[1]) } # Get scans for a specific task and run if (length(tasks(proj)) > 0) { task_scans <- func_scans(proj, task=tasks(proj)[1], run="01") } # Get scans with relative paths rel_scans <- func_scans(proj, full_path=FALSE) # Also try with a dataset that has sessions ds007_path <- get_example_bids_dataset("ds007") ds007_proj <- bids_project(ds007_path) if (length(sessions(ds007_proj)) > 0) { session_scans <- func_scans(ds007_proj, session=sessions(ds007_proj)[1]) } # Clean up # Example datasets are cached; leave the cache in place. unlink(ds007_path, recursive=TRUE) }, error = function(e) { message("Example requires internet connection: ", e$message) })# Create a BIDS project object tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) # Get all functional scans all_scans <- func_scans(proj) # Get scans for specific subjects if (length(participants(proj)) > 0) { sub_scans <- func_scans(proj, subid=participants(proj)[1]) } # Get scans for a specific task and run if (length(tasks(proj)) > 0) { task_scans <- func_scans(proj, task=tasks(proj)[1], run="01") } # Get scans with relative paths rel_scans <- func_scans(proj, full_path=FALSE) # Also try with a dataset that has sessions ds007_path <- get_example_bids_dataset("ds007") ds007_proj <- bids_project(ds007_path) if (length(sessions(ds007_proj)) > 0) { session_scans <- func_scans(ds007_proj, session=sessions(ds007_proj)[1]) } # Clean up # Example datasets are cached; leave the cache in place. unlink(ds007_path, recursive=TRUE) }, error = function(e) { message("Example requires internet connection: ", e$message) })
This method extracts functional scan files from a BIDS project based on specified criteria such as subject ID, task name, run number, and session. It can return either full or relative file paths to the functional scans.
## S3 method for class 'bids_project' func_scans( x, subid = ".*", task = ".*", run = ".*", session = ".*", kind = "bold", full_path = TRUE, ... )## S3 method for class 'bids_project' func_scans( x, subid = ".*", task = ".*", run = ".*", session = ".*", kind = "bold", full_path = TRUE, ... )
x |
A |
subid |
Regular expression for matching subject IDs. Default is ".*". |
task |
Regular expression for matching task names. Default is ".*". |
run |
Regular expression for matching run numbers. Default is ".*". |
session |
Regular expression for matching session IDs. Default is ".*". |
kind |
Regular expression for matching scan type. Default is "bold". |
full_path |
Logical. If TRUE, return full file paths. If FALSE, return relative paths. Default is TRUE. |
... |
Additional arguments (not currently used). |
A character vector of file paths to functional scans matching the criteria. Returns NULL if:
No matching files are found
The project doesn't contain functional data
The specified criteria don't match any files
# Create a BIDS project tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) # Get all functional scans all_scans <- func_scans(proj) # Get scans for specific subjects sub_scans <- func_scans(proj, subid="0[123]") # Get scans for a specific task task_scans <- func_scans(proj, task="rest") # Get scans from specific runs run_scans <- func_scans(proj, run="0[123]") # Combine multiple filters filtered_scans <- func_scans(proj, subid="01", task="rest", run="01") # Get relative paths instead of full paths rel_scans <- func_scans(proj, full_path=FALSE) # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) })# Create a BIDS project tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) # Get all functional scans all_scans <- func_scans(proj) # Get scans for specific subjects sub_scans <- func_scans(proj, subid="0[123]") # Get scans for a specific task task_scans <- func_scans(proj, task="rest") # Get scans from specific runs run_scans <- func_scans(proj, run="0[123]") # Combine multiple filters filtered_scans <- func_scans(proj, subid="01", task="rest", run="01") # Get relative paths instead of full paths rel_scans <- func_scans(proj, full_path=FALSE) # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) })
Converts a parser_spec list (as returned by bids_datatype_spec
or the internal func_spec() etc.) into a parser object suitable for
passing to register_datatype.
gen_parser(spec, typename = "kind")gen_parser(spec, typename = "kind")
spec |
A |
typename |
The name given to the final type element. Default is
|
A regex-based parser object.
bids_datatype_spec, register_datatype
spec <- bids_datatype_spec( type = "dwi", entities = c("sub", "ses", "acq", "run"), suffixes = list(dwi = c(".nii.gz", ".nii", ".bvec", ".bval", ".json")) ) parser <- gen_parser(spec)spec <- bids_datatype_spec( type = "dwi", entities = c("sub", "ses", "acq", "run"), suffixes = list(dwi = c(".nii.gz", ".nii", ".bvec", ".bval", ".json")) ) parser <- gen_parser(spec)
Downloads and extracts an example BIDS dataset for testing and demonstration purposes. The datasets are sourced from the official BIDS examples repository on GitHub.
get_example_bids_dataset(dataset_name = "ds001")get_example_bids_dataset(dataset_name = "ds001")
dataset_name |
Character string specifying which dataset to download. Common options include "ds001", "ds002", "ds007", "phoneme_stripped", etc. |
This function requires an internet connection to download data from GitHub.
The datasets are cached in the temporary directory AND in memory for the session,
so repeated calls with the same dataset_name will reuse the already downloaded data.
Note: Don't call unlink() on the returned path in examples, as this defeats
the caching mechanism and forces re-downloads.
Character string containing the path to the downloaded dataset directory.
tryCatch({ ds_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds_path) print(participants(proj)) # Dataset cache is intentionally retained for performance. }, error = function(e) { message("Example requires internet connection: ", e$message) })tryCatch({ ds_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds_path) print(participants(proj)) # Dataset cache is intentionally retained for performance. }, error = function(e) { message("Example requires internet connection: ", e$message) })
Retrieves JSON metadata for a target BIDS file. When inherit = TRUE, this
method applies BIDS-style inheritance by merging matching sidecars from less
specific to more specific locations.
get_metadata( x, file, inherit = TRUE, scope = c("auto", "raw", "derivatives", "all"), ... ) ## S3 method for class 'bids_project' get_metadata( x, file, inherit = TRUE, scope = c("auto", "raw", "derivatives", "all"), ... )get_metadata( x, file, inherit = TRUE, scope = c("auto", "raw", "derivatives", "all"), ... ) ## S3 method for class 'bids_project' get_metadata( x, file, inherit = TRUE, scope = c("auto", "raw", "derivatives", "all"), ... )
x |
A |
file |
Target file path (relative to project root or absolute path). |
inherit |
If |
scope |
Scope used when applying inheritance:
|
... |
Additional arguments for methods. |
If multiple sidecars are equally specific at the same directory depth, they are merged in deterministic path order after less specific ancestors, so the final values are reproducible.
A named list of metadata fields.
tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) f <- func_scans(proj, subid = "01")[1] if (!is.null(f)) get_metadata(proj, f) # Example datasets are cached; leave the cache in place. }, error = function(e) message("Example requires internet: ", e$message))tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) f <- func_scans(proj, subid = "01")[1] if (!is.null(f)) get_metadata(proj, f) # Example datasets are cached; leave the cache in place. }, error = function(e) message("Example requires internet: ", e$message))
This function attempts to find and return the repetition time (TR) for a given subject, task, and run (and optionally session) by locating the associated BOLD sidecar JSON file and extracting the 'RepetitionTime' field. If not found, returns NA.
get_repetition_time(x, subid, task, run = ".*", session = ".*", ...)get_repetition_time(x, subid, task, run = ".*", session = ".*", ...)
x |
A |
subid |
Subject ID (exact or regex). |
task |
Task name (exact or regex). |
run |
Run number (exact or regex). Default is ".*" to allow flexible matching. |
session |
Session ID (exact or regex). Default is ".*". |
... |
Additional arguments passed to |
A numeric value representing the RepetitionTime in seconds, or NA if not found.
# Download and get TR for a specific subject and task tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) if (length(participants(proj)) > 0 && length(tasks(proj)) > 0) { tr <- get_repetition_time(proj, subid=participants(proj)[1], task=tasks(proj)[1]) cat("TR:", tr, "seconds\n") } # Try with a dataset that has sessions ds007_path <- get_example_bids_dataset("ds007") ds007_proj <- bids_project(ds007_path) if (length(participants(ds007_proj)) > 0 && length(sessions(ds007_proj)) > 0) { tr_session <- get_repetition_time(ds007_proj, subid=participants(ds007_proj)[1], session=sessions(ds007_proj)[1]) cat("TR with session:", tr_session, "seconds\n") } # Clean up # Example datasets are cached; leave the cache in place. unlink(ds007_path, recursive=TRUE) }, error = function(e) { message("Example requires internet connection: ", e$message) })# Download and get TR for a specific subject and task tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) if (length(participants(proj)) > 0 && length(tasks(proj)) > 0) { tr <- get_repetition_time(proj, subid=participants(proj)[1], task=tasks(proj)[1]) cat("TR:", tr, "seconds\n") } # Try with a dataset that has sessions ds007_path <- get_example_bids_dataset("ds007") ds007_proj <- bids_project(ds007_path) if (length(participants(ds007_proj)) > 0 && length(sessions(ds007_proj)) > 0) { tr_session <- get_repetition_time(ds007_proj, subid=participants(ds007_proj)[1], session=sessions(ds007_proj)[1]) cat("TR with session:", tr_session, "seconds\n") } # Clean up # Example datasets are cached; leave the cache in place. unlink(ds007_path, recursive=TRUE) }, error = function(e) { message("Example requires internet connection: ", e$message) })
Given a path to a BOLD NIfTI file (*.nii or *.nii.gz) or its JSON
sidecar (*.json), this function locates the appropriate sidecar JSON and
returns the TR (in seconds). It prefers the JSON RepetitionTime field
(BIDS-compliant). If that is not available, it falls back to computing TR as
the median difference of VolumeTiming (if present). Optionally, when the
sidecar cannot be found or is missing both fields, the function attempts to
read TR from the NIfTI header (pixdim[4]) if an appropriate reader is
installed.
infer_tr(x, ...) ## S3 method for class 'character' infer_tr( x, prefer = c("json", "nifti"), fallback = TRUE, coerce_units = c("strict", "auto"), verbose = FALSE, ... )infer_tr(x, ...) ## S3 method for class 'character' infer_tr( x, prefer = c("json", "nifti"), fallback = TRUE, coerce_units = c("strict", "auto"), verbose = FALSE, ... )
x |
A character path to a BOLD |
... |
Additional arguments passed to methods. |
prefer |
Preferred source of TR: |
fallback |
If TRUE (default), attempt NIfTI header fallback when JSON is not available or incomplete. |
coerce_units |
Unit handling for non-compliant values. |
verbose |
If TRUE, print informative messages when falling back or when encountering special cases (e.g., SBRef files). |
For NIfTI inputs, the JSON sidecar is resolved by replacing the
*.nii/*.nii.gz suffix with .json in the same directory. If that file is
not found, the function searches the directory for a .json file with the
same stem (filename without the NIfTI extension).
Numeric TR in seconds, or NA_real_ if it cannot be determined. The
return value includes attributes: source (e.g., json:RepetitionTime,
json:VolumeTiming, nifti:pixdim4), path (the file used), and
optionally variable = TRUE if VolumeTiming indicates non-constant TR; a
unit = "ms->s" attribute is added if units were auto-converted.
tmp_json <- tempfile(fileext = ".json") writeLines('{"RepetitionTime": 2}', tmp_json) infer_tr(tmp_json) unlink(tmp_json) tmp_json2 <- tempfile(fileext = ".json") writeLines('{"VolumeTiming": [0, 2, 4, 6]}', tmp_json2) infer_tr(tmp_json2) unlink(tmp_json2)tmp_json <- tempfile(fileext = ".json") writeLines('{"RepetitionTime": 2}', tmp_json) infer_tr(tmp_json) unlink(tmp_json) tmp_json2 <- tempfile(fileext = ".json") writeLines('{"VolumeTiming": [0, 2, 4, 6]}', tmp_json2) infer_tr(tmp_json2) unlink(tmp_json2)
Test whether an object is a BIDS URI
is_bids_uri(x)is_bids_uri(x)
x |
Any object. |
TRUE if x inherits from "bids_uri", FALSE otherwise.
u <- bids_uri("bids::sub-01/anat/sub-01_T1w.nii.gz") is_bids_uri(u) # TRUE is_bids_uri("bids::sub-01/anat/sub-01_T1w.nii.gz") # FALSEu <- bids_uri("bids::sub-01/anat/sub-01_T1w.nii.gz") is_bids_uri(u) # TRUE is_bids_uri("bids::sub-01/anat/sub-01_T1w.nii.gz") # FALSE
Returns the names and short descriptions of the predefined confound sets
usable with confound_set().
list_confound_sets()list_confound_sets()
A data.frame with columns set and description.
list_confound_sets()list_confound_sets()
Returns the names and short descriptions of the predefined confound
strategies usable with confound_strategy().
list_confound_strategies()list_confound_strategies()
A data.frame with columns strategy and description.
list_confound_strategies()list_confound_strategies()
Returns the names of all datatypes currently registered in the bidser runtime registry.
list_datatypes(scope = c("all", "raw", "derivative", "both"))list_datatypes(scope = c("all", "raw", "derivative", "both"))
scope |
One of |
A character vector of datatype names.
list_datatypes() list_datatypes(scope = "raw")list_datatypes() list_datatypes(scope = "raw")
This function lists the contents of a BIDS archive created by pack_bids,
showing file sizes and identifying which files are stubs.
list_pack_bids(archive_path, verbose = TRUE)list_pack_bids(archive_path, verbose = TRUE)
archive_path |
Character string specifying the path to the archive file. |
verbose |
Logical. Whether to print summary statistics. Default is TRUE. |
A data frame with columns:
file |
Relative file path within the archive |
size |
File size in bytes |
is_stub |
Logical indicating if the file is a 0-byte stub |
is_downsampled |
Logical indicating if the file is a downsampled image |
type |
File type based on extension (imaging, imaging_stub, imaging_downsampled, json, tsv, etc.) |
# Create and inspect a packed BIDS archive tryCatch({ ds_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds_path) archive_path <- pack_bids(proj, verbose = FALSE) # List contents contents <- list_pack_bids(archive_path) # Show stub files stub_files <- contents[contents$is_stub, ] print(head(stub_files)) # Clean up unlink(archive_path) # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example failed: ", e$message) })# Create and inspect a packed BIDS archive tryCatch({ ds_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds_path) archive_path <- pack_bids(proj, verbose = FALSE) # List contents contents <- list_pack_bids(archive_path) # Show stub files stub_files <- contents[contents$is_stub, ] print(head(stub_files)) # Clean up unlink(archive_path) # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example failed: ", e$message) })
Searches for and reads event files (events.tsv) from a BIDS
project, combining them into a single (potentially nested) tibble.
This function searches for all events.tsv files that match the provided
filters (subid, task, run, session) and loads them into a single tibble.
If full_path=TRUE, full file paths are returned; otherwise relative paths.
load_all_events(x, ...) ## S3 method for class 'bids_project' load_all_events( x, subid = ".*", task = ".*", run = ".*", session = ".*", full_path = TRUE, ... )load_all_events(x, ...) ## S3 method for class 'bids_project' load_all_events( x, subid = ".*", task = ".*", run = ".*", session = ".*", full_path = TRUE, ... )
x |
A |
... |
Additional arguments passed on to |
subid |
A regex for matching participant IDs. Default is |
task |
A regex for matching tasks. Default is |
run |
A regex for matching runs. Default is |
session |
A regex for matching sessions. Default is |
full_path |
If TRUE, return full file paths before reading. Default is TRUE. |
A tibble containing the combined event data.
A tibble combining all matched event files, with columns .subid, .task, .run, .session
and all event columns. If no events are found, returns an empty tibble.
# Example with a bids_project (assuming events exist) tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) all_events <- load_all_events(proj) print(all_events) # Load specific subject/task if (length(participants(proj)) > 0) { sub01_events <- load_all_events(proj, subid=participants(proj)[1], task="balloonanalogrisktask") print(sub01_events) } # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) })# Example with a bids_project (assuming events exist) tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) all_events <- load_all_events(proj) print(all_events) # Load specific subject/task if (length(participants(proj)) > 0) { sub01_events <- load_all_events(proj, subid=participants(proj)[1], task="balloonanalogrisktask") print(sub01_events) } # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) })
Retrieves paths to brain mask files from a BIDS project, optionally filtered by subject, session, and coordinate space. Mask files are typically found in fMRIPrep derivatives and include brain masks and tissue segmentation masks.
mask_files( x, subid = ".*", session = ".*", space = ".*", full_path = TRUE, ... ) ## S3 method for class 'bids_project' mask_files( x, subid = ".*", session = ".*", space = ".*", full_path = TRUE, ... ) ## S3 method for class 'mock_bids_project' mask_files( x, subid = ".*", session = ".*", space = ".*", full_path = TRUE, ... )mask_files( x, subid = ".*", session = ".*", space = ".*", full_path = TRUE, ... ) ## S3 method for class 'bids_project' mask_files( x, subid = ".*", session = ".*", space = ".*", full_path = TRUE, ... ) ## S3 method for class 'mock_bids_project' mask_files( x, subid = ".*", session = ".*", space = ".*", full_path = TRUE, ... )
x |
A |
subid |
Regex pattern to match subject IDs (without "sub-" prefix).
Default |
session |
Regex pattern to match session IDs (without "ses-" prefix).
Default |
space |
Regex pattern to match coordinate space (e.g., |
full_path |
Logical. If |
... |
Additional arguments passed to |
Character vector of file paths matching the criteria, or NULL if
no matching files are found.
# Get all mask files tryCatch({ ds_path <- get_example_bids_dataset("ds000001-fmriprep") proj <- bids_project(ds_path, fmriprep = TRUE) # All masks all_masks <- mask_files(proj) # Masks in MNI space mni_masks <- mask_files(proj, space = "MNI152") # Masks for specific subject sub01_masks <- mask_files(proj, subid = "01") # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) })# Get all mask files tryCatch({ ds_path <- get_example_bids_dataset("ds000001-fmriprep") proj <- bids_project(ds_path, fmriprep = TRUE) # All masks all_masks <- mask_files(proj) # Masks in MNI space mni_masks <- mask_files(proj, space = "MNI152") # Masks for specific subject sub01_masks <- mask_files(proj, subid = "01") # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) })
This function creates a compressed archive (tar.gz or zip) of a BIDS project, either replacing large imaging files (.nii, .nii.gz) with 0-byte stub files or downsampling them to lower resolution while preserving all metadata files (JSON, TSV, etc.) with their full content. This is useful for sharing BIDS project structure and metadata without the large imaging data.
pack_bids( x, output_file = NULL, format = NULL, include_derivatives = TRUE, downsample_factor = NULL, downsample_method = "box", ncores = 1, max_file_size = "10MB", exclude = NULL, strict_bids = FALSE, verbose = TRUE, temp_dir = NULL, cleanup = TRUE )pack_bids( x, output_file = NULL, format = NULL, include_derivatives = TRUE, downsample_factor = NULL, downsample_method = "box", ncores = 1, max_file_size = "10MB", exclude = NULL, strict_bids = FALSE, verbose = TRUE, temp_dir = NULL, cleanup = TRUE )
x |
A |
output_file |
Character string specifying the output archive filename.
Should end with ".tar.gz" or ".zip". If not specified, defaults to
|
format |
Character string specifying the archive format. Can be "tar.gz" (default) or "zip". If not specified, inferred from output_file extension. |
include_derivatives |
Logical. Whether to include fMRIPrep derivatives if available. Default is TRUE. |
downsample_factor |
Numeric value between 0 and 1 specifying the downsampling factor for imaging files. If NULL (default), creates stub files. A value of 0.25 reduces dimensions by 4x (e.g., 64x64x64 becomes 16x16x16). Time dimension is preserved for 4D files. |
downsample_method |
Character string specifying the downsampling method. Currently only "box" (box averaging) is supported. Default is "box". |
ncores |
Integer specifying the number of cores for parallel processing during downsampling. Default is 1 (sequential). Values > 1 enable parallel processing if the 'future' package is available. |
max_file_size |
Character string or numeric value specifying the maximum file size for non-imaging files to include. Files larger than this will be replaced with stub files. Can be specified as "1MB", "500KB", "1.5GB" or as numeric bytes. Default is "10MB". |
exclude |
Character string with a regular expression pattern to exclude files. Files matching this pattern will be replaced with stub files. For example, "\.h5$" to exclude HDF5 files. Default is NULL (no exclusion). |
strict_bids |
Logical. If TRUE, only include files that match BIDS naming conventions and standard BIDS metadata files. Non-BIDS files like .DS_Store, temporary files, or other non-standard files will be excluded. Default is FALSE (include all files). |
verbose |
Logical. Whether to print progress messages. Default is TRUE. |
temp_dir |
Character string specifying the temporary directory for creating the archive. If NULL (default), uses tempdir(). |
cleanup |
Logical. Whether to clean up the temporary directory after creating the archive. Default is TRUE. |
The function works by:
Creating a temporary copy of the BIDS project structure
Replacing all .nii and .nii.gz files with 0-byte stub files
Preserving all other files (JSON, TSV, TXT, etc.) with full content
Creating a compressed archive of the modified structure
This allows researchers to share BIDS dataset structure and metadata without the large imaging files, which is useful for:
Sharing dataset organization and metadata for review
Creating lightweight references for dataset structure
Testing BIDS tools without full datasets
Character string containing the path to the created archive file. Returns NULL if the operation fails.
# Create a BIDS project and pack it tryCatch({ ds_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds_path) # Pack with default settings (tar.gz with stub files) archive_path <- pack_bids(proj) # Pack with size limit and exclusion pattern archive_filtered <- pack_bids(proj, max_file_size = "1MB", exclude = "\\.h5$", output_file = "ds001_filtered.tar.gz") # Pack with downsampling (4x reduction) archive_downsampled <- pack_bids(proj, downsample_factor = 0.25, output_file = "ds001_low4x.tar.gz") # Pack with downsampling using parallel processing if (requireNamespace("future", quietly = TRUE)) { archive_parallel <- pack_bids(proj, downsample_factor = 0.5, ncores = 2, output_file = "ds001_low2x.tar.gz") } # Pack as zip file zip_path <- pack_bids(proj, output_file = "ds001_metadata.zip") # Pack without derivatives archive_no_deriv <- pack_bids(proj, include_derivatives = FALSE) # Pack with strict BIDS mode (exclude non-BIDS files) archive_strict <- pack_bids(proj, strict_bids = TRUE, output_file = "ds001_strict.tar.gz") # Clean up unlink(c(archive_path, archive_filtered, archive_downsampled, zip_path, archive_no_deriv, archive_strict)) if (exists("archive_parallel")) unlink(archive_parallel) # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example failed: ", e$message) })# Create a BIDS project and pack it tryCatch({ ds_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds_path) # Pack with default settings (tar.gz with stub files) archive_path <- pack_bids(proj) # Pack with size limit and exclusion pattern archive_filtered <- pack_bids(proj, max_file_size = "1MB", exclude = "\\.h5$", output_file = "ds001_filtered.tar.gz") # Pack with downsampling (4x reduction) archive_downsampled <- pack_bids(proj, downsample_factor = 0.25, output_file = "ds001_low4x.tar.gz") # Pack with downsampling using parallel processing if (requireNamespace("future", quietly = TRUE)) { archive_parallel <- pack_bids(proj, downsample_factor = 0.5, ncores = 2, output_file = "ds001_low2x.tar.gz") } # Pack as zip file zip_path <- pack_bids(proj, output_file = "ds001_metadata.zip") # Pack without derivatives archive_no_deriv <- pack_bids(proj, include_derivatives = FALSE) # Pack with strict BIDS mode (exclude non-BIDS files) archive_strict <- pack_bids(proj, strict_bids = TRUE, output_file = "ds001_strict.tar.gz") # Clean up unlink(c(archive_path, archive_filtered, archive_downsampled, zip_path, archive_no_deriv, archive_strict)) if (exists("archive_parallel")) unlink(archive_parallel) # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example failed: ", e$message) })
This generic function parses a BIDS filename into its component parts. It uses a parser combinator approach to match the filename against known BIDS patterns and extract relevant metadata such as subject ID, session, task, run, and modality.
parse(x, fname, ...)parse(x, fname, ...)
x |
the parser object to use for parsing |
fname |
the string (filename) to parse |
... |
extra args passed to methods |
A parsed representation of the BIDS filename, typically a list with extracted components
# Parse an anatomical file parser <- anat_parser() parse(parser, "sub-01_T1w.nii.gz") # Parse a functional file parser <- func_parser() parse(parser, "sub-01_task-rest_run-01_bold.nii.gz") # Use the generic BIDS parser parser <- bids_parser() parse(parser, "sub-01_ses-pre_task-rest_run-01_bold.nii.gz")# Parse an anatomical file parser <- anat_parser() parse(parser, "sub-01_T1w.nii.gz") # Parse a functional file parser <- func_parser() parse(parser, "sub-01_task-rest_run-01_bold.nii.gz") # Use the generic BIDS parser parser <- bids_parser() parse(parser, "sub-01_ses-pre_task-rest_run-01_bold.nii.gz")
Retrieves participant information from a BIDS project. By default returns
a sorted character vector of unique participant IDs (without the "sub-"
prefix).
participants(x, ...) ## S3 method for class 'bids_project' participants(x, as_tibble = FALSE, ...)participants(x, ...) ## S3 method for class 'bids_project' participants(x, as_tibble = FALSE, ...)
x |
the |
... |
extra args passed to methods |
as_tibble |
Logical.
If |
When as_tibble = TRUE, a tibble is returned instead containing the full
participants.tsv data (or inferred IDs when the file is missing) plus a
source column indicating whether each ID came from the "table" or the
"filesystem".
A character vector of unique participant IDs, or a tibble when
as_tibble = TRUE.
# Get participants from a BIDS project tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) participants(proj) # Get full tibble with provenance participants(proj, as_tibble = TRUE) # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) })# Get participants from a BIDS project tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) participants(proj) # Get full tibble with provenance participants(proj, as_tibble = TRUE) # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) })
Extracts the unique participant IDs from the mock project definition.
Note: Returns IDs without the "sub-" prefix for consistency with bids_project methods.
## S3 method for class 'mock_bids_project' participants(x, as_tibble = FALSE, ...)## S3 method for class 'mock_bids_project' participants(x, as_tibble = FALSE, ...)
x |
A |
as_tibble |
If |
... |
Extra arguments (ignored). |
Character vector of unique participant IDs (e.g., c("01", "02")), sorted.
If as_tibble = TRUE, a tibble with participant metadata.
# Create a mock project parts <- data.frame(participant_id = c("sub-01", "sub-02")) fs <- data.frame(subid=c("01", "02"), datatype="func", suffix="bold.nii.gz", fmriprep=FALSE) mock_proj <- create_mock_bids("SimpleMock", parts, fs) # Get participant IDs participants(mock_proj)# Create a mock project parts <- data.frame(participant_id = c("sub-01", "sub-02")) fs <- data.frame(subid=c("01", "02"), datatype="func", suffix="bold.nii.gz", fmriprep=FALSE) mock_proj <- create_mock_bids("SimpleMock", parts, fs) # Get participant IDs participants(mock_proj)
This function creates a multi-panel visualization of a BIDS project structure, showing file distributions, completeness, and data characteristics.
plot_bids( x, interactive = TRUE, color_scheme = "viridis", include_derivatives = TRUE, file_size_scale = "log", highlight_missing = TRUE, visualization_mode = "standard", debug = FALSE )plot_bids( x, interactive = TRUE, color_scheme = "viridis", include_derivatives = TRUE, file_size_scale = "log", highlight_missing = TRUE, visualization_mode = "standard", debug = FALSE )
x |
A |
interactive |
Logical. Whether to create an interactive plot (default TRUE) |
color_scheme |
Character. Name of the color palette to use (default "viridis") |
include_derivatives |
Logical. Whether to include derivatives data in the visualization (default TRUE) |
file_size_scale |
Character. Whether to scale file sizes ("log", "sqrt", or "linear", default "log") |
highlight_missing |
Logical. Whether to highlight missing data points (default TRUE) |
visualization_mode |
Character. The mode of visualization to use ("standard", "heatmap", or "complete") |
debug |
Logical. Whether to print debugging information (default FALSE) |
A plot object (ggplot2, plotly, or other depending on settings)
# Create a basic BIDS project and plot it tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) plot_bids(proj) # Create an interactive plot plot_bids(proj, interactive=TRUE) # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) })# Create a basic BIDS project and plot it tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) plot_bids(proj) # Create an interactive plot plot_bids(proj, interactive=TRUE) # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) })
Visualize principal component scores and loadings returned by
read_confounds(..., npcs = ...). When multiple runs are present,
the default view facets per run for scores (up to max_panels) and
aggregates loadings across runs.
## S3 method for class 'bids_confounds' plot( x, view = c("auto", "run", "aggregate"), pcs = NULL, top_n = 8, max_panels = 6, ... )## S3 method for class 'bids_confounds' plot( x, view = c("auto", "run", "aggregate"), pcs = NULL, top_n = 8, max_panels = 6, ... )
x |
A |
view |
Character. One of |
pcs |
Integer or character vector of PCs to plot (e.g., |
top_n |
Integer. Keep the top |
max_panels |
Integer. In |
... |
Unused. |
A ggplot object, or a list of ggplot objects when patchwork is not available.
parts <- c("01", "02") fs <- tibble::tibble( subid = rep(c("01", "02"), each = 2), datatype = "func", suffix = rep(c("bold.nii.gz", "desc-confounds_timeseries.tsv"), 2), task = "rest", fmriprep = TRUE ) conf_data <- list() for (p in parts) { key <- paste0("derivatives/fmriprep/sub-", p, "/func/sub-", p, "_task-rest_desc-confounds_timeseries.tsv") conf_data[[key]] <- data.frame( csf = rnorm(100), white_matter = rnorm(100), global_signal = rnorm(100), framewise_displacement = abs(rnorm(100)), trans_x = rnorm(100), trans_y = rnorm(100), trans_z = rnorm(100), rot_x = rnorm(100), rot_y = rnorm(100), rot_z = rnorm(100) ) } mock <- create_mock_bids("ConfPlot", parts, fs, confound_data = conf_data) conf <- read_confounds(mock, npcs = 3) if (requireNamespace("ggplot2", quietly = TRUE)) { plot(conf) }parts <- c("01", "02") fs <- tibble::tibble( subid = rep(c("01", "02"), each = 2), datatype = "func", suffix = rep(c("bold.nii.gz", "desc-confounds_timeseries.tsv"), 2), task = "rest", fmriprep = TRUE ) conf_data <- list() for (p in parts) { key <- paste0("derivatives/fmriprep/sub-", p, "/func/sub-", p, "_task-rest_desc-confounds_timeseries.tsv") conf_data[[key]] <- data.frame( csf = rnorm(100), white_matter = rnorm(100), global_signal = rnorm(100), framewise_displacement = abs(rnorm(100)), trans_x = rnorm(100), trans_y = rnorm(100), trans_z = rnorm(100), rot_x = rnorm(100), rot_y = rnorm(100), rot_z = rnorm(100) ) } mock <- create_mock_bids("ConfPlot", parts, fs, confound_data = conf_data) conf <- read_confounds(mock, npcs = 3) if (requireNamespace("ggplot2", quietly = TRUE)) { plot(conf) }
This method visualises the hierarchical file structure of a BIDS project. The tree is converted to a dendrogram and drawn using base graphics. Large projects can be trimmed by setting a maximum depth.
## S3 method for class 'bids_project' plot(x, max_depth = Inf, ...) ## S3 method for class 'mock_bids_project' plot(x, max_depth = Inf, ...)## S3 method for class 'bids_project' plot(x, max_depth = Inf, ...) ## S3 method for class 'mock_bids_project' plot(x, max_depth = Inf, ...)
x |
A |
max_depth |
Maximum depth of the tree to display. Defaults to
|
... |
Additional arguments passed to |
The input object x is returned invisibly.
tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) plot(proj) # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) })tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) plot(proj) # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) })
This function retrieves paths to preprocessed functional MRI scans from a BIDS project. It searches for files in the fMRIPrep derivatives directory that match specified criteria, such as subject ID, task, run, and other BIDS metadata. Preprocessed scans are identified by having either 'desc-preproc' or 'kind-preproc' in their filename.
preproc_scans( x, subid = ".*", task = ".*", run = ".*", session = ".*", variant = NULL, space = ".*", modality = "bold", kind = ".*", full_path = FALSE, ... )preproc_scans( x, subid = ".*", task = ".*", run = ".*", session = ".*", variant = NULL, space = ".*", modality = "bold", kind = ".*", full_path = FALSE, ... )
x |
A |
subid |
Subject ID regex to match specific subjects (default: ".*" for all subjects) |
task |
Task regex to match specific tasks (default: ".*" for all tasks) |
run |
Run regex to match specific runs (default: ".*" for all runs) |
session |
Session regex to match specific sessions (default: ".*" for all sessions) |
variant |
Preprocessing variant to match (default: NULL, which matches files without a variant) |
space |
Space regex to match specific spaces (default: ".*" for all spaces) |
modality |
Image modality to match (default: "bold" for functional MRI) |
kind |
Kind regex to match specific kinds (default: ".*" for all kinds) |
full_path |
If TRUE, return full file paths; if FALSE, return paths relative to the project root (default: FALSE) |
... |
Additional arguments passed to internal functions |
A character vector of file paths to preprocessed functional scans matching the criteria. If no matching files are found, returns NULL.
# Get all preprocessed scans from a BIDS project with fMRIPrep derivatives # Download and load a BIDS project with fMRIPrep derivatives tryCatch({ ds001_deriv_path <- get_example_bids_dataset("ds000001-fmriprep") proj <- bids_project(ds001_deriv_path, fmriprep=TRUE) # Get all preprocessed scans scans <- preproc_scans(proj) # Get preprocessed scans for a specific subject if (!is.null(scans) && length(scans) > 0) { sub01_scans <- preproc_scans(proj, subid="01") } # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires derivatives dataset: ", e$message) })# Get all preprocessed scans from a BIDS project with fMRIPrep derivatives # Download and load a BIDS project with fMRIPrep derivatives tryCatch({ ds001_deriv_path <- get_example_bids_dataset("ds000001-fmriprep") proj <- bids_project(ds001_deriv_path, fmriprep=TRUE) # Get all preprocessed scans scans <- preproc_scans(proj) # Get preprocessed scans for a specific subject if (!is.null(scans) && length(scans) > 0) { sub01_scans <- preproc_scans(proj, subid="01") } # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires derivatives dataset: ", e$message) })
This function retrieves paths to preprocessed functional MRI scans from a BIDS project's fMRIPrep derivatives. It allows filtering by various BIDS entities such as subject, task, run, session, and space. The function is particularly useful for accessing preprocessed data for analysis pipelines.
## S3 method for class 'bids_project' preproc_scans( x, subid = ".*", task = ".*", run = ".*", session = ".*", variant = NULL, space = ".*", modality = "bold", kind = ".*", full_path = FALSE, ... )## S3 method for class 'bids_project' preproc_scans( x, subid = ".*", task = ".*", run = ".*", session = ".*", variant = NULL, space = ".*", modality = "bold", kind = ".*", full_path = FALSE, ... )
x |
A |
subid |
A regex pattern for matching subjects. Default is ".*". |
task |
A regex pattern for matching tasks. Default is ".*". |
run |
A regex pattern for matching runs. Default is ".*". |
session |
A regex pattern for matching sessions. Default is ".*". |
variant |
A regex pattern for matching preprocessing variants. Default is NULL (no variant filtering). |
space |
A regex pattern for matching spaces (e.g., "MNI152NLin2009cAsym"). Default is ".*". |
modality |
A regex pattern for matching modality. Default is "bold". Set this to something else if you need a different modality. |
kind |
The kind of preprocessed data to return. Default is ".*" to match any kind. |
full_path |
If TRUE, return full file paths. Otherwise return relative paths. Default is FALSE. |
... |
Additional key-value filters for BIDS entities. These are matched
against parsed file entities in the derivatives tree. Common examples:
|
A character vector of file paths to preprocessed scans matching the criteria. Returns NULL if:
No matching files are found
The project doesn't have fMRIPrep derivatives
The specified criteria don't match any files
# Create a BIDS project with fMRIPrep derivatives tryCatch({ ds_path <- get_example_bids_dataset("phoneme_stripped") proj <- bids_project(ds_path, fmriprep=TRUE) # Get all preprocessed BOLD scans all_scans <- preproc_scans(proj) # Get preprocessed scans for specific subjects sub_scans <- preproc_scans(proj, subid="0[12]") # Get scans in MNI space mni_scans <- preproc_scans(proj, space="MNI152NLin2009cAsym") # Get scans for a specific task with full paths task_scans <- preproc_scans(proj, task="phoneme", full_path=TRUE) # Get scans from a specific session session_scans <- preproc_scans(proj, session="test") # Combine multiple filters filtered_scans <- preproc_scans(proj, subid="01", task="phoneme", run="01", space="MNI152NLin2009cAsym") # Filter by resolution (BIDS entity 'res') res2_scans <- preproc_scans(proj, res = "2") # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) })# Create a BIDS project with fMRIPrep derivatives tryCatch({ ds_path <- get_example_bids_dataset("phoneme_stripped") proj <- bids_project(ds_path, fmriprep=TRUE) # Get all preprocessed BOLD scans all_scans <- preproc_scans(proj) # Get preprocessed scans for specific subjects sub_scans <- preproc_scans(proj, subid="0[12]") # Get scans in MNI space mni_scans <- preproc_scans(proj, space="MNI152NLin2009cAsym") # Get scans for a specific task with full paths task_scans <- preproc_scans(proj, task="phoneme", full_path=TRUE) # Get scans from a specific session session_scans <- preproc_scans(proj, session="test") # Combine multiple filters filtered_scans <- preproc_scans(proj, subid="01", task="phoneme", run="01", space="MNI152NLin2009cAsym") # Filter by resolution (BIDS entity 'res') res2_scans <- preproc_scans(proj, res = "2") # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) })
Provides a console summary of the mock BIDS project, displaying key information like participant count, tasks, sessions, derivatives status, and discovered BIDS entities.
## S3 method for class 'mock_bids_project' print(x, ...)## S3 method for class 'mock_bids_project' print(x, ...)
x |
A |
... |
Extra arguments (ignored). |
The mock_bids_project object x invisibly.
# Create a simple mock project parts <- data.frame(participant_id = "01") fs <- data.frame(subid = "01", datatype="func", suffix="bold.nii.gz", fmriprep=FALSE) mock_proj <- create_mock_bids("SimpleMock", parts, fs) # Print the summary print(mock_proj)# Create a simple mock project parts <- data.frame(participant_id = "01") fs <- data.frame(subid = "01", datatype="func", suffix="bold.nii.gz", fmriprep=FALSE) mock_proj <- create_mock_bids("SimpleMock", parts, fs) # Print the summary print(mock_proj)
This function provides a stricter, more explicit querying interface than
search_files(), with support for exact-vs-regex entity matching, optional
entity-existence requirements, and raw/derivatives scope selection.
query_files(x, ...) ## S3 method for class 'bids_project' query_files( x, regex = ".*", full_path = FALSE, match_mode = c("regex", "exact", "glob"), require_entity = FALSE, scope = c("all", "raw", "derivatives"), pipeline = NULL, return = c("paths", "tibble"), use_index = c("auto", "never"), strict = TRUE, ... ) ## S3 method for class 'mock_bids_project' query_files( x, regex = ".*", full_path = FALSE, match_mode = c("regex", "exact", "glob"), require_entity = FALSE, scope = c("all", "raw", "derivatives"), pipeline = NULL, return = c("paths", "tibble"), use_index = c("auto", "never"), strict = TRUE, ... )query_files(x, ...) ## S3 method for class 'bids_project' query_files( x, regex = ".*", full_path = FALSE, match_mode = c("regex", "exact", "glob"), require_entity = FALSE, scope = c("all", "raw", "derivatives"), pipeline = NULL, return = c("paths", "tibble"), use_index = c("auto", "never"), strict = TRUE, ... ) ## S3 method for class 'mock_bids_project' query_files( x, regex = ".*", full_path = FALSE, match_mode = c("regex", "exact", "glob"), require_entity = FALSE, scope = c("all", "raw", "derivatives"), pipeline = NULL, return = c("paths", "tibble"), use_index = c("auto", "never"), strict = TRUE, ... )
x |
A |
... |
Additional entity filters (e.g., |
regex |
A regular expression applied to filenames. Default is |
full_path |
If |
match_mode |
Matching mode for entity filters in
|
require_entity |
If |
scope |
Which dataset scope to query:
|
pipeline |
Optional derivative pipeline name(s) used when
|
return |
Whether to return matching file paths ( |
use_index |
Whether to use a persisted file index when available:
|
strict |
Passed through to search methods. If |
A character vector of matching files, a tibble of indexed rows
(sorted by subid, session, task, run, path), or NULL if no matches
are found.
tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path, fmriprep = FALSE) # Exact entity matching for reproducible filters in new workflows exact_bold <- query_files( proj, regex = "bold\\.nii\\.gz$", subid = "01", task = "balloonanalogrisktask", match_mode = "exact" ) # Regex entity matching when selecting multiple runs or tasks regex_bold <- query_files( proj, regex = "bold\\.nii\\.gz$", subid = "0[12]", task = "balloon.*|mixedgamblestask", match_mode = "regex" ) # Require task labels to actually exist on the matched files task_annotated <- query_files( proj, regex = "\\.nii\\.gz$", task = ".*", require_entity = TRUE, scope = "raw" ) # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) }) tryCatch({ deriv_path <- get_example_bids_dataset("ds000001-fmriprep") proj_deriv <- bids_project(deriv_path, fmriprep = TRUE) deriv_only <- query_files( proj_deriv, regex = "bold\\.nii\\.gz$", desc = "preproc", scope = "derivatives", pipeline = "fmriprep", match_mode = "exact" ) all_scopes <- query_files( proj_deriv, regex = "bold\\.nii\\.gz$", scope = "all", return = "tibble" ) # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires derivatives dataset: ", e$message) })tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path, fmriprep = FALSE) # Exact entity matching for reproducible filters in new workflows exact_bold <- query_files( proj, regex = "bold\\.nii\\.gz$", subid = "01", task = "balloonanalogrisktask", match_mode = "exact" ) # Regex entity matching when selecting multiple runs or tasks regex_bold <- query_files( proj, regex = "bold\\.nii\\.gz$", subid = "0[12]", task = "balloon.*|mixedgamblestask", match_mode = "regex" ) # Require task labels to actually exist on the matched files task_annotated <- query_files( proj, regex = "\\.nii\\.gz$", task = ".*", require_entity = TRUE, scope = "raw" ) # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) }) tryCatch({ deriv_path <- get_example_bids_dataset("ds000001-fmriprep") proj_deriv <- bids_project(deriv_path, fmriprep = TRUE) deriv_only <- query_files( proj_deriv, regex = "bold\\.nii\\.gz$", desc = "preproc", scope = "derivatives", pipeline = "fmriprep", match_mode = "exact" ) all_scopes <- query_files( proj_deriv, regex = "bold\\.nii\\.gz$", scope = "all", return = "tibble" ) # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires derivatives dataset: ", e$message) })
This function reads in fMRIPrep confound tables for one or more subjects from a BIDS project. Confound files contain nuisance variables that can be used for denoising fMRI data, such as motion parameters, physiological signals, and other noise components. The function can optionally perform PCA reduction on the confounds and return either nested or flat tibbles.
read_confounds(x, ...)read_confounds(x, ...)
x |
The object to read confounds from (typically a |
... |
Additional arguments passed to methods, including:
|
A bids_confounds tibble containing confound data. If nest=TRUE
(default), returns a nested tibble with columns for subject, task, session,
run, and a nested data column containing the confound variables. If
nest=FALSE, returns a flat tibble with all confound variables. When PCA is
requested, the object includes a pca attribute with loadings/variance for
plotting. Returns NULL if no matching files are found.
# Create a BIDS project with fMRIPrep derivatives tryCatch({ ds_path <- get_example_bids_dataset("ds000001-fmriprep") proj <- bids_project(ds_path, fmriprep=TRUE) # Read all confound files all_conf <- read_confounds(proj) # Read confounds for specific subjects and tasks sub_conf <- read_confounds(proj, subid="01", task="balloonanalogrisktask") # Select specific confound variables motion_conf <- read_confounds(proj, cvars=c("framewise_displacement", "trans_x", "trans_y", "trans_z", "rot_x", "rot_y", "rot_z")) # Perform PCA reduction pca_conf <- read_confounds(proj, npcs=5) # Get confounds as a flat tibble flat_conf <- read_confounds(proj, nest=FALSE) # Combine multiple options custom_conf <- read_confounds(proj, subid="01", task="balloonanalogrisktask", cvars=c("framewise_displacement", "trans_x", "trans_y", "trans_z"), npcs=3, nest=FALSE) # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) })# Create a BIDS project with fMRIPrep derivatives tryCatch({ ds_path <- get_example_bids_dataset("ds000001-fmriprep") proj <- bids_project(ds_path, fmriprep=TRUE) # Read all confound files all_conf <- read_confounds(proj) # Read confounds for specific subjects and tasks sub_conf <- read_confounds(proj, subid="01", task="balloonanalogrisktask") # Select specific confound variables motion_conf <- read_confounds(proj, cvars=c("framewise_displacement", "trans_x", "trans_y", "trans_z", "rot_x", "rot_y", "rot_z")) # Perform PCA reduction pca_conf <- read_confounds(proj, npcs=5) # Get confounds as a flat tibble flat_conf <- read_confounds(proj, nest=FALSE) # Combine multiple options custom_conf <- read_confounds(proj, subid="01", task="balloonanalogrisktask", cvars=c("framewise_displacement", "trans_x", "trans_y", "trans_z"), npcs=3, nest=FALSE) # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) })
Reads in fmriprep confound tables for one or more subjects.
## S3 method for class 'bids_project' read_confounds( x, subid = ".*", task = ".*", session = ".*", run = ".*", cvars = DEFAULT_CVARS, npcs = -1, perc_var = -1, nest = TRUE, clean = "zero_variance", na_action = "leave", ... )## S3 method for class 'bids_project' read_confounds( x, subid = ".*", task = ".*", session = ".*", run = ".*", cvars = DEFAULT_CVARS, npcs = -1, perc_var = -1, nest = TRUE, clean = "zero_variance", na_action = "leave", ... )
x |
A |
subid |
Subject ID regex |
task |
Task regex |
session |
Session regex |
run |
Run regex. If the run identifier cannot be extracted from the filename, the run value defaults to "1". |
cvars |
The names of the confound variables to select. Defaults to |
npcs |
Perform PCA reduction on confounds and return |
perc_var |
Perform PCA reduction to retain |
nest |
If TRUE, nests confound tables by subject/task/session/run. |
clean |
Character vector controlling run-level confound cleaning before
returning data or running PCA. Supported values are |
na_action |
How to handle missing values in raw confound columns before
returning them. Supported values are |
... |
Additional arguments (not currently used) |
A bids_confounds tibble (nested if nest=TRUE) with identifier columns
for participant_id, task, session, and run. When PCA is requested, the
object includes a pca attribute with per-run loadings and variance used
by plot(). Dropped or flagged confounds are stored in the
confound_diagnostics attribute.
# Try to load a BIDS project with fMRIPrep derivatives tryCatch({ ds_path <- get_example_bids_dataset("ds000001-fmriprep") proj <- bids_project(ds_path, fmriprep=TRUE) # Read confounds with canonical names (automatically resolve to actual columns) conf <- read_confounds(proj, cvars = c("csf", "framewise_displacement")) # Use convenience sets conf_36p <- read_confounds(proj, cvars = confound_set("36p")) conf_compcor6 <- read_confounds(proj, cvars = confound_set("acompcor", n = 6)) # Read confounds for specific subjects and tasks conf_sub <- read_confounds(proj, subid="01", task="balloonanalogrisktask") # Get confounds as flat tibble conf_flat <- read_confounds(proj, nest=FALSE) # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires derivatives dataset with confounds: ", e$message) })# Try to load a BIDS project with fMRIPrep derivatives tryCatch({ ds_path <- get_example_bids_dataset("ds000001-fmriprep") proj <- bids_project(ds_path, fmriprep=TRUE) # Read confounds with canonical names (automatically resolve to actual columns) conf <- read_confounds(proj, cvars = c("csf", "framewise_displacement")) # Use convenience sets conf_36p <- read_confounds(proj, cvars = confound_set("36p")) conf_compcor6 <- read_confounds(proj, cvars = confound_set("acompcor", n = 6)) # Read confounds for specific subjects and tasks conf_sub <- read_confounds(proj, subid="01", task="balloonanalogrisktask") # Get confounds as flat tibble conf_flat <- read_confounds(proj, nest=FALSE) # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires derivatives dataset with confounds: ", e$message) })
Read Confound Files (Mock Implementation)
## S3 method for class 'mock_bids_project' read_confounds( x, subid = ".*", task = ".*", session = ".*", run = ".*", cvars = NULL, npcs = -1, perc_var = -1, nest = TRUE, clean = "zero_variance", na_action = "leave", ... )## S3 method for class 'mock_bids_project' read_confounds( x, subid = ".*", task = ".*", session = ".*", run = ".*", cvars = NULL, npcs = -1, perc_var = -1, nest = TRUE, clean = "zero_variance", na_action = "leave", ... )
x |
A |
subid |
Regex pattern for subject IDs. Default |
task |
Regex pattern for task names. Default |
session |
Regex pattern for session IDs. Default |
run |
Regex pattern for run indices. Default |
cvars |
Variables to select (ignored in mock). |
npcs |
PCA components (applied when requested). |
perc_var |
PCA variance (applied when requested). |
nest |
If |
clean |
Character vector controlling run-level confound cleaning before
returning data or running PCA. Supported values are |
na_action |
How to handle missing values in raw confound columns before
returning them. Supported values are |
... |
Additional BIDS entities (passed to |
A bids_confounds tibble of confound data (nested if nest = TRUE).
parts <- c("01") fs <- tibble::tibble( subid = "01", datatype = "func", suffix = c("bold.nii.gz", "desc-confounds_timeseries.tsv"), task = "rest", fmriprep = c(TRUE, TRUE) ) conf_data <- list() key <- "derivatives/fmriprep/sub-01/func/sub-01_task-rest_desc-confounds_timeseries.tsv" conf_data[[key]] <- data.frame( csf = rnorm(50), white_matter = rnorm(50), trans_x = rnorm(50), trans_y = rnorm(50) ) mock <- create_mock_bids("ConfTest", parts, fs, confound_data = conf_data) conf <- read_confounds(mock) print(conf)parts <- c("01") fs <- tibble::tibble( subid = "01", datatype = "func", suffix = c("bold.nii.gz", "desc-confounds_timeseries.tsv"), task = "rest", fmriprep = c(TRUE, TRUE) ) conf_data <- list() key <- "derivatives/fmriprep/sub-01/func/sub-01_task-rest_desc-confounds_timeseries.tsv" conf_data[[key]] <- data.frame( csf = rnorm(50), white_matter = rnorm(50), trans_x = rnorm(50), trans_y = rnorm(50) ) mock <- create_mock_bids("ConfTest", parts, fs, confound_data = conf_data) conf <- read_confounds(mock) print(conf)
Read the dataset_description.json for a BIDS project
read_dataset_description(x, ...) ## S3 method for class 'character' read_dataset_description(x, ...) ## S3 method for class 'bids_project' read_dataset_description(x, ...)read_dataset_description(x, ...) ## S3 method for class 'character' read_dataset_description(x, ...) ## S3 method for class 'bids_project' read_dataset_description(x, ...)
x |
A |
... |
Additional arguments passed to methods. |
A bids_dataset_description object, or NULL if the file is absent.
tryCatch({ ds001_path <- get_example_bids_dataset("ds001") desc <- read_dataset_description(ds001_path) print(desc) # Example datasets are cached; leave the cache in place. }, error = function(e) message("Example requires internet: ", e$message))tryCatch({ ds001_path <- get_example_bids_dataset("ds001") desc <- read_dataset_description(ds001_path) print(desc) # Example datasets are cached; leave the cache in place. }, error = function(e) message("Example requires internet: ", e$message))
This generic function reads and nests event files from a BIDS project. Event files contain timing information about task events, conditions, and responses during functional MRI scans. The function can filter events by subject and task, and returns a nested tibble for easy data manipulation.
read_events(x, ...)read_events(x, ...)
x |
The object to read events from (typically a |
... |
Additional arguments passed to methods. |
A nested tibble with columns:
.task: Task name
.run: Run number
.subid: Subject ID
data: Nested column containing the event data
If no matching data is found, returns an empty tibble with appropriate columns.
# Create a BIDS project tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) # Read all event files all_events <- read_events(proj) # Read events for specific subjects sub_events <- read_events(proj, subid="0[123]") # Read events for a specific task task_events <- read_events(proj, task="balloonanalogrisktask") # Combine multiple filters filtered_events <- read_events(proj, subid="01", task="balloonanalogrisktask") # Access nested data if (nrow(filtered_events) > 0) { first_run <- filtered_events$data[[1]] print(head(first_run)) } # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) })# Create a BIDS project tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) # Read all event files all_events <- read_events(proj) # Read events for specific subjects sub_events <- read_events(proj, subid="0[123]") # Read events for a specific task task_events <- read_events(proj, task="balloonanalogrisktask") # Combine multiple filters filtered_events <- read_events(proj, subid="01", task="balloonanalogrisktask") # Access nested data if (nrow(filtered_events) > 0) { first_run <- filtered_events$data[[1]] print(head(first_run)) } # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) })
Reads and nests event files for given subjects and tasks from a bids_project object.
Returns a nested tibble with event data grouped by task, session, run, and subject. Event files
typically contain trial-by-trial information for task-based fMRI data, including onset times,
durations, trial types, and other task-specific variables.
## S3 method for class 'bids_project' read_events(x, subid = ".*", task = ".*", run = ".*", session = ".*", ...)## S3 method for class 'bids_project' read_events(x, subid = ".*", task = ".*", run = ".*", session = ".*", ...)
x |
A |
subid |
Regex pattern to match subject IDs. Default is ".*" (all subjects). |
task |
Regex pattern to match tasks. Default is ".*" (all tasks). |
run |
Regex pattern to match runs. Default is ".*" (all runs). |
session |
Regex pattern to match sessions. Default is ".*" (all sessions). |
... |
Additional arguments passed to |
A nested tibble with columns:
.task: Task name
.session: Session ID (if present)
.run: Run number
.subid: Subject ID
data: A nested tibble containing the event data with columns:
onset: Event onset time in seconds
duration: Event duration in seconds
Additional task-specific columns (e.g., trial type, response, accuracy)
If no matching data is found, returns an empty tibble with appropriate columns.
Run and session identifiers are parsed from filenames using func_parser().
# Create a BIDS project object tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) # Read all event files all_events <- read_events(proj) # Read events for a specific subject and task sub01_events <- read_events(proj, subid="01", task="balloonanalogrisktask") # Read events for multiple subjects and a specific run multi_sub_events <- read_events(proj, subid="0[1-3]", run="01") # Access nested data for analysis if (nrow(sub01_events) > 0) { # Get first subject's data first_sub_data <- sub01_events$data[[1]] # Calculate mean trial duration mean_duration <- mean(first_sub_data$duration) } # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) })# Create a BIDS project object tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) # Read all event files all_events <- read_events(proj) # Read events for a specific subject and task sub01_events <- read_events(proj, subid="01", task="balloonanalogrisktask") # Read events for multiple subjects and a specific run multi_sub_events <- read_events(proj, subid="0[1-3]", run="01") # Access nested data for analysis if (nrow(sub01_events) > 0) { # Get first subject's data first_sub_data <- sub01_events$data[[1]] # Calculate mean trial duration mean_duration <- mean(first_sub_data$duration) } # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) })
Retrieves and formats event data stored within the mock project object.
## S3 method for class 'mock_bids_project' read_events(x, subid = ".*", task = ".*", run = ".*", session = ".*", ...)## S3 method for class 'mock_bids_project' read_events(x, subid = ".*", task = ".*", run = ".*", session = ".*", ...)
x |
A |
subid |
Regex pattern for subject IDs. Default |
task |
Regex pattern for task names. Default |
run |
Regex pattern for run indices. Default |
session |
Regex pattern for session IDs. Default |
... |
Additional arguments passed to |
A nested tibble with columns .subid, .task, .run, .session (if applicable),
and data (containing the event tibbles), or an empty tibble if no matching data.
parts <- c("01") fs <- tibble::tibble( subid = "01", datatype = "func", suffix = c("bold.nii.gz", "events.tsv"), task = "rest", run = "01", fmriprep = FALSE ) evt_data <- list() evt_data[["sub-01/func/sub-01_task-rest_run-01_events.tsv"]] <- tibble::tibble(onset = c(1, 5, 10), duration = c(0.5, 0.5, 0.5), trial_type = c("go", "stop", "go")) mock <- create_mock_bids("EventTest", parts, fs, event_data = evt_data) events <- read_events(mock) print(events)parts <- c("01") fs <- tibble::tibble( subid = "01", datatype = "func", suffix = c("bold.nii.gz", "events.tsv"), task = "rest", run = "01", fmriprep = FALSE ) evt_data <- list() evt_data[["sub-01/func/sub-01_task-rest_run-01_events.tsv"]] <- tibble::tibble(onset = c(1, 5, 10), duration = c(0.5, 0.5, 0.5), trial_type = c("go", "stop", "go")) mock <- create_mock_bids("EventTest", parts, fs, event_data = evt_data) events <- read_events(mock) print(events)
Read in a set of four-dimensional functional scans
read_func_scans.bids_project( x, mask, mode = c("normal", "bigvec"), subid = "^sub-.*", task = ".*", run = ".*", modality = "bold", ... )read_func_scans.bids_project( x, mask, mode = c("normal", "bigvec"), subid = "^sub-.*", task = ".*", run = ".*", modality = "bold", ... )
x |
A |
mask |
A brain mask of type |
mode |
The file mode: 'normal' for in-memory files or 'bigvec' for on-disk files |
subid |
One or more subject IDs (regex) |
task |
An optional task regex |
run |
An optional run regex |
modality |
The image modality (usually "bold") |
... |
Extra arguments passed to |
An instance of type NeuroVec
tryCatch({ ds_path <- get_example_bids_dataset("ds000001-fmriprep") proj <- bids_project(ds_path, fmriprep=TRUE) mask <- brain_mask(proj, subid="01") vec <- read_func_scans.bids_project(proj, mask, subid="01", task="balloonanalogrisktask", run="01") # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires derivatives dataset: ", e$message) })tryCatch({ ds_path <- get_example_bids_dataset("ds000001-fmriprep") proj <- bids_project(ds_path, fmriprep=TRUE) mask <- brain_mask(proj, subid="01") vec <- read_func_scans.bids_project(proj, mask, subid="01", task="balloonanalogrisktask", run="01") # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires derivatives dataset: ", e$message) })
Read participants.tsv as a typed tabular object
read_participants(x, ...) ## S3 method for class 'bids_project' read_participants(x, ...) ## S3 method for class 'character' read_participants(x, ...)read_participants(x, ...) ## S3 method for class 'bids_project' read_participants(x, ...) ## S3 method for class 'character' read_participants(x, ...)
x |
A |
... |
Additional arguments passed to methods. |
A bids_participants object inheriting from tbl_df, or NULL.
tryCatch({ ds001_path <- get_example_bids_dataset("ds001") pt <- read_participants(ds001_path) print(pt) # Example datasets are cached; leave the cache in place. }, error = function(e) message("Example requires internet: ", e$message))tryCatch({ ds001_path <- get_example_bids_dataset("ds001") pt <- read_participants(ds001_path) print(pt) # Example datasets are cached; leave the cache in place. }, error = function(e) message("Example requires internet: ", e$message))
This function reads preprocessed functional MRI scans from a BIDS project's fMRIPrep
derivatives directory. It uses the preproc_scans function to locate the files
and then reads each one into its own NeuroVec object using the
neuroim2 package. If a
mask is not provided, one will be automatically created from available brainmask files.
read_preproc_scans.bids_project( x, mask = NULL, mode = c("normal", "bigvec"), subid = "^sub-.*", task = ".*", run = ".*", modality = "bold", ... )read_preproc_scans.bids_project( x, mask = NULL, mode = c("normal", "bigvec"), subid = "^sub-.*", task = ".*", run = ".*", modality = "bold", ... )
x |
A |
mask |
A brain mask of type |
mode |
The file mode: 'normal' for in-memory files or 'bigvec' for on-disk files |
subid |
Regular expression to match subject IDs (default: "^sub-.*" to match all subjects) |
task |
Regular expression to match tasks (default: ".*" to match all tasks) |
run |
Regular expression to match runs (default: ".*" to match all runs) |
modality |
Image modality to match (default: "bold" for functional MRI) |
... |
Extra arguments passed to |
This function requires the neuroim2 package to be installed. It will throw an
error if the package is not available or if fMRIPrep derivatives are not found in the
BIDS project. If no mask is provided, it will create one using the create_preproc_mask
function.
A named list of NeuroVec objects, one per matched preprocessed
scan, in file order.
# Load a BIDS project with fMRIPrep derivatives tryCatch({ ds_path <- get_example_bids_dataset("ds000001-fmriprep") proj <- bids_project(ds_path, fmriprep=TRUE) # Read preprocessed scans for all subjects # (mask will be created automatically) all_scans <- read_preproc_scans(proj) # Read preprocessed scans for a specific subject sub01_scans <- read_preproc_scans(proj, subid="01") # Read preprocessed scans for a specific task and run task_scans <- read_preproc_scans(proj, task="balloonanalogrisktask", run="01") # Specify mode for large datasets bigvec_scans <- read_preproc_scans(proj, mode="bigvec") # Provide a custom mask mask <- create_preproc_mask(proj, thresh=0.95) masked_scans <- read_preproc_scans(proj, mask=mask) first_run <- masked_scans[[1]] # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires derivatives dataset: ", e$message) })# Load a BIDS project with fMRIPrep derivatives tryCatch({ ds_path <- get_example_bids_dataset("ds000001-fmriprep") proj <- bids_project(ds_path, fmriprep=TRUE) # Read preprocessed scans for all subjects # (mask will be created automatically) all_scans <- read_preproc_scans(proj) # Read preprocessed scans for a specific subject sub01_scans <- read_preproc_scans(proj, subid="01") # Read preprocessed scans for a specific task and run task_scans <- read_preproc_scans(proj, task="balloonanalogrisktask", run="01") # Specify mode for large datasets bigvec_scans <- read_preproc_scans(proj, mode="bigvec") # Provide a custom mask mask <- create_preproc_mask(proj, thresh=0.95) masked_scans <- read_preproc_scans(proj, mask=mask) first_run <- masked_scans[[1]] # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires derivatives dataset: ", e$message) })
Read a scans.tsv file for a subject
read_scans_tsv(x, subid, session = NULL, ...) ## S3 method for class 'bids_project' read_scans_tsv(x, subid, session = NULL, ...)read_scans_tsv(x, subid, session = NULL, ...) ## S3 method for class 'bids_project' read_scans_tsv(x, subid, session = NULL, ...)
x |
A |
subid |
Subject ID (without |
session |
Optional session ID (without |
... |
Additional arguments passed to methods. |
A bids_scans_tsv object inheriting from tbl_df, or NULL.
tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) scans <- read_scans_tsv(proj, subid = "01") # Example datasets are cached; leave the cache in place. }, error = function(e) message("Example requires internet: ", e$message))tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) scans <- read_scans_tsv(proj, subid = "01") # Example datasets are cached; leave the cache in place. }, error = function(e) message("Example requires internet: ", e$message))
Read a sessions.tsv file for a subject
read_sessions_tsv(x, subid, ...) ## S3 method for class 'bids_project' read_sessions_tsv(x, subid, ...)read_sessions_tsv(x, subid, ...) ## S3 method for class 'bids_project' read_sessions_tsv(x, subid, ...)
x |
A |
subid |
Subject ID (without |
... |
Additional arguments passed to methods. |
A bids_sessions_tsv object inheriting from tbl_df, or NULL.
tryCatch({ ds007_path <- get_example_bids_dataset("ds007") proj <- bids_project(ds007_path) sess <- read_sessions_tsv(proj, subid = "01") unlink(ds007_path, recursive = TRUE) }, error = function(e) message("Example requires internet: ", e$message))tryCatch({ ds007_path <- get_example_bids_dataset("ds007") proj <- bids_project(ds007_path) sess <- read_sessions_tsv(proj, subid = "01") unlink(ds007_path, recursive = TRUE) }, error = function(e) message("Example requires internet: ", e$message))
This function searches for JSON sidecar files matching the given criteria (subject, task, run, session), reads the JSON content, and converts all top-level fields into columns of a tibble. Each file's metadata becomes one row in the returned tibble. This is particularly useful for extracting metadata about BIDS imaging files, such as acquisition parameters, task descriptions, and other relevant information.
read_sidecar( x, subid = ".*", task = ".*", run = ".*", session = ".*", modality = "bold", full_path = TRUE, inherit = FALSE, inherit_scope = c("auto", "raw", "derivatives", "all"), ... )read_sidecar( x, subid = ".*", task = ".*", run = ".*", session = ".*", modality = "bold", full_path = TRUE, inherit = FALSE, inherit_scope = c("auto", "raw", "derivatives", "all"), ... )
x |
A |
subid |
A regex for matching subject IDs. Default is |
task |
A regex for matching tasks. Default is |
run |
A regex for matching runs. Default is |
session |
A regex for matching sessions. Default is |
modality |
A regex for matching modality/kind (e.g. "bold"). Default is |
full_path |
If TRUE, return full file paths in the |
inherit |
If TRUE, resolve metadata using BIDS inheritance across parent sidecars. If FALSE (default), read each JSON sidecar directly. |
inherit_scope |
Scope used when
|
... |
Additional arguments passed to |
A tibble with one row per JSON file. Columns include:
file: the JSON file path
.subid: subject ID extracted from filename
.session: session ID extracted from filename (if present)
.task: task name extracted from filename (if present)
.run: run number extracted from filename (if present)
Additional columns for each top-level key in the JSON files If no files are found, returns an empty tibble.
# Read all BOLD sidecar files from a BIDS dataset tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) metadata <- read_sidecar(proj) # Read sidecar files for a specific subject and task sub01_meta <- read_sidecar(proj, subid="01", task="balloonanalogrisktask") # Read sidecar files for anatomical data anat_meta <- read_sidecar(proj, modality="T1w", full_path=FALSE) # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) })# Read all BOLD sidecar files from a BIDS dataset tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) metadata <- read_sidecar(proj) # Read sidecar files for a specific subject and task sub01_meta <- read_sidecar(proj, subid="01", task="balloonanalogrisktask") # Read sidecar files for anatomical data anat_meta <- read_sidecar(proj, modality="T1w", full_path=FALSE) # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) })
Adds a new datatype to the bidser runtime registry so that
bids_project will scan and parse its folder. The five
built-in datatypes ("func", "anat", "fmap",
"funcprep", "anatprep") can only be overwritten by passing
overwrite = TRUE.
register_datatype( name, spec, parser_fn, folder = name, scope = c("raw", "derivative", "both"), overwrite = FALSE )register_datatype( name, spec, parser_fn, folder = name, scope = c("raw", "derivative", "both"), overwrite = FALSE )
name |
A non-empty character string naming the datatype. |
spec |
A spec list as returned by |
parser_fn |
A parser object as returned by |
folder |
The folder name to scan inside each subject/session directory.
Defaults to |
scope |
One of |
overwrite |
Logical. If |
The name string, invisibly.
## Not run: my_spec <- func_spec() # placeholder my_parser <- func_parser() # placeholder register_datatype("dwi", spec = my_spec, parser_fn = my_parser, folder = "dwi", scope = "raw") list_datatypes() ## End(Not run)## Not run: my_spec <- func_spec() # placeholder my_parser <- func_parser() # placeholder register_datatype("dwi", spec = my_spec, parser_fn = my_parser, folder = "dwi", scope = "raw") list_datatypes() ## End(Not run)
Resolve a BIDS URI to a local or remote path
resolve_bids_uri(uri, description, ..., must_exist = FALSE) ## S3 method for class 'bids_uri' resolve_bids_uri(uri, description, ..., must_exist = FALSE) ## S3 method for class 'character' resolve_bids_uri(uri, description, ..., must_exist = FALSE)resolve_bids_uri(uri, description, ..., must_exist = FALSE) ## S3 method for class 'bids_uri' resolve_bids_uri(uri, description, ..., must_exist = FALSE) ## S3 method for class 'character' resolve_bids_uri(uri, description, ..., must_exist = FALSE)
uri |
A |
description |
A |
... |
Additional arguments passed to methods. |
must_exist |
Logical. If |
A character scalar path (or URL for remote links).
tryCatch({ ds001_path <- get_example_bids_dataset("ds001") desc <- read_dataset_description(ds001_path) uri <- bids_uri("bids::sub-01/anat/sub-01_T1w.nii.gz") path <- resolve_bids_uri(uri, desc) # Example datasets are cached; leave the cache in place. }, error = function(e) message("Example requires internet: ", e$message))tryCatch({ ds001_path <- get_example_bids_dataset("ds001") desc <- read_dataset_description(ds001_path) uri <- bids_uri("bids::sub-01/anat/sub-01_T1w.nii.gz") path <- resolve_bids_uri(uri, desc) # Example datasets are cached; leave the cache in place. }, error = function(e) message("Example requires internet: ", e$message))
This function searches for files in a BIDS project that match a specified pattern and optional key-value criteria. It can be used to find files in both raw data and preprocessed derivatives based on filename patterns and BIDS metadata.
This function searches for files in a BIDS project that match a specified pattern and optional key-value criteria. It can search in both raw data and preprocessed derivatives (if available).
Finds files in the mock BIDS tree by matching file names and BIDS entities.
search_files(x, ...) ## S3 method for class 'bids_project' search_files(x, regex = ".*", full_path = FALSE, strict = TRUE, ...) ## S3 method for class 'mock_bids_project' search_files(x, regex = ".*", full_path = FALSE, strict = TRUE, ...)search_files(x, ...) ## S3 method for class 'bids_project' search_files(x, regex = ".*", full_path = FALSE, strict = TRUE, ...) ## S3 method for class 'mock_bids_project' search_files(x, regex = ".*", full_path = FALSE, strict = TRUE, ...)
x |
A |
... |
Additional BIDS entities to match (e.g., |
regex |
A regular expression to match filenames (node names). Default |
full_path |
If |
strict |
If |
search_files() remains available as the compatibility interface for
existing code and ad hoc regex-heavy searches. For new code, prefer
query_files(), which provides explicit matching mode, entity-existence
semantics, and scope controls without changing search_files() behavior.
This method remains available for backward compatibility and flexible
regex-driven searches. Prefer query_files() for explicit query semantics
in new code.
A character vector of file paths matching the criteria, or NULL if no matches found.
A character vector of file paths matching the criteria, or NULL if no matches found.
A character vector of matching file paths, or NULL if no matches.
# Search for event files in a BIDS dataset tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path, fmriprep=FALSE) event_files <- search_files(proj, regex="events\\.tsv$") # Search with additional criteria sub01_files <- search_files(proj, regex="bold\\.nii\\.gz$", subid="01", task="balloonanalogrisktask") # Get full paths full_paths <- search_files(proj, regex="events\\.tsv$", full_path=TRUE) # Search with strict matching strict_matches <- search_files(proj, regex="\\.tsv$", strict=TRUE, task="balloonanalogrisktask") # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) }) # Search for event files in a BIDS dataset tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path, fmriprep=FALSE) event_files <- search_files(proj, regex="events\\.tsv$") # Search with additional criteria (note: ds001 only has one subject '01') sub01_files <- search_files(proj, regex="bold\\.nii\\.gz$", subid="01", task="balloonanalogrisktask") # Get full paths full_paths <- search_files(proj, regex="events\\.tsv$", full_path=TRUE) # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) })# Search for event files in a BIDS dataset tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path, fmriprep=FALSE) event_files <- search_files(proj, regex="events\\.tsv$") # Search with additional criteria sub01_files <- search_files(proj, regex="bold\\.nii\\.gz$", subid="01", task="balloonanalogrisktask") # Get full paths full_paths <- search_files(proj, regex="events\\.tsv$", full_path=TRUE) # Search with strict matching strict_matches <- search_files(proj, regex="\\.tsv$", strict=TRUE, task="balloonanalogrisktask") # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) }) # Search for event files in a BIDS dataset tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path, fmriprep=FALSE) event_files <- search_files(proj, regex="events\\.tsv$") # Search with additional criteria (note: ds001 only has one subject '01') sub01_files <- search_files(proj, regex="bold\\.nii\\.gz$", subid="01", task="balloonanalogrisktask") # Get full paths full_paths <- search_files(proj, regex="events\\.tsv$", full_path=TRUE) # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) })
This function retrieves a vector of session IDs from a BIDS project. Sessions in BIDS are typically represented as directories named 'ses-XX' within subject directories. This function extracts and returns the unique session identifiers.
sessions(x, ...) ## S3 method for class 'bids_project' sessions(x, ...)sessions(x, ...) ## S3 method for class 'bids_project' sessions(x, ...)
x |
the object to extract sessions from |
... |
extra args passed to methods |
A character vector of unique session IDs if the project has sessions, or NULL if the project does not have sessions
# Get sessions from a BIDS project tryCatch({ ds007_path <- get_example_bids_dataset("ds007") proj <- bids_project(ds007_path) sessions(proj) # Dataset cache is intentionally retained for performance. }, error = function(e) { message("Example requires internet connection: ", e$message) })# Get sessions from a BIDS project tryCatch({ ds007_path <- get_example_bids_dataset("ds007") proj <- bids_project(ds007_path) sessions(proj) # Dataset cache is intentionally retained for performance. }, error = function(e) { message("Example requires internet connection: ", e$message) })
Extracts the unique session IDs found in the mock project's file structure. Note: Returns IDs without the "ses-" prefix.
## S3 method for class 'mock_bids_project' sessions(x, ...)## S3 method for class 'mock_bids_project' sessions(x, ...)
x |
A |
... |
Extra arguments (ignored). |
Character vector of unique session IDs (e.g., c("pre", "post")), sorted,
or NULL if the project does not have sessions.
# Create a mock project with sessions parts <- data.frame(participant_id = "01") fs <- data.frame(subid="01", session="test", datatype="func", suffix="bold.nii.gz", fmriprep=FALSE) mock_proj <- create_mock_bids("SessionMock", parts, fs) # Get session IDs sessions(mock_proj) # Project without sessions fs_no_session <- data.frame(subid="01", datatype="func", suffix="bold.nii.gz", fmriprep=FALSE) mock_proj_no_sess <- create_mock_bids("NoSessionMock", parts, fs_no_session) sessions(mock_proj_no_sess) # Returns NULL# Create a mock project with sessions parts <- data.frame(participant_id = "01") fs <- data.frame(subid="01", session="test", datatype="func", suffix="bold.nii.gz", fmriprep=FALSE) mock_proj <- create_mock_bids("SessionMock", parts, fs) # Get session IDs sessions(mock_proj) # Project without sessions fs_no_session <- data.frame(subid="01", datatype="func", suffix="bold.nii.gz", fmriprep=FALSE) mock_proj_no_sess <- create_mock_bids("NoSessionMock", parts, fs_no_session) sessions(mock_proj_no_sess) # Returns NULL
Get the sidecar metadata attached to a tabular BIDS object
sidecar(x, ...) ## S3 method for class 'bids_tabular' sidecar(x, ...)sidecar(x, ...) ## S3 method for class 'bids_tabular' sidecar(x, ...)
x |
A |
... |
Additional arguments passed to methods. |
A named list of sidecar metadata, or an empty list if none.
tryCatch({ ds001_path <- get_example_bids_dataset("ds001") pt <- read_participants(ds001_path) sc <- sidecar(pt) # Example datasets are cached; leave the cache in place. }, error = function(e) message("Example requires internet: ", e$message))tryCatch({ ds001_path <- get_example_bids_dataset("ds001") pt <- read_participants(ds001_path) sc <- sidecar(pt) # Example datasets are cached; leave the cache in place. }, error = function(e) message("Example requires internet: ", e$message))
Retrieves paths to surface mesh files (GIFTI format, .gii) from a BIDS project, optionally filtered by hemisphere and surface type. Surface files are typically found in fMRIPrep derivatives and represent cortical surface reconstructions in various coordinate spaces.
surface_files( x, subid = ".*", session = ".*", hemi = ".*", surf_type = ".*", space = ".*", full_path = TRUE, ... ) ## S3 method for class 'bids_project' surface_files( x, subid = ".*", session = ".*", hemi = ".*", surf_type = ".*", space = ".*", full_path = TRUE, ... ) ## S3 method for class 'mock_bids_project' surface_files( x, subid = ".*", session = ".*", hemi = ".*", surf_type = ".*", space = ".*", full_path = TRUE, ... )surface_files( x, subid = ".*", session = ".*", hemi = ".*", surf_type = ".*", space = ".*", full_path = TRUE, ... ) ## S3 method for class 'bids_project' surface_files( x, subid = ".*", session = ".*", hemi = ".*", surf_type = ".*", space = ".*", full_path = TRUE, ... ) ## S3 method for class 'mock_bids_project' surface_files( x, subid = ".*", session = ".*", hemi = ".*", surf_type = ".*", space = ".*", full_path = TRUE, ... )
x |
A |
subid |
Regex pattern to match subject IDs (without "sub-" prefix).
Default |
session |
Regex pattern to match session IDs (without "ses-" prefix).
Default |
hemi |
Hemisphere filter: |
surf_type |
Surface type filter: |
space |
Regex pattern to match coordinate space (e.g., |
full_path |
Logical. If |
... |
Additional arguments passed to |
Character vector of file paths matching the criteria, or NULL if
no matching files are found.
# Get all surface files tryCatch({ ds_path <- get_example_bids_dataset("ds000001-fmriprep") proj <- bids_project(ds_path, fmriprep = TRUE) # All surfaces all_surfs <- surface_files(proj) # Left hemisphere pial surfaces only left_pial <- surface_files(proj, hemi = "L", surf_type = "pial") # All surfaces in fsnative space fsnative_surfs <- surface_files(proj, space = "fsnative") # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) })# Get all surface files tryCatch({ ds_path <- get_example_bids_dataset("ds000001-fmriprep") proj <- bids_project(ds_path, fmriprep = TRUE) # All surfaces all_surfs <- surface_files(proj) # Left hemisphere pial surfaces only left_pial <- surface_files(proj, hemi = "L", surf_type = "pial") # All surfaces in fsnative space fsnative_surfs <- surface_files(proj, space = "fsnative") # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) })
This function retrieves a sorted vector of unique task names from a BIDS project. Tasks in BIDS are typically represented in filenames with the pattern 'task-XX'. This function extracts and returns the unique task identifiers, filtering out any NULL or NA values.
tasks(x, ...) ## S3 method for class 'bids_project' tasks(x, ...)tasks(x, ...) ## S3 method for class 'bids_project' tasks(x, ...)
x |
the object to extract tasks from |
... |
extra args passed to methods |
A character vector of unique, sorted task names found in the BIDS project
# Get tasks from a BIDS project tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) tasks(proj) # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) })# Get tasks from a BIDS project tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) tasks(proj) # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) })
Extracts the unique task names found in the mock project's file structure. Note: Returns names without the "task-" prefix.
## S3 method for class 'mock_bids_project' tasks(x, ...)## S3 method for class 'mock_bids_project' tasks(x, ...)
x |
A |
... |
Extra arguments (ignored). |
Character vector of unique task names (e.g., c("rest", "nback")), sorted.
# Create a mock project with tasks parts <- data.frame(participant_id = "01") fs <- data.frame(subid="01", task="taskA", run="01", datatype="func", suffix="bold.nii.gz", fmriprep=FALSE) fs <- rbind(fs, data.frame(subid="01", task="taskB", run="01", datatype="func", suffix="bold.nii.gz", fmriprep=FALSE)) mock_proj <- create_mock_bids("TaskMock", parts, fs) # Get task names tasks(mock_proj)# Create a mock project with tasks parts <- data.frame(participant_id = "01") fs <- data.frame(subid="01", task="taskA", run="01", datatype="func", suffix="bold.nii.gz", fmriprep=FALSE) fs <- rbind(fs, data.frame(subid="01", task="taskB", run="01", datatype="func", suffix="bold.nii.gz", fmriprep=FALSE)) mock_proj <- create_mock_bids("TaskMock", parts, fs) # Get task names tasks(mock_proj)
Retrieves paths to transformation files (xfm, warp, affine) from a BIDS project, optionally filtered by source and target coordinate space. Transform files are typically found in fMRIPrep derivatives and encode spatial transformations between different coordinate spaces (e.g., T1w to MNI, boldref to T1w).
transform_files( x, subid = ".*", session = ".*", from = ".*", to = ".*", mode = ".*", kind = ".*", full_path = TRUE, ... ) ## S3 method for class 'bids_project' transform_files( x, subid = ".*", session = ".*", from = ".*", to = ".*", mode = ".*", kind = ".*", full_path = TRUE, ... ) ## S3 method for class 'mock_bids_project' transform_files( x, subid = ".*", session = ".*", from = ".*", to = ".*", mode = ".*", kind = ".*", full_path = TRUE, ... )transform_files( x, subid = ".*", session = ".*", from = ".*", to = ".*", mode = ".*", kind = ".*", full_path = TRUE, ... ) ## S3 method for class 'bids_project' transform_files( x, subid = ".*", session = ".*", from = ".*", to = ".*", mode = ".*", kind = ".*", full_path = TRUE, ... ) ## S3 method for class 'mock_bids_project' transform_files( x, subid = ".*", session = ".*", from = ".*", to = ".*", mode = ".*", kind = ".*", full_path = TRUE, ... )
x |
A |
subid |
Regex pattern to match subject IDs (without "sub-" prefix).
Default |
session |
Regex pattern to match session IDs (without "ses-" prefix).
Default |
from |
Regex pattern to match source space (the "from" BIDS entity).
Common values: "T1w", "boldref", "fsnative". Default |
to |
Regex pattern to match target space (the "to" BIDS entity).
Common values: "MNI152NLin2009cAsym", "T1w", "fsnative". Default |
mode |
Regex pattern to match transform mode entity. Default |
kind |
Transform type: |
full_path |
Logical. If |
... |
Additional arguments passed to |
Character vector of file paths matching the criteria, or NULL if
no matching files are found.
# Get all transform files tryCatch({ ds_path <- get_example_bids_dataset("ds000001-fmriprep") proj <- bids_project(ds_path, fmriprep = TRUE) # All transforms all_xfms <- transform_files(proj) # Transforms from T1w to MNI space t1_to_mni <- transform_files(proj, from = "T1w", to = "MNI152") # All transforms for a specific subject sub01_xfms <- transform_files(proj, subid = "01") # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) })# Get all transform files tryCatch({ ds_path <- get_example_bids_dataset("ds000001-fmriprep") proj <- bids_project(ds_path, fmriprep = TRUE) # All transforms all_xfms <- transform_files(proj) # Transforms from T1w to MNI space t1_to_mni <- transform_files(proj, from = "T1w", to = "MNI152") # All transforms for a specific subject sub01_xfms <- transform_files(proj, subid = "01") # Clean up # Example datasets are cached; leave the cache in place. }, error = function(e) { message("Example requires internet connection: ", e$message) })
Removes a previously registered custom datatype from the registry. Built-in datatypes cannot be removed.
unregister_datatype(name)unregister_datatype(name)
name |
Character string naming the datatype to remove. |
The name string, invisibly.
## Not run: register_datatype("dwi", spec = func_spec(), parser_fn = func_parser()) unregister_datatype("dwi") ## End(Not run)## Not run: register_datatype("dwi", spec = func_spec(), parser_fn = func_parser()) unregister_datatype("dwi") ## End(Not run)
Aggregates event tables, confound tables, and scan inventory into a single run-level tibble with normalized identifiers and nested list-columns. This is a lightweight variables layer for downstream R workflows rather than a full model-spec engine.
variables_table( x, subid = ".*", task = ".*", run = ".*", session = ".*", include = c("events", "confounds"), scope = c("all", "raw", "derivatives"), pipeline = NULL )variables_table( x, subid = ".*", task = ".*", run = ".*", session = ".*", include = c("events", "confounds"), scope = c("all", "raw", "derivatives"), pipeline = NULL )
x |
A |
subid |
Regex pattern to match subject IDs. |
task |
Regex pattern to match tasks. |
run |
Regex pattern to match runs. |
session |
Regex pattern to match sessions. |
include |
Which variable sources to include. Supported values are
|
scope |
Query scope used for scan inventory. One of |
pipeline |
Optional derivative pipeline name to restrict derivative scan inventory. |
A tibble with one row per run and list-columns scans, events, and
confounds when available.
tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) vt <- variables_table(proj) print(vt) # Example datasets are cached; leave the cache in place. }, error = function(e) message("Example requires internet: ", e$message))tryCatch({ ds001_path <- get_example_bids_dataset("ds001") proj <- bids_project(ds001_path) vt <- variables_table(proj) print(vt) # Example datasets are cached; leave the cache in place. }, error = function(e) message("Example requires internet: ", e$message))