rtCommon.bidsIncremental


bidsIncremental.py

Implements the BIDS Incremental data type used for streaming BIDS data between different applications.


Module Contents

Classes

BidsIncremental

Attributes

logger

rtCommon.bidsIncremental.logger
class rtCommon.bidsIncremental.BidsIncremental(image: nibabel.Nifti1Image, imageMetadata: dict, datasetDescription: dict = None)
ENTITIES
REQUIRED_IMAGE_METADATA = ['subject', 'task', 'suffix', 'datatype', 'RepetitionTime']

BIDS Incremental data format suitable for streaming BIDS Archives

_imgMetadata

Store dataset description

__str__(self)

Return str(self).

__eq__(self, other)

Return self==value.

__getstate__(self)
__setstate__(self, state)
_preprocessMetadata(self, imageMetadata: dict) dict

Pre-process metadata to extract any additonal metadata that might be embedded in the provided metadata, like ProtocolName, and ensure that certain metadata values (e.g., RepetitionTime) are within BIDS-specified ranges.

Parameters

imageMetadata – Metadata dictionary provided to BIDS incremental to search for additional, embedded metadata

Returns

Original dictionary with all embedded metadata added explicitly and

values within BIDS-specified ranges.

_exceptIfMissingMetadata(self, imageMetadata: dict) None

Ensure that all required metadata is present.

Parameters

imageMetadata – Metadata dictionary to check for missing metadata

Raises

MissingMetadataError – If not all required metadata is present.

_postprocessMetadata(self, imageMetadata: dict) dict

Post-process metadata once all required fields are given (e.g., to create derived fields like ‘TaskName’ from ‘task’).

Parameters

imageMetadata – Metadata dictionary to post-process.

Returns

Metadata dictionary with derived fields set.

static createImageMetadataDict(subject: str, task: str, suffix: str, datatype: str, repetitionTime: int)

Creates an image metadata dictionary for a BIDS-I with all of the basic required fields using the correct key names.

Parameters
  • subject – Subject ID (e.g., ‘01’)

  • task – Task ID (e.g., ‘story’)

  • suffix – Imaging method (e.g., ‘bold’)

  • datatype – Data type (e.g., ‘func’ or ‘anat’)

  • repetitionTime – TR time, in seconds, used for the imaging run

Returns

Dictionary with the provided information ready for use in a BIDS-I

classmethod findMissingImageMetadata(cls, imageMeta: dict) list

Creates a list of all required metadata fields that the argument dictionary is missing.

Parameters

imageMeta – Metadata dictionary to check for missing fields

Returns

List of required fields missing in the provided dictionary.

Examples

>>> meta = {'subject': '01', 'task': 'test', 'suffix': 'bold',
            'datatype': 'func'}
>>> BidsIncremental.findMissingImageMetadata(meta)
['RepetitionTime']
classmethod isCompleteImageMetadata(cls, imageMeta: dict) bool

Verifies that all required metadata fields for BIDS-I construction are present in the dictionary.

Parameters

imageMeta – The dictionary with the metadata fields

Returns

True if all required fields are present in the dictionary, False otherwise.

Examples

>>> meta = {'subject': '01', 'task': 'test', 'suffix': 'bold',
            'datatype': 'func'}
>>> BidsIncremental.isCompleteImageMetadata(meta)
False
_exceptIfNotBids(self, entityName: str) None

Raise an exception if the argument is not a valid BIDS entity

getMetadataField(self, field: str, strict: bool = False) Any

Get value for the field in the incremental’s metadata, if it exists.

Parameters
  • field – Metadata field to retrieve a value for.

  • default – Default value to return if field is not present.

  • strict – Only allow getting fields that are defined as BIDS entities in the standard.

Returns

Entity’s value, or None if the entity isn’t present in the metadata.

Raises
  • ValueError – If ‘strict’ is True and ‘field’ is not a BIDS entity.

  • KeyError – If the field is not present in the Incremental’s metadata and not default value is provided.

Examples

>>> incremental.getMetadataField('task')
'faces'
>>> incremental.getMetadataField('RepetitionTime')
1.5
>>> incremental.getMetadataField('RepetitionTime', strict=True)
ValueError: RepetitionTime is not a valid BIDS entity name
setMetadataField(self, field: str, value: Any, strict: bool = False) None

Set metadata field to provided value in Incremental’s metadata.

Parameters
  • field – Metadata field to set value for.

  • value – Value to set for the provided entity.

  • strict – Only allow setting fields that are defined as BIDS entities in the standard.

Raises

ValueError – If ‘strict’ is True and ‘field’ is not a BIDS entity.

removeMetadataField(self, field: str, strict: bool = False) None

Remove a piece of metadata from the incremental’s metadata.

Parameters
  • field – BIDS entity name to retrieve a value for.

  • strict – Only allow removing fields that are defined as BIDS entities in the standard.

Raises
  • ValueError – If ‘strict’ is True and ‘field’ is not a BIDS entity.

  • RuntimeError – If the field to be removed is required by the Incremental.

getImageMetadata(self)
getSuffix(self) str
getDatatype(self) str

func or anat

getEntities(self) dict
getImageDimensions(self) tuple
getImageHeader(self)
getImageData(self) numpy.ndarray
makeBidsFileName(self, extension: rtCommon.bidsCommon.BidsFileExtension) str

Create the a BIDS-compatible file name based on the metadata. General format of the filename, per BIDS standard 1.4.1, is as follows (items in [square brackets] are considered optional):

sub-<label>[_ses-<label>]_task-<label>[_acq-<label>] [_ce-<label>] [_dir-<label>][_rec-<label>][_run-<index>] [_echo-<index>]_<contrast_label >.ext

Parameters

extension – The extension for the file, e.g., ‘nii’ for images or ‘json’ for metadata

Returns

Filename from metadata according to BIDS standard 1.4.1.

getDatasetName(self) str
getImageFileName(self) str
getMetadataFileName(self) str
getEventsFileName(self) str
getImageFilePath(self) str
getMetadataFilePath(self) str
getEventsFilePath(self) str
getDataDirPath(self) str

Path to where this incremental’s data would be in a BIDS archive, relative to the archive root.

Returns

Path string relative to root of the imaginary dataset.

Examples

>>> print(bidsi.getDataDirPath())
sub-01/ses-2011/anat
getAcquisitionTime(self) datetime.datetime.time

Returns the acquisition time as a datetime.time

getRepetitionTime(self) float

Returns the TR repetition time in seconds

timeToNextTr(self, clockSkew, now=None) float

Based on acquisition time returns seconds to next TR start

writeToDisk(self, datasetRoot: str, onlyData=False) None

Writes the incremental’s data to a directory on disk. NOTE: The directory is assumed to be empty, and no checks are made for data that would be overwritten.

Parameters
  • datasetRoot – Path to the root of the BIDS archive to be written to.

  • onlyData – Only write out the NIfTI image and sidecar metadata (Default False). Useful if writing an incremental out to an existing archive and you don’t want to overwrite existing README or dataset_description.json files.

Examples

>>> from bidsArchive import BidsArchive
>>> incremental = BidsIncremental(image, metadata)
>>> root = '/tmp/emptyDirectory'
>>> incremental.writeToDisk(root)
>>> archive = BidsArchive(root)
>>> print(archive)
Root: /tmp/emptyDirectory | Subjects: 1 | Sessions: 1 | Runs: 1