Skip to main content

BidsLayout

Struct BidsLayout 

Source
pub struct BidsLayout {
    pub is_derivative: bool,
    pub source_pipeline: Option<String>,
    /* private fields */
}
Expand description

The main entry point for interacting with a BIDS dataset.

BidsLayout indexes a BIDS dataset directory into a SQLite database and provides a fluent query API for finding files by their BIDS entities. It handles JSON sidecar metadata inheritance, file associations, derivative datasets, and path building.

This is the Rust equivalent of PyBIDS’ BIDSLayout class.

§Thread Safety

BidsLayout wraps a rusqlite::Connection and is therefore !Send and !Sync. It cannot be shared across threads or sent to async tasks.

For multi-threaded or async workloads:

  1. Save once, load per-thread — Use save() to persist the index, then load() in each thread/task:

    let layout = BidsLayout::new("/data").unwrap();
    layout.save(std::path::Path::new("/tmp/index.sqlite")).unwrap();
    
    // In each thread:
    let local = BidsLayout::load(std::path::Path::new("/tmp/index.sqlite")).unwrap();
  2. Create per-thread — Call BidsLayout::new() in each thread. The directory walk is fast for typical datasets (< 100ms for 10k files).

§Creating a Layout

use bids_layout::BidsLayout;

// Simple: index with defaults (validation enabled, in-memory database)
let layout = BidsLayout::new("/path/to/bids/dataset").unwrap();

// Builder: customize indexing behavior
let layout = BidsLayout::builder("/path/to/dataset")
    .validate(false)                            // skip BIDS validation
    .database_path("/tmp/index.sqlite")         // persistent database
    .index_metadata(true)                       // index JSON sidecars
    .add_derivative("/path/to/derivatives/fmriprep")
    .build()
    .unwrap();

§Querying Files

// Fluent query API
let files = layout.get()
    .suffix("bold")
    .extension(".nii.gz")
    .subject("01")
    .task("rest")
    .collect().unwrap();

// Get unique entity values
let subjects = layout.get_subjects().unwrap();
let tasks = layout.get_tasks().unwrap();

// Get metadata with BIDS inheritance
let md = layout.get_metadata(&files[0].path).unwrap();
let tr = md.get_f64("RepetitionTime");

§Derivatives

layout.add_derivatives("/path/to/derivatives").unwrap();

// Query across raw + derivatives
let all_files = layout.get().scope("all").suffix("bold").collect().unwrap();

// Query derivatives only
let deriv_files = layout.get().scope("derivatives").collect().unwrap();

Fields§

§is_derivative: bool§source_pipeline: Option<String>

Implementations§

Source§

impl BidsLayout

Source

pub fn new(root: impl AsRef<Path>) -> Result<Self>

Create a new layout with default settings (validation enabled, in-memory DB).

§Errors

Returns an error if the root path doesn’t exist, dataset_description.json is missing or invalid, or the filesystem walk fails.

Source

pub fn builder(root: impl AsRef<Path>) -> LayoutBuilder

Source

pub fn load(database_path: &Path) -> Result<Self>

Load a layout from an existing database file.

§Errors

Returns an error if the database file doesn’t exist, can’t be opened, or doesn’t contain valid layout info.

Source

pub fn save(&self, path: &Path) -> Result<()>

Save the database to a file for later reloading with BidsLayout::load.

§Errors

Returns a database error if the backup operation fails.

Source

pub fn root(&self) -> &Path

Source

pub fn description(&self) -> Option<&DatasetDescription>

Source

pub fn bids_version(&self) -> Option<&str>

The BIDS specification version declared in dataset_description.json.

Source

pub fn spec_compatibility(&self) -> Option<&Compatibility>

Compatibility between the dataset’s BIDS version and this library.

Returns None if no dataset_description.json was found (e.g., for derivative datasets loaded without validation).

Source

pub fn get(&self) -> GetBuilder<'_>

Start building a query.

Source

pub fn get_subjects(&self) -> Result<Vec<String>>

Source

pub fn get_sessions(&self) -> Result<Vec<String>>

Source

pub fn get_tasks(&self) -> Result<Vec<String>>

Source

pub fn get_runs(&self) -> Result<Vec<String>>

Source

pub fn get_datatypes(&self) -> Result<Vec<String>>

Source

pub fn get_suffixes(&self) -> Result<Vec<String>>

Source

pub fn get_entities(&self) -> Result<Vec<String>>

Source

pub fn get_entity_values(&self, entity: &str) -> Result<Vec<String>>

Source

pub fn get_file(&self, path: impl AsRef<Path>) -> Result<Option<BidsFile>>

Get a specific file by path.

Source

pub fn get_metadata(&self, path: impl AsRef<Path>) -> Result<BidsMetadata>

Get metadata for a file.

Source

pub fn get_tr(&self, filters: &[QueryFilter]) -> Result<f64>

Get the scanning repetition time (TR) for matching runs.

Source

pub fn get_bvec(&self, path: impl AsRef<Path>) -> Result<Option<BidsFile>>

Get bvec file for a path.

Source

pub fn get_gradient_table( &self, path: impl AsRef<Path>, ) -> Result<GradientTable>

Load the gradient table (b-values + b-vectors) for a DWI file.

Looks up the companion .bval and .bvec files and parses them into a bids_io::gradient::GradientTable.

§Errors

Returns an error if the companion files aren’t found or can’t be parsed.

Source

pub fn get_bval(&self, path: impl AsRef<Path>) -> Result<Option<BidsFile>>

Get bval file for a path.

Source

pub fn add_derivatives(&mut self, path: impl AsRef<Path>) -> Result<()>

Add a derivatives directory.

Source

pub fn get_derivative(&self, name: &str) -> Option<&BidsLayout>

Source

pub fn derivatives(&self) -> &HashMap<String, BidsLayout>

Source

pub fn get_nearest( &self, path: impl AsRef<Path>, filters: &[QueryFilter], ) -> Result<Option<BidsFile>>

Get the nearest file matching filters, walking up the directory tree.

Source

pub fn parse_file_entities(&self, filename: &str) -> Entities

Parse entities from a filename using this layout’s config.

Source

pub fn build_path( &self, source: &Entities, path_patterns: Option<&[&str]>, strict: bool, ) -> Result<String>

Build a path from entities using this layout’s config patterns.

Source

pub fn to_df(&self, metadata: bool) -> Result<Vec<(String, String, String)>>

Export file index as rows of (path, entity_name, value).

Source

pub fn clone_layout(&self) -> Result<Self>

Deep copy the layout.

Source

pub fn get_fieldmap( &self, path: impl AsRef<Path>, ) -> Result<Vec<HashMap<String, String>>>

Get fieldmap(s) for a specified file path.

Source

pub fn copy_files( &self, path_patterns: &[&str], mode: CopyMode, root: Option<&Path>, filters: &[QueryFilter], ) -> Result<Vec<PathBuf>>

Copy BIDSFiles to new locations defined by path patterns.

Source

pub fn write_to_file( &self, entities: &Entities, path_patterns: Option<&[&str]>, contents: &[u8], strict: bool, ) -> Result<PathBuf>

Write data to a file defined by entities and path patterns.

Source

pub fn sanitize_query_dtypes(&self, entities: &mut Entities)

Auto-convert entity query values to correct dtype.

Source

pub fn get_associations( &self, path: &str, kind: Option<&str>, ) -> Result<Vec<BidsFile>>

Get file associations from the database.

Trait Implementations§

Source§

impl Display for BidsLayout

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.