rtCommon.bidsCommon


bidsCommon.py

Shared constants and functions used by modules working with BIDS data.


Module Contents

Classes

BidsFileExtension

Generic enumeration.

BidsEntityKeys

Generic enumeration.

Functions

loadBidsEntities() → dict

Loads all accepted BIDS entities from PyBids into a dictionary.

filterEntities(metadata: dict) → dict

Returns a new dictionary containing all the elements of the argument that

getNiftiData(image: nibabel.Nifti1Image) → numpy.ndarray

Nibabel exposes a get_fdata() method, but this converts all the data to

makeDicomFieldBidsCompatible(dicomField: str) → str

Remove non-alphanumeric characters to make a DICOM field name

correct3DHeaderTo4D(image: nibabel.Nifti1Image, repetitionTime: int, timeUnitCode: int = 8) → None

Makes necessary changes to the NIfTI header to reflect the increase in its

adjustTimeUnits(imageMetadata: dict) → None

Validates and converts in-place the units of various time-based metadata,

metadataFromProtocolName(protocolName: str) → dict

Extracts BIDS label-value combinations from a DICOM protocol name, if

getDicomMetadata(dicomImg: pydicom.dataset.Dataset, kind='all') → dict

Returns the public (even-numbered tags) and private (odd-numbered tags)

symmetricDictDifference(d1: dict, d2: dict, equal: Callable[[Any, Any], bool] = opeq) → dict

Returns the symmetric difference of the provided dictionaries. This

niftiHeadersAppendCompatible(header1: dict, header2: dict)

Verifies that two Nifti image headers match in along a defined set of

niftiImagesAppendCompatible(img1: nibabel.Nifti1Image, img2: nibabel.Nifti1Image) → Tuple[bool, str]

Verifies that two Nifti images have headers matching along a defined set of

metadataAppendCompatible(meta1: dict, meta2: dict) → Tuple[bool, str]

Verifies two metadata dictionaries match in a set of required fields. If a

correctEventsFileDatatypes(df: pandas.DataFrame) → pandas.DataFrame

writeDataFrameToEvents(df: pandas.DataFrame, path: str) → None

Attributes

logger

BIDS_VERSION

DATASET_DESC_REQ_FIELDS

DEFAULT_DATASET_DESC

DEFAULT_README

DEFAULT_EVENTS_HEADERS

BIDS_FILE_PATTERN

BIDS_DIR_PATH_PATTERN

BIDS_FILE_PATH_PATTERN

PYBIDS_PSEUDO_ENTITIES

BIDS_EVENT_COL_TO_DTYPE

BidsAttributesToAnonymize

UNIT_TO_CODE

CODE_TO_UNIT

