nwb2bids#

NWB2BIDS#

Reorganize NWB files into a BIDS directory layout.

convert_nwb_dataset(*, nwb_paths: ~typing.Annotated[list[~typing.Annotated[~pathlib.Path, ~pydantic.types.PathType(path_type=file), ~pydantic.functional_validators.BeforeValidator(func=~nwb2bids._core._convert_nwb_dataset._make_absolute, json_schema_input_type=PydanticUndefined)] | ~typing.Annotated[~pathlib.Path, ~pydantic.types.PathType(path_type=dir), ~pydantic.functional_validators.BeforeValidator(func=~nwb2bids._core._convert_nwb_dataset._make_absolute, json_schema_input_type=PydanticUndefined)]], ~annotated_types.MinLen(min_length=1)], run_config: ~nwb2bids._converters._run_config.RunConfig = FieldInfo(annotation=NoneType, required=False, default_factory=<lambda>)) DatasetConverter[source]#

Convert a dataset of NWB files to a BIDS dataset.

Parameters:
  • nwb_paths (any iterable of file or directory paths) – An iterable of NWB file paths and directories containing NWB files.

  • run_config (RunConfig, optional) – The configuration for this conversion run.

Returns:

dataset_converter – The DatasetConverter used to perform the conversion. Contains notifications and other contextual information about the conversion process.

Return type:

DatasetConverter

class RunConfig(
*,
bids_directory: Path = <factory>,
additional_metadata_file_path: Path,
~pydantic.types.PathType(path_type=file)] | None = None,
file_mode: Literal['move',
'copy',
'symlink']=<factory>,
cache_directory: Path,
~pydantic.types.PathType(path_type=dir)] = <factory>,
sanitization_config: SanitizationConfig = <factory>,
run_id: str = <factory>,
space: Literal['AllenCCFv3',
'PaxinosWatson'] | None=None,
archive_target: Literal['dandi',
'ember'] | None=None,
use_session_labels: bool = False,
probe: str | None = None,
silent: bool = False,
)[source]#

Bases: BaseModel

Specifies configuration options for a single run of NWB to BIDS conversion.

bids_directorydirectory path

The path to the directory where the BIDS dataset will be created. Defaults to the current working directory and checks if it is either empty or a BIDS dataset.

additional_metadata_file_pathfile path, optional

The path to a YAML file containing additional metadata not included within the NWB files that you wish to include in the BIDS dataset.

file_modeone of “move”, “copy”, or “symlink”
Specifies how to handle the NWB files when converting to BIDS format.
  • “move”: Move the files to the BIDS directory.

  • “copy”: Copy the files to the BIDS directory. Copy-on-write is supported and used on systems that allow it, but requires Python 3.14 to use.

  • “symlink”: Create symbolic links to the files in the BIDS directory.

  • if not specified, decide between all the above based on the system, with preference for linking when possible.

cache_directorydirectory path

The directory where run specific files (e.g., notifications, sanitization reports) will be stored. Defaults to ~/.nwb2bids.

sanitization_confignwb2bids.SanitizationConfig

Specifies the types of sanitization to apply when creating the BIDS dataset. Read more about the specific options from nwb2bids.sanitization.SanitizationConfig?.

run_idstr

On each unique run of nwb2bids, a run ID is generated. Set this option to override this to any identifying string. This ID is used in the naming of the files saved to your run directory. The default ID uses runtime timestamp information of the form “date-%Y%m%d_time-%H%M%S.”

archive_targetone of “dandi”, “ember”, or None, default: None

The archive you intend to upload the BIDS dataset to. When set to a non-None value, a .bidsignore file is created in the BIDS directory containing dandiset.yaml, since dandiset.yaml is not part of the BIDS specification. If None, then no .bidsignore file is created.

use_session_labelsbool, default: False

When True, ses- labels and session-level subdirectories are always included in BIDS output, even when every subject has only a single session. By default (False), ses- labels are omitted for single-session subjects unless more than 50% of subjects have multiple sessions, in which case they are applied to all subjects for dataset-level consistency.

silentbool, default: False

Whether to suppress progress bar output during conversion. Set to True to hide all progress bars (e.g., when --silent is used via the CLI).

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

