bids.layout
.BIDSLayout¶
-
class
BIDSLayout
(root, validate=True, index_associated=True, absolute_paths=True, derivatives=False, config=None, sources=None, ignore=None, force_index=None, config_filename='layout_config.json', regex_search=False)[source]¶ Layout class representing an entire BIDS dataset.
Parameters: - root (str) – The root directory of the BIDS dataset.
- validate (bool) – If True, all files are checked for BIDS compliance when first indexed, and non-compliant files are ignored. This provides a convenient way to restrict file indexing to only those files defined in the “core” BIDS spec, as setting validate=True will lead files in supplementary folders like derivatives/, code/, etc. to be ignored.
- index_associated (bool) – Argument passed onto the BIDSValidator; ignored if validate = False.
- absolute_paths (bool) – If True, queries always return absolute paths. If False, queries return relative paths, unless the root argument was left empty (in which case the root defaults to the file system root).
- derivatives (bool, str, list) – Specifies whether and/or which derivatives to to index. If True, all pipelines found in the derivatives/ subdirectory will be indexed. If a str or list, gives the paths to one or more derivatives directories to index. If False or None, the derivatives/ directory is ignored during indexing, and derivatives will have to be added manually via add_derivatives().
- config (str, list) – Optional name(s) of configuration file(s) to use. By default (None), uses ‘bids’.
- sources (BIDLayout, list) – Optional BIDSLayout(s) from which the current BIDSLayout is derived.
- ignore (str, SRE_Pattern, list) – Path(s) to exclude from indexing. Each path is either a string or a SRE_Pattern object (i.e., compiled regular expression). If a string is passed, it must be either an absolute path, or be relative to the BIDS project root. If an SRE_Pattern is passed, the contained regular expression will be matched against the full (absolute) path of all files and directories.
- force_index (str, SRE_Pattern, list) – Path(s) to forcibly index in the BIDSLayout, even if they would otherwise fail validation. See the documentation for the ignore argument for input format details. Note that paths in force_index takes precedence over those in ignore (i.e., if a file matches both ignore and force_index, it will be indexed).
- config_filename (str) – Optional name of filename within directories that contains configuration information.
- regex_search (bool) – Whether to require exact matching (True) or regex search (False, default) when comparing the query string to each entity in .get() calls. This sets a default for the instance, but can be overridden in individual .get() requests.
Methods
add_derivatives
(path, **kwargs)Add BIDS-Derivatives datasets to tracking. build_path
(source[, path_patterns, strict, …])Constructs a target filename for a file or dictionary of entities. clone
()Return a deep copy of the current BIDSLayout. copy_files
([files, path_patterns, …])Copies one or more BIDSFiles to new locations defined by each BIDSFile’s entities and the specified path_patterns. get
([return_type, target, extensions, …])Retrieve files and/or metadata from the current Layout. get_bval
(path, **kwargs)Get bval file for passed path. get_bvec
(path, **kwargs)Get bvec file for passed path. get_collections
(level[, types, variables, …])Return one or more variable Collections in the BIDS project. get_fieldmap
(path[, return_list])Get fieldmap(s) for specified path. get_file
(filename[, scope])Returns the BIDSFile object with the specified path. get_metadata
(path[, include_entities])Return metadata found in JSON sidecars for the specified file. get_nearest
(path[, return_type, strict, …])Walk up the file tree from the specified path and return the nearest matching file(s). get_tr
([derivatives])Returns the scanning repetition time (TR) for one or more runs. parse_file_entities
(filename[, scope, …])Parse the passed filename for entity/value pairs. to_df
(**kwargs)Return information for all BIDSFiles tracked in the Layout as a pandas DataFrame. write_contents_to_file
(entities[, …])Write arbitrary data to a file defined by the passed entities and path patterns. -
add_derivatives
(path, **kwargs)[source]¶ Add BIDS-Derivatives datasets to tracking.
Parameters: - path (str, list) – One or more paths to BIDS-Derivatives datasets. Each path can point to either a derivatives/ directory containing one more more pipeline directories, or to a single pipeline directory (e.g., derivatives/fmriprep).
- kwargs (dict) – Optional keyword arguments to pass on to BIDSLayout() when initializing each of the derivative datasets.
-
build_path
(source, path_patterns=None, strict=False, scope='all')[source]¶ Constructs a target filename for a file or dictionary of entities.
Parameters: - source (str, BIDSFile, dict) –
The source data to use to construct the new file path. Must be one of: - A BIDSFile object - A string giving the path of a BIDSFile contained within the
current Layout.- A dict of entities, with entity names in keys and values in values
- path_patterns (list) – Optional path patterns to use to construct the new file path. If None, the Layout-defined patterns will be used.
- strict (bool) – If True, all entities must be matched inside a pattern in order to be a valid match. If False, extra entities will be ignored so long as all mandatory entities are found.
- scope (str, list) – The scope of the search space. Indicates which BIDSLayouts’ path patterns to use. See BIDSLayout docstring for valid values. By default, uses all available layouts. If two or more values are provided, the order determines the precedence of path patterns (i.e., earlier layouts will have higher precedence).
- source (str, BIDSFile, dict) –
-
copy_files
(files=None, path_patterns=None, symbolic_links=True, root=None, conflicts='fail', **kwargs)[source]¶ Copies one or more BIDSFiles to new locations defined by each BIDSFile’s entities and the specified path_patterns.
Parameters: - files (list) – Optional list of BIDSFile objects to write out. If none provided, use files from running a get() query using remaining **kwargs.
- path_patterns (str, list) – Write patterns to pass to each file’s write_file method.
- symbolic_links (bool) – Whether to copy each file as a symbolic link or a deep copy.
- root (str) – Optional root directory that all patterns are relative to. Defaults to current working directory.
- conflicts (str) –
Defines the desired action when the output path already exists. Must be one of:
’fail’: raises an exception ‘skip’ does nothing ‘overwrite’: overwrites the existing file ‘append’: adds a suffix to each file copy, starting with 1 - kwargs (kwargs) – Optional key word arguments to pass into a get() query.
-
get
(return_type='object', target=None, extensions=None, scope='all', regex_search=False, defined_fields=None, **kwargs)[source]¶ Retrieve files and/or metadata from the current Layout.
Parameters: - return_type (str) –
Type of result to return. Valid values: ‘object’ (default): return a list of matching BIDSFile objects. ‘file’: return a list of matching filenames. ‘dir’: return a list of directories. ‘id’: return a list of unique IDs. Must be used together with
a valid target. - target (str) – Optional name of the target entity to get results for (only used if return_type is ‘dir’ or ‘id’).
- extensions (str, list) – One or more file extensions to filter on. BIDSFiles with any other extensions will be excluded.
- scope (str, list) –
Scope of the search space. If passed, only nodes/directories that match the specified scope will be searched. Possible values include:
’all’ (default): search all available directories. ‘derivatives’: search all derivatives directories ‘raw’: search only BIDS-Raw directories <PipelineName>: the name of a BIDS-Derivatives pipeline - regex_search (bool or None) – Whether to require exact matching (False) or regex search (True) when comparing the query string to each entity.
- defined_fields (list) – Optional list of names of metadata fields that must be defined in JSON sidecars in order to consider the file a match, but which don’t need to match any particular value.
- kwargs (dict) – Any optional key/values to filter the entities on. Keys are entity names, values are regexes to filter on. For example, passing filter={ ‘subject’: ‘sub-[12]’} would return only files that match the first two subjects.
Returns: A list of BIDSFiles (default) or strings (see return_type).
- return_type (str) –
-
get_collections
(level, types=None, variables=None, merge=False, sampling_rate=None, skip_empty=False, **kwargs)[source]¶ Return one or more variable Collections in the BIDS project.
Parameters: - level (str) – The level of analysis to return variables for. Must be one of ‘run’, ‘session’, ‘subject’, or ‘dataset’.
- types (str, list) – Types of variables to retrieve. All valid values
- the filename stipulated in the BIDS spec for each kind of (reflect) –
- Valid values include (variable.) – ‘events’, ‘physio’, ‘stim’,
- 'participants', 'sessions', and 'regressors'. ('scans',) –
- variables (list) – Optional list of variables names to return. If None, all available variables are returned.
- merge (bool) – If True, variables are merged across all observations of the current level. E.g., if level=’subject’, variables from all subjects will be merged into a single collection. If False, each observation is handled separately, and the result is returned as a list.
- sampling_rate (int, str) – If level=’run’, the sampling rate to pass onto the returned BIDSRunVariableCollection.
- skip_empty (bool) – Whether or not to skip empty Variables (i.e., where there are no rows/records in a file after applying any filtering operations like dropping NaNs).
- kwargs – Optional additional arguments to pass onto load_variables.
-
get_file
(filename, scope='all')[source]¶ Returns the BIDSFile object with the specified path.
Parameters: - filename (str) – The path of the file to retrieve. Must be either an absolute path, or relative to the root of this BIDSLayout.
- scope (str, list) – Scope of the search space. If passed, only BIDSLayouts that match the specified scope will be searched. See BIDSLayout docstring for valid values.
Returns: A BIDSFile, or None if no match was found.
-
get_metadata
(path, include_entities=False, **kwargs)[source]¶ Return metadata found in JSON sidecars for the specified file.
Parameters: - path (str) – Path to the file to get metadata for.
- include_entities (bool) – If True, all available entities extracted from the filename (rather than JSON sidecars) are included in the returned metadata dictionary.
- kwargs (dict) – Optional keyword arguments to pass onto get_nearest().
- Returns: A dictionary of key/value pairs extracted from all of the
- target file’s associated JSON sidecars.
Notes
A dictionary containing metadata extracted from all matching .json files is returned. In cases where the same key is found in multiple files, the values in files closer to the input filename will take precedence, per the inheritance rules in the BIDS specification.
-
get_nearest
(path, return_type='file', strict=True, all_=False, ignore_strict_entities=None, full_search=False, **kwargs)[source]¶ Walk up the file tree from the specified path and return the nearest matching file(s).
Parameters: - path (str) – The file to search from.
- return_type (str) – What to return; must be one of ‘file’ (default) or ‘tuple’.
- strict (bool) – When True, all entities present in both the input path and the target file(s) must match perfectly. When False, files will be ordered by the number of matching entities, and partial matches will be allowed.
- all (bool) – When True, returns all matching files. When False (default), only returns the first match.
- ignore_strict_entities (list) – Optional list of entities to exclude from strict matching when strict is True. This allows one to search, e.g., for files of a different type while matching all other entities perfectly by passing ignore_strict_entities=[‘type’].
- full_search (bool) – If True, searches all indexed files, even if they don’t share a common root with the provided path. If False, only files that share a common root will be scanned.
- kwargs – Optional keywords to pass on to .get().
-
get_tr
(derivatives=False, **selectors)[source]¶ Returns the scanning repetition time (TR) for one or more runs.
Parameters: - derivatives (bool) – If True, also checks derivatives images.
- selectors – Optional keywords used to constrain the selected runs. Can be any arguments valid for a .get call (e.g., BIDS entities or JSON sidecar keys).
Returns: A single float.
Notes: Raises an exception if more than one unique TR is found.
-
parse_file_entities
(filename, scope='all', entities=None, config=None, include_unmatched=False)[source]¶ Parse the passed filename for entity/value pairs.
Parameters: - filename (str) – The filename to parse for entity values
- scope (str, list) – The scope of the search space. Indicates which BIDSLayouts’ entities to extract. See BIDSLayout docstring for valid values. By default, extracts all entities
- entities (list) – An optional list of Entity instances to use in extraction. If passed, the scope and config arguments are ignored, and only the Entities in this list are used.
- config (str, Config, list) – One or more Config objects, or paths to JSON config files on disk, containing the Entity definitions to use in extraction. If passed, scope is ignored.
- include_unmatched (bool) – If True, unmatched entities are included in the returned dict, with values set to None. If False (default), unmatched entities are ignored.
- Returns: A dict, where keys are Entity names and values are the
- values extracted from the filename.
-
to_df
(**kwargs)[source]¶ Return information for all BIDSFiles tracked in the Layout as a pandas DataFrame.
Parameters: kwargs – Optional keyword arguments passed on to get(). This allows one to easily select only a subset of files for export. Returns: - A pandas DataFrame, where each row is a file, and each column is
- a tracked entity. NaNs are injected whenever a file has no value for a given attribute.
-
write_contents_to_file
(entities, path_patterns=None, contents=None, link_to=None, content_mode='text', conflicts='fail', strict=False)[source]¶ Write arbitrary data to a file defined by the passed entities and path patterns.
Parameters: - entities (dict) – A dictionary of entities, with Entity names in keys and values for the desired file in values.
- path_patterns (list) – Optional path patterns to use when building the filename. If None, the Layout-defined patterns will be used.
- contents (object) – Contents to write to the generate file path. Can be any object serializable as text or binary data (as defined in the content_mode argument).
- link_to (str) – Optional path with which to create a symbolic link to. Used as an alternative to and takes priority over the contents argument.
- conflicts (str) –
Defines the desired action when the output path already exists. Must be one of:
’fail’: raises an exception ‘skip’ does nothing ‘overwrite’: overwrites the existing file ‘append’: adds a suffix to each file copy, starting with 1 - strict (bool) – If True, all entities must be matched inside a pattern in order to be a valid match. If False, extra entities