rtCommon.bidsCommon.logger
rtCommon.bidsCommon.BIDS_VERSION = 1.4.1
rtCommon.bidsCommon.DATASET_DESC_REQ_FIELDS = ['Name', 'BIDSVersion']
rtCommon.bidsCommon.DEFAULT_DATASET_DESC
rtCommon.bidsCommon.DEFAULT_README = Generated BIDS-Incremental Dataset from RT-Cloud
rtCommon.bidsCommon.DEFAULT_EVENTS_HEADERS = ['onset', 'duration']
rtCommon.bidsCommon.BIDS_FILE_PATTERN = sub-{subject}[_ses-{session}]_task-{task}[_acq-{acquisition}][_ce-{ceagent}][_dir-{direction}][_r...
rtCommon.bidsCommon.BIDS_DIR_PATH_PATTERN = sub-{subject}[/ses-{session}]/{datatype<func>|func}
rtCommon.bidsCommon.BIDS_FILE_PATH_PATTERN
rtCommon.bidsCommon.PYBIDS_PSEUDO_ENTITIES = ['extension']
rtCommon.bidsCommon.BIDS_EVENT_COL_TO_DTYPE
rtCommon.bidsCommon.BidsAttributesToAnonymize = ['PatientID', 'PatientsAge', 'PatientsBirthDate', 'PatientsName', 'PatientsSex', 'PatientsSize',...
class rtCommon.bidsCommon.BidsFileExtension

Bases: enum.Enum

Generic enumeration.

Derive from this class to define new enumerations.

IMAGE = .nii
IMAGE_COMPRESSED = .nii.gz
METADATA = .json
EVENTS = .tsv
class rtCommon.bidsCommon.BidsEntityKeys

Bases: enum.Enum

Generic enumeration.

Derive from this class to define new enumerations.

ENTITY = entity
FORMAT = format
DESCRIPTION = description
rtCommon.bidsCommon.loadBidsEntities() dict

Loads all accepted BIDS entities from PyBids into a dictionary.

Returns

A dictionary mapping the entity names to the PyBids Entity object

containing information about that entity.

rtCommon.bidsCommon.filterEntities(metadata: dict) dict

Returns a new dictionary containing all the elements of the argument that are valid BIDS entities.

rtCommon.bidsCommon.getNiftiData(image: nibabel.Nifti1Image) numpy.ndarray

Nibabel exposes a get_fdata() method, but this converts all the data to float64. Since our Nifti files are often converted from DICOM’s, which store data in signed or unsigned ints, treating the data as float can cause issues when comparing images or re-writing a Nifti read in from disk.

rtCommon.bidsCommon.makeDicomFieldBidsCompatible(dicomField: str) str

Remove non-alphanumeric characters to make a DICOM field name BIDS-compatible (CamelCase alphanumeric) metadata field. Note: Multi-word keys like ‘Frame of Reference UID’ become ‘FrameofReferenceUID’, which might be different than the expected behavior

Parameters

dicomField – Name of the DICOM field to convert to BIDS format

Returns

DICOM field name in BIDS-compatible format.

Examples

>>> field = "Repetition Time"
>>> makeDicomFieldBidsCompatible(field)
'RepetitionTime'
rtCommon.bidsCommon.UNIT_TO_CODE
rtCommon.bidsCommon.CODE_TO_UNIT
rtCommon.bidsCommon.correct3DHeaderTo4D(image: nibabel.Nifti1Image, repetitionTime: int, timeUnitCode: int = 8) None

Makes necessary changes to the NIfTI header to reflect the increase in its corresponding image’s data shape from 3D to 4D.

Parameters
  • image – NIfTI image to modify header for

  • repetitionTime – Repetition time for the scan that produced the image

  • timeUnitCode – The temporal dimension NIfTI unit code (e.g., millimeters is 2, seconds is 8). Defaults to seconds.

rtCommon.bidsCommon.adjustTimeUnits(imageMetadata: dict) None

Validates and converts in-place the units of various time-based metadata, which is stored in seconds in BIDS, but often provided using milliseconds in DICOM.

rtCommon.bidsCommon.metadataFromProtocolName(protocolName: str) dict

Extracts BIDS label-value combinations from a DICOM protocol name, if any are present.

Returns

A dictionary containing any valid label-value combinations found.

rtCommon.bidsCommon.getDicomMetadata(dicomImg: pydicom.dataset.Dataset, kind='all') dict

Returns the public (even-numbered tags) and private (odd-numbered tags) metadata from the provided DICOM image.

Parameters
  • dicomImg – A Pydicom object to read metadata from.

  • kind – Metadata category to get. ‘public’ for public DICOM tags, ‘private’ for private DICOM tags, ‘all’ for all DICOM tags.

Returns

Dictionary containing requested metadata from the DICOM image.

Raises

TypeError – If the image provided is not a pydicom.dataset.Dataset object (e.g., if the image were the raw DICOM data).

rtCommon.bidsCommon.symmetricDictDifference(d1: dict, d2: dict, equal: Callable[[Any, Any], bool] = opeq) dict

Returns the symmetric difference of the provided dictionaries. This consists of 3 parts: 1) Key-value pairs for which both dictionaries have the key, but have different values for that key. 2) All key-value pairs that only the first dictionary has. 3) All key-value pairs that only the second dictionary has.

Parameters
  • d1 – First dictionary

  • d2 – Second dictionary

  • equal – Function that returns True if two keys are equal, False otherwise

Returns

A dictionary with all key-value pair differences between the two dictionaries. ‘None’ is used as the value for a key-value pair if that dictionary lacks a key that the other one has.

Examples

>>> d1 = {'a': 1, 'b': 2, 'c': 3}
>>> d2 = {'c': 4, 'd': 5}
>>> print(symmetricDictDifference(d1, d2))
{'a': [1, None], 'b': [2, None], 'c': [3, 4], 'd': [None, 5]}
>>> d2 = {'a': 1, 'b': 2, 'c': 4}
>>> print(symmetricDictDifference(d1, d2))
{'c': [3, 4]}
rtCommon.bidsCommon.niftiHeadersAppendCompatible(header1: dict, header2: dict)

Verifies that two Nifti image headers match in along a defined set of NIfTI header fields which should not change during a continuous fMRI scanning session.

This is primarily intended as a safety check, and does not conclusively determine that two images are valid to append to together or are part of the same scanning session.

Parameters
  • header1 – First Nifti header to compare (dict of numpy arrays)

  • header2 – Second Nifti header to compare (dict of numpy arrays)

Returns

True if the headers match along the required dimensions, False otherwise.

rtCommon.bidsCommon.niftiImagesAppendCompatible(img1: nibabel.Nifti1Image, img2: nibabel.Nifti1Image) Tuple[bool, str]

Verifies that two Nifti images have headers matching along a defined set of NIfTI header fields which should not change during a continuous fMRI scanning session.

This is primarily intended as a safety check, and does not conclusively determine that two images are valid to append to together or are part of the same scanning session.

Parameters
  • img1 – First Nifti image to compare

  • img2 – Second Nifti image to compare

Returns

True if the image headers match along the required dimensions, False

otherwise.

rtCommon.bidsCommon.metadataAppendCompatible(meta1: dict, meta2: dict) Tuple[bool, str]

Verifies two metadata dictionaries match in a set of required fields. If a field is present in only one or neither of the two dictionaries, this is considered a match.

This is primarily intended as a safety check, and does not conclusively determine that two images are valid to append to together or are part of the same series.

Parameters
  • meta1 – First metadata dictionary

  • meta2 – Second metadata dictionary

Returns

True if all keys that are present in both dictionaries have equivalent

values, false otherwise.

rtCommon.bidsCommon.correctEventsFileDatatypes(df: pandas.DataFrame) pandas.DataFrame
rtCommon.bidsCommon.writeDataFrameToEvents(df: pandas.DataFrame, path: str) None