bids_directory: Path#
additional_metadata_file_path: Annotated[Path, PathType(path_type=file)] | None#
file_mode: Literal['move', 'copy', 'symlink']#
cache_directory: Annotated[Path, PathType(path_type=dir)]#
sanitization_config: SanitizationConfig#
run_id: str#
space: Literal['AllenCCFv3', 'PaxinosWatson'] | None#
archive_target: Literal['dandi', 'ember'] | None#
use_session_labels: bool#
probe: str | None#
silent: bool#
model_config = {'frozen': True, 'validate_default': True}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

model_post_init(context: Any, /) None[source]#

Override this method to perform additional initialization after __init__ and model_construct. This is useful if you want to do some validation that requires the entire model to be initialized.

property sanitization_file_path: Path#

The file path leading to a record of sanitizations made.

property notifications_file_path: Path#

The file path leading to a human-readable notifications report.

property notifications_json_file_path: Path#

The file path leading to a JSON dump of the notifications.

classmethod validate_bids_directory(value: Path) Path[source]#
class DatasetConverter(*, run_config: ~nwb2bids._converters._run_config.RunConfig = <factory>, session_converters: list[~nwb2bids._converters._session_converter.SessionConverter], dataset_description: ~nwb2bids.bids_models._dataset_description.DatasetDescription | None = None)[source]#

Bases: BaseConverter

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

session_converters: list[SessionConverter]#
dataset_description: DatasetDescription | None#
property notifications: list[Notification]#

All notifications from contained session converters.

These can accumulate over time based on which instance methods have been called.

classmethod from_remote_dandiset(
dandiset_id: str = FieldInfo(annotation=NoneType,
required=True,
metadata=[_PydanticGeneralMetadata(pattern='^\\d{6}$')]),
api_url: str | None = None,
version_id: str = 'draft',
token: str | None = None,
limit: int | None = None,
run_config: RunConfig = FieldInfo(annotation=NoneType,
required=False,
default_factory=<lambda>),
) Self[source]#

Initialize a converter of a Dandiset to BIDS format.

Parameters:
  • dandiset_id (str) – The dandiset ID of the Dandiset to be converted.

  • api_url (str, optional) – The API URL of a custom DANDI instance to use. If not provided, the API URL of the DANDI instance specified by the DANDI_INSTANCE environment variable is used. If the DANDI_INSTANCE environment variable is not specified, The API URL of the “dandi” DANDI instance is used.

  • version_id (str, default: “draft”) – The version ID of the Dandiset to be converted.

  • token (str, optional) – The authentication token for accessing the DANDI instance. If not provided, will attempt to read from the environment variable DANDI_API_KEY if it exists. This is required for accessing embargoed Dandisets.

  • limit (int, optional) – If specified, limits the number of sessions to convert. This is mainly useful for testing purposes.

  • run_config (RunConfig, optional) – The configuration for this conversion run.

classmethod from_nwb_paths(
nwb_paths: list[~typing.Annotated[~pathlib.Path,
~pydantic.types.PathType(path_type=file)] | ~typing.Annotated[~pathlib.Path,
~pydantic.types.PathType(path_type=dir)]] = FieldInfo(annotation=NoneType,
required=True,
metadata=[MinLen(min_length=1)]),
run_config: RunConfig = FieldInfo(annotation=NoneType,
required=False,
default_factory=<lambda>),
) Self[source]#

Initialize a converter of NWB files to BIDS format.

Parameters:
  • nwb_paths (iterable of file and directory paths) – An iterable of NWB file paths and directories containing NWB files.

  • run_config (RunConfig, optional) – The configuration for this conversion run.

Return type:

An instance of DatasetConverter.

extract_metadata() None[source]#

Extract essential metadata used by the BIDS standard from the source NWB files.

convert_to_bids_dataset() None[source]#

Convert the directory of NWB files to a BIDS dataset.

write_bidsignore() None[source]#

Write the .bidsignore file if an archive target of “dandi” or “ember” is specified.

write_dataset_description() None[source]#

Write the dataset_description.json file.

write_participants_metadata() None[source]#

Write the participants.tsv and participants.json files.

write_sessions_metadata() None[source]#

Write the _sessions.tsv and _sessions.json files, then create empty participant and session directories.

Sessions metadata files and ses- subdirectories are only written for subjects that use session labels (i.e., subjects with multiple sessions, or all subjects when more than 50% have multiple sessions).

model_config = {}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

model_post_init(context: Any, /) None#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Args:

self: The BaseModel instance. context: The context.

class SessionConverter(*, run_config: ~nwb2bids._converters._run_config.RunConfig = <factory>, session_id: str, nwbfile_paths: ~typing.Annotated[list[~typing.Annotated[~pathlib.Path, ~pydantic.types.PathType(path_type=file)]] | list[~pydantic.networks.HttpUrl], ~annotated_types.MinLen(min_length=1)], session_metadata: ~nwb2bids.bids_models._bids_session_metadata.BidsSessionMetadata | None = None, notifications: ~typing.Annotated[list[~nwb2bids.notifications._notification.Notification], ~annotated_types.Ge(ge=0)] = <factory>, modality: ~typing.Literal['ecephys', 'icephys'] | None = None, use_session_labels: bool = True)[source]#

Bases: BaseConverter

Initialize a converter of NWB files to BIDS format.

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

session_id: str#
nwbfile_paths: list[Annotated[Path, PathType(path_type=file)]] | list[HttpUrl]#
session_metadata: BidsSessionMetadata | None#
notifications: list[Notification]#
modality: Literal['ecephys', 'icephys'] | None#
use_session_labels: bool#
classmethod from_nwb_paths(
nwb_paths: list[~typing.Annotated[~pathlib.Path,
~pydantic.types.PathType(path_type=file)] | ~typing.Annotated[~pathlib.Path,
~pydantic.types.PathType(path_type=dir)]] = FieldInfo(annotation=NoneType,
required=True,
metadata=[MinLen(min_length=1)]),
run_config: RunConfig = FieldInfo(annotation=NoneType,
required=False,
default_factory=<lambda>),
ignore_hidden: bool = True,
) list[Self][source]#

Initialize a list of session converters from a list of NWB file paths.

Automatically associates multiple NWB files to a single session according to session ID.

Parameters:
  • nwb_paths (iterable of file and directory paths) – An iterable of NWB file paths and directories containing NWB files.

  • run_config (RunConfig, optional) – The configuration for this conversion run.

  • ignore_hidden (bool, default: True) – Whether to ignore NWB files located under directories (those starting with a period).

Return type:

A list of SessionConverter instances, one per unique session ID.

extract_metadata() None[source]#

Extract essential metadata used by the BIDS standard from the source NWB files.

convert_to_bids_session() None[source]#

Convert the NWB file to a BIDS session directory.

write_ephys_files() None[source]#

Write the _probes, _channels, and _electrodes metadata files, both .tsv and .json, for this session.

write_events_files() None[source]#

Write the _events.tsv and _events.json files for this session.

model_config = {}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

model_post_init(context: Any, /) None#

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Args:

self: The BaseModel instance. context: The context.

class Notification(
*,
identifier: str | None = None,
title: str,
reason: str,
solution: str,
examples: list[str] | None = None,
field: str | None = None,
data_standards: list[DataStandard] | None = None,
source_file_paths: list[Path] | list[HttpUrl] | None = None,
target_file_paths: list[Path] | list[HttpUrl] | None = None,
category: Category,
severity: Severity,
)[source]#

Bases: BaseModel

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

identifier: str | None#
title: str#
reason: str#
solution: str#
examples: list[str] | None#
field: str | None#
data_standards: list[DataStandard] | None#
source_file_paths: list[Path] | list[HttpUrl] | None#
target_file_paths: list[Path] | list[HttpUrl] | None#
category: Category#
severity: Severity#
model_config = {'validate_assignment': True}#

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

classmethod from_definition(
identifier: str,
source_file_paths: list[Path] | list[HttpUrl] | None = None,
target_file_paths: list[Path] | list[HttpUrl] | None = None,
traceback: str | None = None,
) Self[source]#
classmethod validate_source_file_paths(value: list[str] | None) list[str] | None[source]#

Remove any paths that contain ‘remfile’, which NWB source container fields include automatically.