direct.data package

Contents

direct.data package#

Submodules#

direct.data.bbox module#

Utilities to handle images with respect to bounding boxes.

direct.data.bbox.crop_to_bbox(data, bbox, pad_value=0)[source]#

Extract bbox from images, coordinates can be negative.

Parameters:
  • data (Union[ndarray, Tensor]) – nD array or torch tensor.

  • bbox (List[int]) – Bounding box of the form (coordinates, size). For instance (4, 4, 2, 1) is a patch starting at row 4, col 4 with height 2 and width 1.

  • pad_value (int) – If bounding box would be out of the image, this is value the patch will be padded with. Default: 0.

Return type:

Union[ndarray, Tensor]

Returns:

Numpy array or torch tensor of data cropped to bounding box.

direct.data.bbox.crop_to_largest(data, pad_value=0)[source]#

Given a list of arrays or tensors, return the same list with the data padded to the largest in the set.

Can be convenient for e.g. logging and tiling several images as with torchvision’s make_grid.

Parameters:
  • data (List[Union[ndarray, Tensor]]) – List of numpy arrays or torch tensors.

  • pad_value (int) – Padding value. Default: 0.

Return type:

List[Union[ndarray, Tensor]]

Returns:

List of padded arrays or tensors.

direct.data.datasets module#

DIRECT datasets module.

direct.data.datasets.build_dataset_from_input(transforms, dataset_config, **kwargs)[source]#

Builds dataset from input keyword arguments and configuration file.

Only transforms is common for all Datasets. ALL other keyword arguments should be passed in **kwargs.

Parameters:
  • transforms (Callable) – Transformation object.

  • dataset_config (DictConfig) – Dataset configuration file.

  • kwargs (dict[str, Any]) –

    Additional keyword arguments. Can include:

    • initial_images: Path to initial_images.

    • initial_kspaces: Path to initial kspace images.

    • filenames_filter: List of filenames to include in the dataset.

    • data_root: Root path to the data for the dataset class.

    • pass_dictionaries: Optional dictionary of dictionaries.

Return type:

Dataset

Returns:

Dataset instance.

class direct.data.datasets.CalgaryCampinasDataset(data_root, transform=None, regex_filter=None, filenames_filter=None, filenames_lists=None, filenames_lists_root=None, pass_mask=False, crop_outer_slices=False, pass_h5s=None, **kwargs)[source]#

Bases: H5SliceData

Calgary-Campinas challenge dataset.

__init__(data_root, transform=None, regex_filter=None, filenames_filter=None, filenames_lists=None, filenames_lists_root=None, pass_mask=False, crop_outer_slices=False, pass_h5s=None, **kwargs)[source]#

Initialize the H5SliceData dataset.

Parameters:
  • root – Root directory to data.

  • filenames_filter (Optional[list[Union[Path, str]]]) – List of filenames to include in the dataset, should be the same as the ones that can be derived from a glob on the root. If set, will skip searching for files in the root. Default: None.

  • filenames_lists (Optional[list[Union[Path, str]]]) – List of paths pointing to .lst file(s) that contain file-names in root to filter. Should be the same as the ones that can be derived from a glob on the root. If this is set, this will override the filenames_filter option if not None. Default: None.

  • filenames_lists_root (Union[Path, str, None]) – Root of filenames_lists. Ignored if filename_lists is None. Default: None.

  • regex_filter (Optional[str]) – Regular expression filter on the absolute filename. Will be applied after any filenames filter. Default: None.

  • dataset_description – Dataset description dictionary. Default: None.

  • metadata – If given, this dictionary will be passed to the output transform. Default: None.

  • sensitivity_maps – Path to sensitivity maps, or None. Default: None.

  • extra_keys – Add extra keys in h5 file to output. Default: None.

  • pass_attrs – Pass the attributes saved in the h5 file. Default: False.

  • text_description – Description of dataset, can be useful for logging. Default: None.

  • kspace_context – K-space context. Default: None.

  • pass_dictionaries – Pass a dictionary of dictionaries, e.g. if {"name": {"filename_0": val}}, then to filename_0``s sample dict, a key with name ``"name" and value val will be added. Default: None.

  • pass_h5s (Optional[dict]) – Pass a dictionary of paths. If {"name": path} is given then to the sample of filename the same slice of path / filename will be added to the sample dictionary and will be assigned key "name". This can for instance be convenient when you want to pass sensitivity maps as well. Default: None.

  • slice_data – If set, for instance to slice(50,-50) only data within this slice will be added to the dataset. This is for instance convenient in the validation set of the public Calgary-Campinas dataset as the first 50 and last 50 slices are excluded in the evaluation. Default: None.

class direct.data.datasets.ConcatDataset(datasets)[source]#

Bases: Dataset

Dataset as a concatenation of multiple datasets.

This class is useful to assemble different existing datasets. From pytorch 1.5.1: torch.utils.data.ConcatDataset.

Parameters:

datasets (list[Dataset]) – List of datasets to be concatenated.

static cumsum(sequence)[source]#
Return type:

list[int]

__init__(datasets)[source]#
class direct.data.datasets.CMRxReconDataset(data_root, transform=None, filenames_filter=None, filenames_lists=None, filenames_lists_root=None, kspace_key='kspace_full', extra_keys=None, text_description=None, compute_mask=False, kspace_context=None)[source]#

Bases: Dataset

CMRxRecon Challenge 2023 Dataset [1]_.

Assuming the instructions in direct/projects/CMRxRecon have been followed, this dataset can be loaded with different options:

  1. Load the original fully sampled data by setting kspace_key = ‘kspace_full’.

  2. Load the custom-made fully-sampled data containing provided masks by the challenge by setting kspace_key``="kspace_full" and  ``extra_keys = [‘maskxx’,…] where ‘xx’ can be ‘04’, ‘08’ or ‘10’.

  3. Load the original sub-sampled data by setting kspace_key = ‘kspace_subxx’ ‘xx’ can be ‘04’, ‘08’ or ‘10’. For this option, you can opt to compute the masks from the sub-sampled k-space data by setting compute_mask = True.

Additionally, the dataset allows for the option to load 2D or 3D data:

  1. If kspace_context = None, 2D data will be loaded.

  2. If kspace_context = “time”, sequence 3D (2D + time) data will be loaded.

  3. If kspace_context = “slice”, 3D (x, y, z) data will be loaded.

Parameters:
  • data_root (Path) – Root directory to data.

  • transform (Optional[Callable[[tuple[Any, ...]], dict]]) – A list of transforms to be applied on the generated samples. Default: None.

  • filenames_filter (Optional[list[Union[Path, str]]]) – List of filenames to include in the dataset, should be the same as the ones that can be derived from a glob on the root. If set, will skip searching for files in the root. Default: None.

  • filenames_lists (Optional[list[Union[Path, str]]]) – List of paths pointing to .lst file(s) that contain file-names in root to filter. Should be the same as the ones that can be derived from a glob on the root. If this is set, this will override the filenames_filter option if not None. Default: None.

  • filenames_lists_root (Union[Path, str, None]) – Root of filenames_lists. Ignored if filename_lists is None. Default: None.

  • kspace_key (str) – Key to load the k-space. Typically, ‘kspace_full’ for fully-sampled data, or ‘kspace_subxx’ (xx can be ‘04’, ‘08’ or ‘10) for sub-sampled data. Default: ‘kspace_full’.

  • extra_keys (Optional[tuple[str]]) – Add extra keys in h5 file to output. May be used to load sampling masks, e.g. “maskxx”. Note that this should contain at most one of the following “mask04”, “mask08” or “mask10”. Default: None.

  • text_description (Optional[str]) – Description of dataset, can be useful for logging.

  • compute_mask (bool) – If True, it will compute the sampling mask from data. This should be typically True at inference, where data are already undersampled. This will also compute acs_mask, which is by default the 24 center lines. Default: False.

  • kspace_context (Optional[str]) – Can be either None, “time” or “slice”. If None, data will be loaded per slice or time-frame (2D data). If “time”, all time frames(phases) per slice will be loaded (3D data). If “slice”, all sliced per time frame will be loaded (3D data). Default: None.

  • References

  • website (.. [1] CMRxRecon) – https://cmrxrecon.github.io/Challenge.html

NUM_ACS_LINES = 24#
VALID_CHALLENGE_ACCELERATIONS = {'mask04', 'mask08', 'mask10'}#
__init__(data_root, transform=None, filenames_filter=None, filenames_lists=None, filenames_lists_root=None, kspace_key='kspace_full', extra_keys=None, text_description=None, compute_mask=False, kspace_context=None)[source]#

Inits CMRxReconDataset.

Parameters:
  • data_root (Path) – Root directory to data.

  • transform (Optional[Callable[[tuple[Any, ...]], dict]]) – A list of transforms to be applied on the generated samples. Default is None.

  • filenames_filter (Optional[list[Union[Path, str]]]) – List of filenames to include in the dataset, should be the same as the ones that can be derived from a glob on the root. If set, will skip searching for files in the root. Default: None.

  • filenames_lists (Optional[list[Union[Path, str]]]) – List of paths pointing to .lst file(s) that contain file-names in root to filter. Should be the same as the ones that can be derived from a glob on the root. If this is set, this will override the filenames_filter option if not None. Default: None.

  • filenames_lists_root (Union[Path, str, None]) – Root of filenames_lists. Ignored if filename_lists is None. Default: None.

  • kspace_key (str) – Key to load the k-space. Typically, ‘kspace_full’ for fully-sampled data, or ‘kspace_subxx’ (xx can be ‘04’, ‘08’ or ‘10) for sub-sampled data. Default: ‘kspace_full’.

  • extra_keys (Optional[tuple[str]]) – Add extra keys in h5 file to output. May be used to load sampling masks, e.g. “maskxx”. Note that this should contain at most one of the following “mask04”, “mask08” or “mask10”. Default: None.

  • text_description (Optional[str]) – Description of dataset, can be useful for logging.

  • compute_mask (bool) – If True, it will compute the sampling mask from data. This should be typically True at inference, where data are already undersampled. This will also compute acs_mask, which is by default the 24 center lines. Default: False.

  • kspace_context (Optional[str]) – Can be either None, “time” or “slice”. If None, data will be loaded per slice or time-frame (2D data). If “time”, all time frames(phases) per slice will be loaded (3D data). If “slice”, all sliced per time frame will be loaded (3D data). Default: None.

parse_filenames_data(filenames, extra_mats=None)[source]#

Parse the filenames and collect information on the image masks_dict.

Will collect information on the image masks_dict and store it in the volume_indices attribute.

Parameters:
  • filenames (list[Path]) – List of filenames to parse.

  • extra_mats (tuple[str]) – Tuple of keys of the extra mats to verify. Default is None.

Raises:

OSError – If the filename does not exist.

Return type:

None

static verify_extra_mat_integrity(filename, extra_mats)[source]#

Verify the integrity of the extra mats by checking the shape of the data.

Parameters:
  • filename (Path) – Path to the mat file.

  • extra_mats (tuple[str]) – Tuple of keys of the extra mats to verify.

Return type:

None

__len__()[source]#

Return the length of the dataset.

Return type:

int

Returns:

int The length of the dataset.

get_slice_data(filename, slice_no, key, extra_keys=None)[source]#

Get slice data from the mat file.

This function will return the slice data from the mat file. If extra_keys are provided, it will also return the data from the extra keys.

Parameters:
  • filename (Union[Path, str]) – Path to the mat file.

  • slice_no (int) – Slice number (corresponding to dataset index) to retrieve.

  • key (str) – Key to load the data from the mat file.

  • extra_keys – Extra keys to load from the mat file. Default is None.

Return type:

tuple[ndarray, Any]

Returns:

The retrieved data and the extra data.

__getitem__(idx)[source]#

Get a sample from the dataset.

Parameters:

idx (int) – Index of the sample to retrieve.

Return type:

dict[str, Any]

Returns:

A dictionary containing the sample data.

class direct.data.datasets.FastMRIDataset(data_root, transform=None, filenames_filter=None, filenames_lists=None, filenames_lists_root=None, regex_filter=None, pass_mask=False, pass_max=True, initial_images=None, initial_images_key=None, noise_data=None, pass_h5s=None, **kwargs)[source]#

Bases: H5SliceData

FastMRI challenge dataset.

Parameters:
  • data_root (Path) – Root directory to data.

  • transform (Optional[Callable]) – A list of transforms to be applied on the generated samples. Default is None.

  • filenames_filter (Optional[list[Union[Path, str]]]) – List of filenames to include in the dataset, should be the same as the ones that can be derived from a glob on the root. If set, will skip searching for files in the root. Default: None.

  • filenames_lists (Optional[list[Union[Path, str]]]) – List of paths pointing to .lst file(s) that contain file-names in root to filter. Should be the same as the ones that can be derived from a glob on the root. If this is set, this will override the filenames_filter option if not None. Default: None.

  • filenames_lists_root (Union[Path, str, None]) – Root of filenames_lists. Ignored if filename_lists is None. Default: None.

  • regex_filter (Optional[str]) – Regular expression filter on the absolute filename. Will be applied after any filenames filter.

  • pass_mask (bool) – If True this will load in the sample a sampling mask saved in the h5 file. Default: False.

  • pass_max (bool) – If True this will load the maximum k-space magnitude value saved in the h5 file.

  • initial_images (Optional[list[Path]]) – List of paths to initial images.

  • initial_images_key (Optional[str]) – Key for initial images.

  • noise_data (Optional[dict]) – Noise data dictionary.

  • pass_h5s (Optional[dict]) – Pass a dictionary of paths. If {“name”: path} is given then to the sample of filename the same slice of path / filename will be added to the sample dictionary and will be asigned key name. This can be convenient when you want to pass sensitivity maps. For instance: pass_h5s = {“sensitivity_map”: “/data/sensitivity_maps”} will add to each output sample a key sensitivity_map with value a numpy array containing the same slice of /data/sensitivity_maps/filename.h5 as the one of the original filename.h5.

  • kwargs – Additional keyword arguments.

__init__(data_root, transform=None, filenames_filter=None, filenames_lists=None, filenames_lists_root=None, regex_filter=None, pass_mask=False, pass_max=True, initial_images=None, initial_images_key=None, noise_data=None, pass_h5s=None, **kwargs)[source]#

Initialize the H5SliceData dataset.

Parameters:
  • root – Root directory to data.

  • filenames_filter (Optional[list[Union[Path, str]]]) – List of filenames to include in the dataset, should be the same as the ones that can be derived from a glob on the root. If set, will skip searching for files in the root. Default: None.

  • filenames_lists (Optional[list[Union[Path, str]]]) – List of paths pointing to .lst file(s) that contain file-names in root to filter. Should be the same as the ones that can be derived from a glob on the root. If this is set, this will override the filenames_filter option if not None. Default: None.

  • filenames_lists_root (Union[Path, str, None]) – Root of filenames_lists. Ignored if filename_lists is None. Default: None.

  • regex_filter (Optional[str]) – Regular expression filter on the absolute filename. Will be applied after any filenames filter. Default: None.

  • dataset_description – Dataset description dictionary. Default: None.

  • metadata – If given, this dictionary will be passed to the output transform. Default: None.

  • sensitivity_maps – Path to sensitivity maps, or None. Default: None.

  • extra_keys – Add extra keys in h5 file to output. Default: None.

  • pass_attrs – Pass the attributes saved in the h5 file. Default: False.

  • text_description – Description of dataset, can be useful for logging. Default: None.

  • kspace_context – K-space context. Default: None.

  • pass_dictionaries – Pass a dictionary of dictionaries, e.g. if {"name": {"filename_0": val}}, then to filename_0``s sample dict, a key with name ``"name" and value val will be added. Default: None.

  • pass_h5s (Optional[dict]) – Pass a dictionary of paths. If {"name": path} is given then to the sample of filename the same slice of path / filename will be added to the sample dictionary and will be assigned key "name". This can for instance be convenient when you want to pass sensitivity maps as well. Default: None.

  • slice_data – If set, for instance to slice(50,-50) only data within this slice will be added to the dataset. This is for instance convenient in the validation set of the public Calgary-Campinas dataset as the first 50 and last 50 slices are excluded in the evaluation. Default: None.

static explicit_zero_padding(kspace, padding_left, padding_right)[source]#
Return type:

ndarray

class direct.data.datasets.FakeMRIBlobsDataset(sample_size, num_coils, spatial_shape, transform=None, seed=None, filenames=None, pass_attrs=None, text_description=None, kspace_context=None, **kwargs)[source]#

Bases: Dataset

A PyTorch Dataset class which outputs random fake k-space images which reconstruct into Gaussian blobs.

Parameters:
  • sample_size (int) – Size of the dataset.

  • num_coils (int) – Number of coils for the fake k-space data.

  • spatial_shape (Union[list[int], tuple[int]]) – Shape of the reconstructed fake data. Should be (height, width) or (slice, height, width), corresponding to ndim = 2 and ndim = 3.

  • transform (Optional[Callable]) – A list of transforms to be performed on the generated samples. Default is None.

  • seed (Optional[int]) – Seed. Default is None.

  • filenames (Union[list[str], str, None]) – Names for the generated samples. If string is given, a number order starting from “00001” is appended to the name of each sample.

  • pass_attrs (Optional[bool]) – Pass the attributes of the generated sample.

  • text_description (Optional[str]) – Description of dataset, can be useful for logging.

  • kspace_context (Optional[bool]) – If true corresponds to 3D reconstruction, else reconstruction is 2D.

__init__(sample_size, num_coils, spatial_shape, transform=None, seed=None, filenames=None, pass_attrs=None, text_description=None, kspace_context=None, **kwargs)[source]#

Inits FakeMRIBlobsDataset.

Parameters:
  • sample_size (int) – Size of the dataset.

  • num_coils (int) – Number of coils for the fake k-space data.

  • spatial_shape (Union[list[int], tuple[int]]) – Shape of the reconstructed fake data. Should be (height, width) or (slice, height, width), corresponding to ndim = 2 and ndim = 3.

  • transform (Optional[Callable]) – A list of transforms to be performed on the generated samples. Default: None.

  • seed (Optional[int]) – Random seed. Default: None.

  • filenames (Union[list[str], str, None]) – Names for the generated samples. If string is given, a number order starting from "00001" is appended to the name of each sample. Default: None.

  • pass_attrs (Optional[bool]) – Pass the attributes of the generated sample. Default: None.

  • text_description (Optional[str]) – Description of dataset, can be useful for logging. Default: None.

  • kspace_context (Optional[bool]) – If True corresponds to 3D reconstruction, else reconstruction is 2D. Default: None.

  • **kwargs – Additional keyword arguments.

parse_filenames_data(filenames)[source]#
class direct.data.datasets.SheppLoganDataset(shape, num_coils, intensity, seed=None, ellipsoids=None, B0=3.0, T2_star=None, zlimits=(-1, 1), transform=None, text_description=None)[source]#

Bases: Dataset

Shepp Logan Dataset for MRI as implemented in [1]_. Code was adapted from [2].

Note

This dataset reconstructs into a single volume.

References

GYROMAGNETIC_RATIO = 267.52219#
DEFAULT_NUM_ELLIPSOIDS = 15#
ELLIPSOID_NUM_PARAMS = 13#
IMAGE_INTENSITIES = ['PROTON', 'T1', 'T2']#
__init__(shape, num_coils, intensity, seed=None, ellipsoids=None, B0=3.0, T2_star=None, zlimits=(-1, 1), transform=None, text_description=None)[source]#

Inits SheppLoganDataset.

Parameters:
  • shape (Union[int, list[int], tuple[int, int, int]]) – Shape of Shepp Logan phantom (3-dimensional).

  • num_coils (int) – Number of simulated coils.

  • intensity (ImageIntensityMode) – Can be PROTON to return the proton density dataset, T1 or T2.

  • seed (Union[int, list[int], None]) – Seed to be used for coil sensitivity maps. Default: None.

  • ellipsoids (ndarray) – Ellipsoids parameters. If None, it will used the default parameters as per the paper. Default: None.

  • B0 (float) – Magnetic field. Default: 3.0.

  • T2_star (Optional[bool]) – If True, a T2^{*} dataset will be output. Only valid for intensity = T2. Default: None.

  • zlimits (tuple[float, float]) – Limits of z-axis. Default: (-1, 1).

  • transform (Optional[Callable]) – A list of transforms to be applied on the generated samples. Default is None.

  • text_description (Optional[str]) – Description of dataset, can be useful for logging. Default: None.

sample_image(idx)[source]#
Return type:

ndarray

static default_mr_ellipsoid_parameters()[source]#

Returns default parameters of ellipsoids as in [1]_.

Return type:

ndarray

Returns:

Array containing the parameters for the ellipsoids used to construct the phantom. Each row of the form [x, y, z, a, b, c, theta, m_0, A, C, T1, T2, chi] represents an ellipsoid, where:

  • (x, y, z): denotes the center of the ellipsoid

  • (a, b, c): denote the lengths of the semi-major axis aligned with the x, y, z-axis, respectively

  • theta: denotes the rotation angle of the ellipsoid in rads

  • m_0: denotes the spin density

  • (A, C): denote the T1 parameters

  • T1: denotes the T1 value if explicit, otherwise T1 = A × B_0^C

  • T2: denotes the T2 value

  • chi: denotes the chi value

References

static fft(x)[source]#
class direct.data.datasets.SheppLoganT1Dataset(shape, num_coils, seed=None, ellipsoids=None, B0=3.0, zlimits=(-0.929, 0.929), transform=None, text_description=None)[source]#

Bases: SheppLoganDataset

Creates an instance of SheppLoganDataset with T1 intensity.

__init__(shape, num_coils, seed=None, ellipsoids=None, B0=3.0, zlimits=(-0.929, 0.929), transform=None, text_description=None)[source]#

Inits SheppLoganT1Dataset.

Parameters:
  • shape (Union[int, list[int], tuple[int, int, int]]) – Shape of Shepp Logan phantom (3-dimensional).

  • num_coils (int) – Number of simulated coils.

  • seed (Union[int, list[int], None]) – Seed to be used for coil sensitivity maps. Default: None.

  • ellipsoids (ndarray) – Ellipsoids parameters. If None, it will used the default parameters as per the paper. Default: None.

  • B0 (float) – Magnetic field. Default: 3.0.

  • zlimits (tuple[float, float]) – Limits of z-axis. Default: (-0.929, 0.929).

  • transform (Optional[Callable]) – A list of transforms to be applied on the generated samples. Default is None.

  • text_description (Optional[str]) – Description of dataset, can be useful for logging. Default: None.

class direct.data.datasets.SheppLoganT2Dataset(shape, num_coils, seed=None, ellipsoids=None, B0=3.0, T2_star=None, zlimits=(-0.929, 0.929), transform=None, text_description=None)[source]#

Bases: SheppLoganDataset

Creates an instance of SheppLoganDataset with T2 intensity.

__init__(shape, num_coils, seed=None, ellipsoids=None, B0=3.0, T2_star=None, zlimits=(-0.929, 0.929), transform=None, text_description=None)[source]#

Inits SheppLoganT2Dataset.

Parameters:
  • shape (Union[int, list[int], tuple[int, int, int]]) – Shape of Shepp Logan phantom (3-dimensional).

  • num_coils (int) – Number of simulated coils.

  • seed (Union[int, list[int], None]) – Seed to be used for coil sensitivity maps. Default: None.

  • ellipsoids (ndarray) – Ellipsoids parameters. If None, it will used the default parameters as per the paper. Default: None.

  • B0 (float) – Magnetic field. Default: 3.0.

  • T2_star (Optional[bool]) – If True, a T2^{*} dataset will be output. Only valid for intensity = T2. Default: None.

  • zlimits (tuple[float, float]) – Limits of z-axis. Default: (-0.929, 0.929).

  • transform (Optional[Callable]) – A list of transforms to be applied on the generated samples. Default is None.

  • text_description (Optional[str]) – Description of dataset, can be useful for logging. Default: None.

class direct.data.datasets.SheppLoganProtonDataset(shape, num_coils, seed=None, ellipsoids=None, B0=3.0, zlimits=(-0.929, 0.929), transform=None, text_description=None)[source]#

Bases: SheppLoganDataset

Creates an instance of SheppLoganDataset with PROTON intensity.

__init__(shape, num_coils, seed=None, ellipsoids=None, B0=3.0, zlimits=(-0.929, 0.929), transform=None, text_description=None)[source]#

Inits SheppLoganProtonDataset.

Parameters:
  • shape (Union[int, list[int], tuple[int, int, int]]) – Shape of Shepp Logan phantom (3-dimensional).

  • num_coils (int) – Number of simulated coils.

  • seed (Union[int, list[int], None]) – Seed to be used for coil sensitivity maps. Default: None.

  • ellipsoids (ndarray) – Ellipsoids parameters. If None, it will used the default parameters as per the paper. Default: None.

  • B0 (float) – Magnetic field. Default: 3.0.

  • zlimits (tuple[float, float]) – Limits of z-axis. Default: (-0.929, 0.929).

  • transform (Optional[Callable]) – A list of transforms to be applied on the generated samples. Default is None.

  • text_description (Optional[str]) – Description of dataset, can be useful for logging. Default: None.

direct.data.datasets_config module#

Classes holding the typed configurations for the datasets.

class direct.data.datasets_config.CropTransformConfig(crop=None, crop_type='uniform', image_center_crop=False)[source]#

Bases: BaseConfig

crop = None#
crop_type = 'uniform'#
image_center_crop = False#
__init__(crop=None, crop_type='uniform', image_center_crop=False)#
class direct.data.datasets_config.SensitivityMapEstimationTransformConfig(estimate_sensitivity_maps=True, sensitivity_maps_type=SensitivityMapType.RSS_ESTIMATE, sensitivity_maps_espirit_threshold=0.05, sensitivity_maps_espirit_kernel_size=6, sensitivity_maps_espirit_crop=0.95, sensitivity_maps_espirit_max_iters=30, sensitivity_maps_gaussian=0.7)[source]#

Bases: BaseConfig

estimate_sensitivity_maps = True#
sensitivity_maps_type = 'rss_estimate'#
sensitivity_maps_espirit_threshold = 0.05#
sensitivity_maps_espirit_kernel_size = 6#
sensitivity_maps_espirit_crop = 0.95#
sensitivity_maps_espirit_max_iters = 30#
sensitivity_maps_gaussian = 0.7#
__init__(estimate_sensitivity_maps=True, sensitivity_maps_type=SensitivityMapType.RSS_ESTIMATE, sensitivity_maps_espirit_threshold=0.05, sensitivity_maps_espirit_kernel_size=6, sensitivity_maps_espirit_crop=0.95, sensitivity_maps_espirit_max_iters=30, sensitivity_maps_gaussian=0.7)#
class direct.data.datasets_config.AugmentationTransformConfig(rescale=None, rescale_mode=RescaleMode.NEAREST, rescale_2d_if_3d=False, pad=None)[source]#

Bases: BaseConfig

rescale = None#
rescale_mode = 'nearest'#
rescale_2d_if_3d = False#
pad = None#
__init__(rescale=None, rescale_mode=RescaleMode.NEAREST, rescale_2d_if_3d=False, pad=None)#
class direct.data.datasets_config.RandomAugmentationTransformsConfig(random_rotation_degrees=(-90, 90), random_rotation_probability=0.0, random_flip_type=RandomFlipType.RANDOM, random_flip_probability=0.0, random_reverse_probability=0.0)[source]#

Bases: BaseConfig

random_rotation_degrees = (-90, 90)#
random_rotation_probability = 0.0#
random_flip_type = 'random'#
random_flip_probability = 0.0#
random_reverse_probability = 0.0#
__init__(random_rotation_degrees=(-90, 90), random_rotation_probability=0.0, random_flip_type=RandomFlipType.RANDOM, random_flip_probability=0.0, random_reverse_probability=0.0)#
class direct.data.datasets_config.NormalizationTransformConfig(scaling_key='masked_kspace', scale_percentile=0.99)[source]#

Bases: BaseConfig

scaling_key = 'masked_kspace'#
scale_percentile = 0.99#
__init__(scaling_key='masked_kspace', scale_percentile=0.99)#
class direct.data.datasets_config.TransformsConfig(masking=<factory>, cropping=<factory>, augmentation=<factory>, random_augmentations=<factory>, padding_eps=0.001, estimate_body_coil_image=False, sensitivity_map_estimation=<factory>, normalization=<factory>, delete_acs_mask=True, delete_kspace=True, image_recon_type=ReconstructionType.RSS, compress_coils=None, pad_coils=None, use_seed=True, transforms_type=TransformsType.SUPERVISED, mask_split_ratio=(0.4, ), mask_split_acs_region=(0, 0), mask_split_keep_acs=False, mask_split_type=MaskSplitterType.GAUSSIAN, mask_split_gaussian_std=3.0, mask_split_half_direction=HalfSplitType.VERTICAL)[source]#

Bases: BaseConfig

Configuration for the transforms.

masking#

Configuration for the masking.

cropping#

Configuration for the cropping.

augmentation#

Configuration for the augmentation. Currently only rescale and pad are supported.

random_augmentations#

Configuration for the random augmentations. Currently only random rotation, flip and reverse are supported.

padding_eps#

Padding epsilon. Default is 0.001.

estimate_body_coil_image#

Estimate body coil image. Default is False.

sensitivity_map_estimation#

Configuration for the sensitivity map estimation.

normalization#

Configuration for the normalization.

delete_acs_mask#

Delete ACS mask after its use. Default is True.

delete_kspace#

Delete k-space after its use. This should be set to False if the k-space is needed for the loss computation. Default is True.

image_recon_type#

Image reconstruction type. Default is ReconstructionType.RSS.

compress_coils#

Number of coils to compress input k-space. It is not recommended to be used in combination with pad_coils. Default is None.

pad_coils#

Pad coils. Default is None.

use_seed#

Use seed for the transforms. Typically this should be set to True for reproducibility (e.g. inference), and False for training. Default is True.

transforms_type#

Type of transforms. By default the transforms are set for supervised learning (TransformsType.SUPERVISED). To use SSL transforms, set transforms_type to SSL_SSDU. This will require additional parameters to be set: mask_split_ratio, mask_split_acs_region, mask_split_keep_acs, mask_split_type, mask_split_gaussian_std. Default is TransformsType.SUPERVISED.

mask_split_ratio#

Ratio of the mask to split into input and target mask. Ignored if transforms_type is not SSL_SSDU. Default is (0.4,).

mask_split_acs_region#

Region of the ACS k-space to keep in the input mask. Ignored if transforms_type is not SSL_SSDU. Default is (0, 0).

mask_split_keep_acs#

Keep ACS in both masks, input and target. Ignored if transforms_type is not SSL_SSDU. Default is False.

mask_split_type#

Type of mask splitting if transforms_type is SSL_SSDU. Ignored if transforms_type is not SSL_SSDU. Default is MaskSplitterType.GAUSSIAN.

mask_split_gaussian_std#

Standard deviation of the Gaussian mask splitter. Ignored if mask_split_type is not MaskSplitterType.GAUSSIAN. Ignored if transforms_type is not SSL_SSDU. Default is 3.0.

mask_split_half_direction#

Direction to split the mask if mask_split_type is MaskSplitterType.HALF. Ignored if MaskSplitterType is not HALF or transforms_type is not SSL_SSDU. Default is HalfSplitType.VERTICAL.

masking#
cropping#
augmentation#
random_augmentations#
padding_eps = 0.001#
estimate_body_coil_image = False#
sensitivity_map_estimation#
normalization#
delete_acs_mask = True#
delete_kspace = True#
image_recon_type = 'rss'#
compress_coils = None#
pad_coils = None#
use_seed = True#
transforms_type = 'supervised'#
mask_split_ratio = (0.4,)#
mask_split_acs_region = (0, 0)#
mask_split_keep_acs = False#
mask_split_type = 'gaussian'#
mask_split_gaussian_std = 3.0#
mask_split_half_direction = 'vertical'#
__init__(masking=<factory>, cropping=<factory>, augmentation=<factory>, random_augmentations=<factory>, padding_eps=0.001, estimate_body_coil_image=False, sensitivity_map_estimation=<factory>, normalization=<factory>, delete_acs_mask=True, delete_kspace=True, image_recon_type=ReconstructionType.RSS, compress_coils=None, pad_coils=None, use_seed=True, transforms_type=TransformsType.SUPERVISED, mask_split_ratio=(0.4, ), mask_split_acs_region=(0, 0), mask_split_keep_acs=False, mask_split_type=MaskSplitterType.GAUSSIAN, mask_split_gaussian_std=3.0, mask_split_half_direction=HalfSplitType.VERTICAL)#
class direct.data.datasets_config.DatasetConfig(name='???', transforms=<factory>, text_description=None)[source]#

Bases: BaseConfig

name = '???'#
transforms#
text_description = None#
__init__(name='???', transforms=<factory>, text_description=None)#
class direct.data.datasets_config.H5SliceConfig(name='???', transforms=<factory>, text_description=None, regex_filter=None, input_kspace_key=None, input_image_key=None, kspace_context=0, pass_mask=False, data_root=None, filenames_filter=None, filenames_lists=None, filenames_lists_root=None)[source]#

Bases: DatasetConfig

regex_filter = None#
input_kspace_key = None#
input_image_key = None#
kspace_context = 0#
pass_mask = False#
data_root = None#
filenames_filter = None#
filenames_lists = None#
filenames_lists_root = None#
__init__(name='???', transforms=<factory>, text_description=None, regex_filter=None, input_kspace_key=None, input_image_key=None, kspace_context=0, pass_mask=False, data_root=None, filenames_filter=None, filenames_lists=None, filenames_lists_root=None)#
class direct.data.datasets_config.CMRxReconConfig(name='???', transforms=<factory>, text_description=None, regex_filter=None, data_root=None, filenames_filter=None, filenames_lists=None, filenames_lists_root=None, kspace_key='kspace_full', compute_mask=False, extra_keys=None, kspace_context=None)[source]#

Bases: DatasetConfig

regex_filter = None#
data_root = None#
filenames_filter = None#
filenames_lists = None#
filenames_lists_root = None#
kspace_key = 'kspace_full'#
compute_mask = False#
extra_keys = None#
kspace_context = None#
__init__(name='???', transforms=<factory>, text_description=None, regex_filter=None, data_root=None, filenames_filter=None, filenames_lists=None, filenames_lists_root=None, kspace_key='kspace_full', compute_mask=False, extra_keys=None, kspace_context=None)#
class direct.data.datasets_config.FastMRIConfig(name='???', transforms=<factory>, text_description=None, regex_filter=None, input_kspace_key=None, input_image_key=None, kspace_context=0, pass_mask=False, data_root=None, filenames_filter=None, filenames_lists=None, filenames_lists_root=None, pass_attrs=True)[source]#

Bases: H5SliceConfig

pass_attrs = True#
__init__(name='???', transforms=<factory>, text_description=None, regex_filter=None, input_kspace_key=None, input_image_key=None, kspace_context=0, pass_mask=False, data_root=None, filenames_filter=None, filenames_lists=None, filenames_lists_root=None, pass_attrs=True)#
class direct.data.datasets_config.CalgaryCampinasConfig(name='???', transforms=<factory>, text_description=None, regex_filter=None, input_kspace_key=None, input_image_key=None, kspace_context=0, pass_mask=False, data_root=None, filenames_filter=None, filenames_lists=None, filenames_lists_root=None, crop_outer_slices=False)[source]#

Bases: H5SliceConfig

crop_outer_slices = False#
__init__(name='???', transforms=<factory>, text_description=None, regex_filter=None, input_kspace_key=None, input_image_key=None, kspace_context=0, pass_mask=False, data_root=None, filenames_filter=None, filenames_lists=None, filenames_lists_root=None, crop_outer_slices=False)#
class direct.data.datasets_config.FakeMRIBlobsConfig(name='???', transforms=<factory>, text_description=None, pass_attrs=True)[source]#

Bases: DatasetConfig

pass_attrs = True#
__init__(name='???', transforms=<factory>, text_description=None, pass_attrs=True)#
class direct.data.datasets_config.SheppLoganDatasetConfig(name='???', transforms=<factory>, text_description=None, shape=(100, 100, 30), num_coils=12, seed=None, B0=3.0, zlimits=(-0.929, 0.929))[source]#

Bases: DatasetConfig

shape = (100, 100, 30)#
num_coils = 12#
seed = None#
B0 = 3.0#
zlimits = (-0.929, 0.929)#
__init__(name='???', transforms=<factory>, text_description=None, shape=(100, 100, 30), num_coils=12, seed=None, B0=3.0, zlimits=(-0.929, 0.929))#
class direct.data.datasets_config.SheppLoganProtonConfig(name='???', transforms=<factory>, text_description=None, shape=(100, 100, 30), num_coils=12, seed=None, B0=3.0, zlimits=(-0.929, 0.929))[source]#

Bases: SheppLoganDatasetConfig

__init__(name='???', transforms=<factory>, text_description=None, shape=(100, 100, 30), num_coils=12, seed=None, B0=3.0, zlimits=(-0.929, 0.929))#
class direct.data.datasets_config.SheppLoganT1Config(name='???', transforms=<factory>, text_description=None, shape=(100, 100, 30), num_coils=12, seed=None, B0=3.0, zlimits=(-0.929, 0.929))[source]#

Bases: SheppLoganDatasetConfig

__init__(name='???', transforms=<factory>, text_description=None, shape=(100, 100, 30), num_coils=12, seed=None, B0=3.0, zlimits=(-0.929, 0.929))#
class direct.data.datasets_config.SheppLoganT2Config(name='???', transforms=<factory>, text_description=None, shape=(100, 100, 30), num_coils=12, seed=None, B0=3.0, zlimits=(-0.929, 0.929), T2_star=False)[source]#

Bases: SheppLoganDatasetConfig

T2_star = False#
__init__(name='???', transforms=<factory>, text_description=None, shape=(100, 100, 30), num_coils=12, seed=None, B0=3.0, zlimits=(-0.929, 0.929), T2_star=False)#

direct.data.fake module#

class direct.data.fake.FakeMRIData(ndim=2, blobs_n_samples=None, blobs_cluster_std=None)[source]#

Bases: object

Generates fake 2D or 3D MRI data by generating random 2D or 3D images of gaussian blobs.

__init__(ndim=2, blobs_n_samples=None, blobs_cluster_std=None)[source]#

Inits FakeMRIData.

Parameters:
  • ndim (int) – Dimension of samples. Can be 2 or 3. Default: 2.

  • blobs_n_samples (Optional[int]) – The total number of points equally divided among clusters. Default: None.

  • blobs_cluster_std (Optional[float]) – Standard deviation of the clusters. Default: None.

get_kspace(spatial_shape, num_coils)[source]#

Get k-space data for given spatial shape and number of coils.

Parameters:
  • spatial_shape (Union[List[int], Tuple[int, ...]]) – Spatial dimensions.

  • num_coils (int) – Number of coils.

Return type:

ndarray

Returns:

K-space data.

set_attrs(sample)[source]#

Sets metadata attributes of sample.

Return type:

Dict

make_blobs(spatial_shape, num_coils, seed=None)[source]#

Generates gaussian blobs in num_coils classes and scales them to the interval [0, slice] x [0, height] x [0, width].

Parameters:
  • spatial_shape (Union[List[int], Tuple[int, ...]]) – Spatial dimensions.

  • num_coils (int) – Number of coils/classes.

  • seed (Optional[int]) – Random seed. Default: None.

Return type:

Tuple[ndarray, ndarray, ndarray]

Returns:

Generated blob samples.

__call__(sample_size=1, num_coils=1, spatial_shape=(100, 100), name='fake_mri_sample', seed=None, root=None)[source]#

Returns fake mri samples in the form of gaussian blobs.

Parameters:
  • sample_size (int) – Size of the samples. Default: 1.

  • num_coils (int) – Number of simulated coils. Default: 1.

  • spatial_shape (Union[List[int], Tuple[int, ...]]) – Must be (slice, height, width) or (height, width). Default: (100, 100).

  • name (Union[str, List[str]]) – Name of file. Default: "fake_mri_sample".

  • seed (Optional[int]) – Random seed. Default: None.

  • root (Optional[Path]) – Root to save data. To be used with save_as_h5=True. Default: None.

Returns:

"kspace" of shape (slice, num_coils, height, width) and "reconstruction_rss" of shape (slice, height, width). If spatial_shape is of shape 2 (height, width), slice=1.

Return type:

Dictionary or list of dictionaries. Contains

direct.data.fake.scale_data(data, shape)[source]#

Scales data to (0,1) and then to shape.

direct.data.fake.fft(data, dims=(-2, -1))[source]#

Fast Fourier Transform.

direct.data.fake.ifft(data, dims=(-2, -1))[source]#

Inverse Fast Fourier Transform.

direct.data.fake.root_sum_of_squares(kspace_data, coil_dim=1)[source]#

Root Sum of Squares Estimate, given kspace data.

direct.data.h5_data module#

class direct.data.h5_data.H5SliceData(root, filenames_filter=None, filenames_lists=None, filenames_lists_root=None, regex_filter=None, dataset_description=None, metadata=None, sensitivity_maps=None, extra_keys=None, pass_attrs=False, text_description=None, kspace_context=None, pass_dictionaries=None, pass_h5s=None, slice_data=None)[source]#

Bases: Dataset

A PyTorch Dataset class which outputs k-space slices based on the h5 dataformat.

__init__(root, filenames_filter=None, filenames_lists=None, filenames_lists_root=None, regex_filter=None, dataset_description=None, metadata=None, sensitivity_maps=None, extra_keys=None, pass_attrs=False, text_description=None, kspace_context=None, pass_dictionaries=None, pass_h5s=None, slice_data=None)[source]#

Initialize the H5SliceData dataset.

Parameters:
  • root (Path) – Root directory to data.

  • filenames_filter (Optional[List[Union[Path, str]]]) – List of filenames to include in the dataset, should be the same as the ones that can be derived from a glob on the root. If set, will skip searching for files in the root. Default: None.

  • filenames_lists (Optional[List[Union[Path, str]]]) – List of paths pointing to .lst file(s) that contain file-names in root to filter. Should be the same as the ones that can be derived from a glob on the root. If this is set, this will override the filenames_filter option if not None. Default: None.

  • filenames_lists_root (Union[Path, str, None]) – Root of filenames_lists. Ignored if filename_lists is None. Default: None.

  • regex_filter (Optional[str]) – Regular expression filter on the absolute filename. Will be applied after any filenames filter. Default: None.

  • dataset_description (Optional[Dict[Union[Path, str], Any]]) – Dataset description dictionary. Default: None.

  • metadata (Optional[Dict[Union[Path, str], Dict]]) – If given, this dictionary will be passed to the output transform. Default: None.

  • sensitivity_maps (Union[Path, str, None]) – Path to sensitivity maps, or None. Default: None.

  • extra_keys (Optional[Tuple]) – Add extra keys in h5 file to output. Default: None.

  • pass_attrs (bool) – Pass the attributes saved in the h5 file. Default: False.

  • text_description (Optional[str]) – Description of dataset, can be useful for logging. Default: None.

  • kspace_context (Optional[int]) – K-space context. Default: None.

  • pass_dictionaries (Optional[Dict[str, Dict]]) – Pass a dictionary of dictionaries, e.g. if {"name": {"filename_0": val}}, then to filename_0``s sample dict, a key with name ``"name" and value val will be added. Default: None.

  • pass_h5s (Optional[Dict[str, List]]) – Pass a dictionary of paths. If {"name": path} is given then to the sample of filename the same slice of path / filename will be added to the sample dictionary and will be assigned key "name". This can for instance be convenient when you want to pass sensitivity maps as well. Default: None.

  • slice_data (Optional[slice]) – If set, for instance to slice(50,-50) only data within this slice will be added to the dataset. This is for instance convenient in the validation set of the public Calgary-Campinas dataset as the first 50 and last 50 slices are excluded in the evaluation. Default: None.

parse_filenames_data(filenames, extra_h5s=None, filter_slice=None)[source]#
static verify_extra_h5_integrity(image_fn, _, extra_h5s)[source]#
get_slice_data(filename, slice_no, key='kspace', pass_attrs=False, extra_keys=None)[source]#
get_num_slices(filename)[source]#

direct.data.lr_scheduler module#

class direct.data.lr_scheduler.LRScheduler(optimizer, last_epoch=-1)[source]#

Bases: _LRScheduler

__init__(optimizer, last_epoch=-1)[source]#
state_dict()[source]#

Returns the state of the scheduler as a dictionary.

It contains an entry for every variable in self.__dict__ which is not the optimizer or logger.

Returns:

State dictionary.

class direct.data.lr_scheduler.WarmupMultiStepLR(optimizer, milestones, gamma=0.1, warmup_factor=0.001, warmup_iterations=1000, warmup_method='linear', last_epoch=-1)[source]#

Bases: _LRScheduler

__init__(optimizer, milestones, gamma=0.1, warmup_factor=0.001, warmup_iterations=1000, warmup_method='linear', last_epoch=-1)[source]#
get_lr()[source]#

Compute learning rate using chainable form of the scheduler.

Return type:

List[float]

class direct.data.lr_scheduler.WarmupCosineLR(optimizer, max_iters, warmup_factor=0.001, warmup_iterations=1000, warmup_method='linear', last_epoch=-1)[source]#

Bases: _LRScheduler

__init__(optimizer, max_iters, warmup_factor=0.001, warmup_iterations=1000, warmup_method='linear', last_epoch=-1)[source]#
get_lr()[source]#

Compute learning rate using chainable form of the scheduler.

Return type:

List[float]

direct.data.mri_transforms module#

The direct.data.mri_transforms module contains mri transformations utilized to transform or augment k-space data, used for DIRECT’s training pipeline. They can be also used individually by importing them into python scripts.

class direct.data.mri_transforms.Compose(transforms)[source]#

Bases: DirectTransform

Compose several transformations together, for instance ClipAndScale and a flip.

Code based on torchvision: pytorch/vision, but got forked from there as torchvision has some additional dependencies.

__init__(transforms)[source]#

Inits Compose.

Parameters:

transforms (Iterable[Callable]) – List of transforms.

__call__(sample)[source]#

Calls Compose.

Parameters:

sample (dict[str, Any]) – Dict sample.

Return type:

dict[str, Any]

Returns:

Dict sample transformed by transforms.

__repr__()[source]#

Representation of Compose.

class direct.data.mri_transforms.RandomRotation(degrees=(-90, 90), p=0.5, keys_to_rotate=(TransformKey.KSPACE,))[source]#

Bases: DirectTransform

Random \(k\)-space rotation.

Performs a random rotation with probability \(p\). Rotation degrees must be multiples of 90.

__init__(degrees=(-90, 90), p=0.5, keys_to_rotate=(TransformKey.KSPACE,))[source]#

Inits RandomRotation.

Parameters:
  • degrees (Sequence[int]) – Degrees of rotation. Must be a multiple of 90. If len(degrees) > 1, then a degree will be chosen at random. Default: (-90, 90).

  • p (float) – Probability of rotation. Default: 0.5.

  • keys_to_rotate (tuple[TransformKey, ...]) – Keys to rotate. Default: (TransformKey.KSPACE,).

__call__(sample)[source]#

Calls RandomRotation.

Parameters:

sample (dict[str, Any]) – Dict sample.

Return type:

dict[str, Any]

Returns:

Sample with rotated values of keys_to_rotate.

class direct.data.mri_transforms.RandomFlipType(value, names=_not_given, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]#

Bases: DirectEnum

HORIZONTAL = 'horizontal'#
VERTICAL = 'vertical'#
RANDOM = 'random'#
BOTH = 'both'#
class direct.data.mri_transforms.RandomFlip(flip=RandomFlipType.RANDOM, p=0.5, keys_to_flip=(TransformKey.KSPACE,))[source]#

Bases: DirectTransform

Random k-space flip transform.

Performs a random flip with probability \(p\). Flip can be horizontal, vertical, or a random choice of the two.

__init__(flip=RandomFlipType.RANDOM, p=0.5, keys_to_flip=(TransformKey.KSPACE,))[source]#

Inits RandomFlip.

Parameters:
  • flip (RandomFlipType) – Horizontal, vertical, or random choice of the two. Default: RandomFlipType.RANDOM.

  • p (float) – Probability of flip. Default: 0.5

  • keys_to_flip (tuple[TransformKey, ...]) – Keys to flip. Default: “kspace”.

__call__(sample)[source]#

Calls RandomFlip.

Parameters:

sample (dict[str, Any]) – Dict sample.

Return type:

dict[str, Any]

Returns:

Sample with flipped values of keys_to_flip.

class direct.data.mri_transforms.RandomReverse(dim=1, p=0.5, keys_to_reverse=(TransformKey.KSPACE,))[source]#

Bases: DirectTransform

Random reverse of the order along a given dimension of a PyTorch tensor.

__init__(dim=1, p=0.5, keys_to_reverse=(TransformKey.KSPACE,))[source]#

Inits RandomReverse.

Parameters:
  • dim (int) – Dimension along to perform reversion. Typically, this is for time or slice dimension. Default: 2.

  • p (float) – Probability of flip. Default: 0.5

  • keys_to_reverse (tuple[TransformKey, ...]) – Keys to reverse. Default: “kspace”.

__call__(sample)[source]#

Calls RandomReverse.

Parameters:

sample (dict[str, Any]) – Dict sample.

Return type:

dict[str, Any]

Returns:

Sample with flipped values of keys_to_flip.

class direct.data.mri_transforms.CreateSamplingMask(mask_func, shape=None, use_seed=True, return_acs=False)[source]#

Bases: DirectTransform

Data Transformer for training MRI reconstruction models.

Creates sampling mask.

__init__(mask_func, shape=None, use_seed=True, return_acs=False)[source]#

Inits CreateSamplingMask.

Parameters:
  • mask_func (Callable) – A function which creates a sampling mask of the appropriate shape.

  • shape (Optional[tuple[int, ...]]) – Sampling mask shape. Default: None.

  • use_seed (bool) – If true, a pseudo-random number based on the filename is computed so that every slice of the volume get the same mask every time. Default: True.

  • return_acs (bool) – If True, it will generate an ACS mask. Default: False.

__call__(sample)[source]#

Calls CreateSamplingMask.

Parameters:

sample (dict[str, Any]) – Dict sample.

Return type:

dict[str, Any]

Returns:

Sample with sampling_mask key.

class direct.data.mri_transforms.ApplyMaskModule(sampling_mask_key='sampling_mask', input_kspace_key=KspaceKey.KSPACE, target_kspace_key=KspaceKey.MASKED_KSPACE)[source]#

Bases: DirectModule

Data Transformer for training MRI reconstruction models.

Masks the input k-space (with key input_kspace_key) using a sampling mask with key sampling_mask_key onto a new masked k-space with key target_kspace_key.

__init__(sampling_mask_key='sampling_mask', input_kspace_key=KspaceKey.KSPACE, target_kspace_key=KspaceKey.MASKED_KSPACE)[source]#

Inits ApplyMaskModule.

Parameters:
  • sampling_mask_key (str) – Default: “sampling_mask”.

  • input_kspace_key (KspaceKey) – Default: KspaceKey.KSPACE.

  • target_kspace_key (KspaceKey) – Default KspaceKey.MASKED_KSPACE.

forward(sample)[source]#

Forward pass of ApplyMaskModule.

Applies mask with key sampling_mask_key onto kspace input_kspace_key. Result is stored as a tensor with key target_kspace_key.

Parameters:

sample (dict[str, Any]) – Dict sample containing keys sampling_mask_key and input_kspace_key.

Return type:

dict[str, Any]

Returns:

Sample with (new) key target_kspace_key.

class direct.data.mri_transforms.CropKspace(crop, forward_operator=T.fft2, backward_operator=T.ifft2, image_space_center_crop=False, random_crop_sampler_type='uniform', random_crop_sampler_use_seed=True, random_crop_sampler_gaussian_sigma=None)[source]#

Bases: DirectTransform

Data Transformer for training MRI reconstruction models.

Crops the k-space by:
  • It first projects the k-space to the image-domain via the backward operator,

  • It crops the back-projected k-space to specified shape or key,

  • It transforms the cropped back-projected k-space to the k-space domain via the forward operator.

__init__(crop, forward_operator=T.fft2, backward_operator=T.ifft2, image_space_center_crop=False, random_crop_sampler_type='uniform', random_crop_sampler_use_seed=True, random_crop_sampler_gaussian_sigma=None)[source]#

Inits CropKspace.

Parameters:
  • crop (Union[str, tuple[int, ...], list[int]]) – Shape to crop the input to or a string pointing to a crop key (e.g. reconstruction_size).

  • forward_operator (Callable) – The forward operator, e.g. some form of FFT (centered or uncentered). Default: direct.data.transforms.fft2.

  • backward_operator (Callable) – The backward operator, e.g. some form of inverse FFT (centered or uncentered). Default: direct.data.transforms.ifft2.

  • image_space_center_crop (bool) – If set, the crop in the data will be taken in the center.

  • random_crop_sampler_type (Optional[str]) – If “uniform” the random cropping will be done by uniformly sampling crop, as opposed to gaussian which will sample from a gaussian distribution. If image_space_center_crop is True, then this is ignored. Default: “uniform”.

  • random_crop_sampler_use_seed (Optional[bool]) – If true, a pseudo-random number based on the filename is computed so that every slice of the volume is cropped the same way. Default: True.

  • random_crop_sampler_gaussian_sigma (Optional[list[float]]) – Standard variance of the gaussian when random_crop_sampler_type is gaussian. If image_space_center_crop is True, then this is ignored. Default: None.

__call__(sample)[source]#

Calls CropKspace.

Parameters:

sample (dict[str, Any]) – Dict sample containing key kspace.

Return type:

dict[str, Any]

Returns:

Cropped and masked sample.

class direct.data.mri_transforms.RescaleMode(value, names=_not_given, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]#

Bases: DirectEnum

AREA = 'area'#
BICUBIC = 'bicubic'#
BILINEAR = 'bilinear'#
NEAREST = 'nearest'#
NEAREST_EXACT = 'nearest-exact'#
TRILINEAR = 'trilinear'#
class direct.data.mri_transforms.RescaleKspace(shape, forward_operator=T.fft2, backward_operator=T.ifft2, rescale_mode=RescaleMode.NEAREST, kspace_key=KspaceKey.KSPACE, rescale_2d_if_3d=None)[source]#

Bases: DirectTransform

Rescale k-space (downsample/upsample) module.

Rescales the k-space: * It first projects the k-space to the image-domain via the backward operator, * It rescales the back-projected k-space to specified shape, * It transforms the rescaled back-projected k-space to the k-space domain via the forward operator.

Parameters:
  • shape (Union[tuple[int, int], list[int]]) – Shape to rescale the input. Must be correspond to (height, width).

  • forward_operator (Callable) – The forward operator, e.g. some form of FFT (centered or uncentered).

  • Default (supported for 2D or 3D data.) – direct.data.transforms.fft2.

  • backward_operator (Callable) – The backward operator, e.g. some form of inverse FFT (centered or uncentered).

  • Defaultdirect.data.transforms.ifft2.

  • rescale_mode (RescaleMode) – Mode to be used for rescaling. Can be RescaleMode.AREA, RescaleMode.BICUBIC, RescaleMode.BILINEAR,

  • RescaleMode.NEAREST

  • RescaleMode.NEAREST_EXACT

  • are (or RescaleMode.TRILINEAR. Note that not all modes)

  • Default – RescaleMode.NEAREST.

  • kspace_key (KspaceKey) – K-space key. Default: KspaceKey.KSPACE.

  • rescale_2d_if_3d (Optional[bool]) – If True and input k-space data is 3D, rescaling will be done only on the height and width dimensions.

  • Default – False.

  • Note – If the input k-space data is 3D, rescaling will be done only on the height and width dimensions if rescale_2d_if_3d is set to True.

__init__(shape, forward_operator=T.fft2, backward_operator=T.ifft2, rescale_mode=RescaleMode.NEAREST, kspace_key=KspaceKey.KSPACE, rescale_2d_if_3d=None)[source]#

Inits RescaleKspace.

Parameters:
  • shape (Union[tuple[int, int], list[int]]) – Shape to rescale the input. Must be correspond to (height, width).

  • forward_operator (Callable) – The forward operator, e.g. some form of FFT (centered or uncentered). Default: direct.data.transforms.fft2.

  • backward_operator (Callable) – The backward operator, e.g. some form of inverse FFT (centered or uncentered). Default: direct.data.transforms.ifft2.

  • rescale_mode (RescaleMode) – Mode to be used for rescaling. Can be RescaleMode.AREA, RescaleMode.BICUBIC, RescaleMode.BILINEAR, RescaleMode.NEAREST, RescaleMode.NEAREST_EXACT, or RescaleMode.TRILINEAR. Note that not all modes are supported for 2D or 3D data. Default: RescaleMode.NEAREST.

  • kspace_key (KspaceKey) – K-space key. Default: KspaceKey.KSPACE.

  • rescale_2d_if_3d (Optional[bool]) – If True and input k-space data is 3D, rescaling will be done only on the height and width dimensions, by combining the slice/time dimension with the batch dimension. Default: False.

__call__(sample)[source]#

Calls RescaleKspace.

Parameters:

sample (dict[str, Any]) – Dict sample containing key kspace.

Return type:

dict[str, Any]

Returns:

Cropped and masked sample.

class direct.data.mri_transforms.PadKspace(pad_shape, forward_operator=T.fft2, backward_operator=T.ifft2, kspace_key=KspaceKey.KSPACE)[source]#

Bases: DirectTransform

Pad k-space with zeros to desired shape module.

Rescales the k-space by: * It first projects the k-space to the image-domain via the backward operator, * It pads the back-projected k-space to specified shape, * It transforms the rescaled back-projected k-space to the k-space domain via the forward operator.

Parameters:
  • pad_shape (Union[tuple[int, ...], list[int]]) – Shape to zero-pad the input. Must be correspond to (height, width) or (slice/time, height, width).

  • forward_operator (Callable) – Callable

  • operator (The backward)

  • FFT (e.g. some form of inverse)

  • Default (K-space key.) – direct.data.transforms.fft2.

  • backward_operator (Callable) – Callable

  • operator

  • FFT

  • Defaultdirect.data.transforms.ifft2.

  • kspace_key (KspaceKey) – KspaceKey

  • Default – KspaceKey.KSPACE.

__init__(pad_shape, forward_operator=T.fft2, backward_operator=T.ifft2, kspace_key=KspaceKey.KSPACE)[source]#

Inits PadKspace.

Parameters:
  • pad_shape (Union[tuple[int, ...], list[int]]) – Shape to zero-pad the input. Must be correspond to (height, width) or (slice/time, height, width).

  • forward_operator (Callable) – The forward operator, e.g. some form of FFT (centered or uncentered). Default: direct.data.transforms.fft2.

  • backward_operator (Callable) – The backward operator, e.g. some form of inverse FFT (centered or uncentered). Default: direct.data.transforms.ifft2.

  • kspace_key (KspaceKey) – K-space key. Default: KspaceKey.KSPACE.

__call__(sample)[source]#

Calls PadKspace.

Parameters:

sample (dict[str, Any]) – Dict sample containing key kspace.

Return type:

dict[str, Any]

Returns:

Cropped and masked sample.

class direct.data.mri_transforms.ComputeZeroPadding(kspace_key=KspaceKey.KSPACE, padding_key='padding', eps=0.0001)[source]#

Bases: DirectTransform

Computes zero padding present in multi-coil kspace input.

Zero-padding is computed from multi-coil kspace with no signal contribution, i.e. its magnitude is really close to zero:

\[\text{padding} = \sum_{i=1}^{n_c} |y_i| < \frac{1}{n_x \cdot n_y} \sum_{j=1}^{n_x \cdot n_y} \big\{\sum_{i=1}^{n_c} |y_i|\big\} * \epsilon.\]
__init__(kspace_key=KspaceKey.KSPACE, padding_key='padding', eps=0.0001)[source]#

Inits ComputeZeroPadding.

Parameters:
  • kspace_key (KspaceKey) – K-space key. Default: KspaceKey.KSPACE.

  • padding_key (str) – Target key. Default: “padding”.

  • eps (Optional[float]) – Epsilon to multiply sum of signals. If really high, probably no padding will be produced. Default: 0.0001.

__call__(sample, coil_dim=0)[source]#

Updates sample with a key padding_key with value a binary tensor.

Non-zero entries indicate samples in kspace with key kspace_key which have minor contribution, i.e. padding.

Parameters:
  • sample (dict[str, Any]) – Dict sample containing key kspace_key.

  • coil_dim (int) – Coil dimension. Default: 0.

Return type:

dict[str, Any]

Returns:

Dict sample containing key padding_key.

class direct.data.mri_transforms.ApplyZeroPadding(kspace_key=KspaceKey.KSPACE, padding_key='padding')[source]#

Bases: DirectTransform

Applies zero padding present in multi-coil kspace input.

__init__(kspace_key=KspaceKey.KSPACE, padding_key='padding')[source]#

Inits ApplyZeroPadding.

Parameters:
  • kspace_key (KspaceKey) – K-space key. Default: KspaceKey.KSPACE.

  • padding_key (str) – Target key. Default: “padding”.

__call__(sample, coil_dim=0)[source]#

Applies zero padding on kspace_key with value a binary tensor.

Parameters:
  • sample (dict[str, Any]) – Dict sample containing key kspace_key.

  • coil_dim (int) – Coil dimension. Default: 0.

Return type:

dict[str, Any]

Returns:

Dict sample containing key padding_key.

class direct.data.mri_transforms.ReconstructionType(value, names=_not_given, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]#

Bases: DirectEnum

Reconstruction method for ComputeImage transform.

IFFT = 'ifft'#
RSS = 'rss'#
COMPLEX = 'complex'#
COMPLEX_MOD = 'complex_mod'#
SENSE = 'sense'#
SENSE_MOD = 'sense_mod'#
class direct.data.mri_transforms.ComputeImageModule(kspace_key, target_key, backward_operator, type_reconstruction=ReconstructionType.RSS)[source]#

Bases: DirectModule

Compute Image transform.

__init__(kspace_key, target_key, backward_operator, type_reconstruction=ReconstructionType.RSS)[source]#

Inits ComputeImageModule.

Parameters:
  • kspace_key (KspaceKey) – K-space key.

  • target_key (str) – Target key.

  • backward_operator (Callable) – The backward operator, e.g. some form of inverse FFT (centered or uncentered).

  • type_reconstruction (ReconstructionType) – Type of reconstruction. Can be ReconstructionType.RSS, ReconstructionType.COMPLEX, ReconstructionType.COMPLEX_MOD, ReconstructionType.SENSE, ReconstructionType.SENSE_MOD or ReconstructionType.IFFT. Default: ReconstructionType.RSS.

forward(sample)[source]#

Forward pass of ComputeImageModule.

Parameters:

sample (dict[str, Any]) – Contains key kspace_key with value a torch.Tensor of shape (coil, *spatial_dims, complex=2).

Return type:

dict[str, Any]

Returns:

Dict with key target_key with value a torch.Tensor of shape (*spatial_dims) if type_reconstruction is ReconstructionType.RSS, ReconstructionType.COMPLEX_MOD, ReconstructionType.SENSE_MOD, and of shape (*spatial_dims, complex_dim=2) otherwise.

class direct.data.mri_transforms.EstimateBodyCoilImage(mask_func, backward_operator, use_seed=True)[source]#

Bases: DirectTransform

Estimates body coil image.

__init__(mask_func, backward_operator, use_seed=True)[source]#

Inits EstimateBodyCoilImage.

Parameters:
  • mask_func (Callable) – A function which creates a sampling mask of the appropriate shape.

  • backward_operator (Callable) – The backward operator, e.g. some form of inverse FFT (centered or uncentered).

  • use_seed (bool) – If true, a pseudo-random number based on the filename is computed so that every slice of the volume get the same mask every time. Default: True.

__call__(sample, coil_dim=0)[source]#

Calls EstimateBodyCoilImage.

Parameters:
  • sample (dict[str, Any]) – Contains key kspace_key with value a torch.Tensor of shape (coil, …, complex=2).

  • coil_dim (int) – Coil dimension. Default: 0.

Return type:

dict[str, Any]

Returns:

Dict containing key “body_coil_image.

class direct.data.mri_transforms.SensitivityMapType(value, names=_not_given, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]#

Bases: DirectEnum

ESPIRIT = 'espirit'#
RSS_ESTIMATE = 'rss_estimate'#
UNIT = 'unit'#
class direct.data.mri_transforms.EstimateSensitivityMapModule(kspace_key=KspaceKey.KSPACE, backward_operator=T.ifft2, type_of_map=SensitivityMapType.RSS_ESTIMATE, gaussian_sigma=None, espirit_threshold=0.05, espirit_kernel_size=6, espirit_crop=0.95, espirit_max_iters=30)[source]#

Bases: DirectModule

Data Transformer for training MRI reconstruction models.

Estimates sensitivity maps given masked k-space data using one of three methods:

  • Unit: unit sensitivity map in case of single coil acquisition.

  • RSS-estimate: sensitivity maps estimated by using the root-sum-of-squares of the autocalibration-signal.

  • ESPIRIT: sensitivity maps estimated with the ESPIRIT method [1]_. Note that this is currently not implemented for 3D data, and attempting to use it in such cases will result in a NotImplementedError.

References:

__init__(kspace_key=KspaceKey.KSPACE, backward_operator=T.ifft2, type_of_map=SensitivityMapType.RSS_ESTIMATE, gaussian_sigma=None, espirit_threshold=0.05, espirit_kernel_size=6, espirit_crop=0.95, espirit_max_iters=30)[source]#

Inits EstimateSensitivityMapModule.

Parameters:
  • kspace_key (KspaceKey) – K-space key. Default: KspaceKey.KSPACE.

  • backward_operator (Callable) – The backward operator, e.g. some form of inverse FFT (centered or uncentered).

  • type_of_map (Optional[SensitivityMapType]) – Type of map to estimate. Can be SensitivityMapType.RSS_ESTIMATE, SensitivityMapType.UNIT or SensitivityMapType.ESPIRIT. Default: SensitivityMapType.RSS_ESTIMATE.

  • gaussian_sigma (Optional[float]) – If non-zero, acs_image well be calculated.

  • espirit_threshold (Optional[float]) – Threshold for the calibration matrix when type_of_map is set to SensitivityMapType.ESPIRIT. Default: 0.05.

  • espirit_kernel_size (Optional[int]) – Kernel size for the calibration matrix when type_of_map is set to SensitivityMapType.ESPIRIT. Default: 6.

  • espirit_crop (Optional[float]) – Output eigenvalue cropping threshold when type_of_map is set to SensitivityMapType.ESPIRIT. Default: 0.95.

  • espirit_max_iters (Optional[int]) – Power method iterations when type_of_map is set to SensitivityMapType.ESPIRIT. Default: 30.

estimate_acs_image(sample, width_dim=-2)[source]#

Estimates the autocalibration (ACS) image by sampling the k-space using the ACS mask.

Parameters:
  • sample (dict[str, Any]) – Sample dictionary.

  • width_dim (int) – Dimension corresponding to width. Default: -2.

Return type:

Tensor

Returns:

Estimate of the ACS image.

forward(sample)[source]#

Calculates sensitivity maps for the input sample.

Parameters:

sample (dict[str, Any]) – Must contain key matching kspace_key with value a (complex) torch.Tensor of shape (coil, height, width, complex=2).

Return type:

dict[str, Any]

Returns:

Sample with key “sensitivity_map” with value the estimated sensitivity map.

class direct.data.mri_transforms.AddBooleanKeysModule(keys, values)[source]#

Bases: DirectModule

Adds keys with boolean values to sample.

__init__(keys, values)[source]#

Inits AddBooleanKeysModule.

Parameters:
  • keys (list[str]) – A list of keys to be added.

  • values (list[bool]) – A list of values corresponding to the keys.

forward(sample)[source]#

Adds boolean keys to the input sample dictionary.

Parameters:

sample (dict[str, Any]) – The input sample dictionary.

Return type:

dict[str, Any]

Returns:

The modified sample with added boolean keys.

class direct.data.mri_transforms.CompressCoilModule(kspace_key, num_coils)[source]#

Bases: DirectModule

Compresses k-space coils using SVD.

__init__(kspace_key, num_coils)[source]#

Inits CompressCoilModule.

Parameters:
  • kspace_key (KspaceKey) – K-space key.

  • num_coils (int) – Number of coils to compress.

forward(sample)[source]#

Performs coil compression to input k-space.

Parameters:

sample (dict[str, Any]) – Dict sample containing key kspace_key. Assumes coil dimension is first axis.

Return type:

dict[str, Any]

Returns:

Dict sample with kspace_key compressed to num_coils.

class direct.data.mri_transforms.DeleteKeysModule(keys)[source]#

Bases: DirectModule

Remove keys from the sample if present.

__init__(keys)[source]#

Inits DeleteKeys.

Parameters:

keys (list[str]) – Key(s) to delete.

forward(sample)[source]#

Forward pass of DeleteKeys.

Parameters:

sample (dict[str, Any]) – Dictionary to look for keys and remove them.

Return type:

dict[str, Any]

Returns:

Dictionary with deleted specified keys.

class direct.data.mri_transforms.RenameKeysModule(old_keys, new_keys)[source]#

Bases: DirectModule

Rename keys from the sample if present.

__init__(old_keys, new_keys)[source]#

Inits RenameKeys.

Parameters:
  • old_keys (list[str]) – Key(s) to rename.

  • new_keys (list[str]) – Key(s) to replace old keys.

forward(sample)[source]#

Forward pass of RenameKeys.

Parameters:

sample (dict[str, Any]) – Dictionary to look for keys and rename them.

Return type:

dict[str, Any]

Returns:

Dictionary with renamed specified keys.

class direct.data.mri_transforms.PadCoilDimensionModule(pad_coils=None, key='masked_kspace', coil_dim=1)[source]#

Bases: DirectModule

Pad the coils by zeros to a given number of coils.

Useful if you want to collate volumes with different coil dimension.

__init__(pad_coils=None, key='masked_kspace', coil_dim=1)[source]#

Inits PadCoilDimensionModule.

Parameters:
  • pad_coils (Optional[int]) – Number of coils to pad to. Default: None.

  • key (str) – Key to pad in sample. Default: “masked_kspace”.

  • coil_dim (int) – Coil dimension along which the pad will be done. Default: 0.

forward(sample)[source]#

Forward pass of PadCoilDimensionModule.

Parameters:

sample (dict[str, Any]) – Dictionary with key self.key.

Return type:

dict[str, Any]

Returns:

Dictionary with padded coils of sample[self.key] if self.num_coils is not None.

class direct.data.mri_transforms.ComputeScalingFactorModule(normalize_key=TransformKey.MASKED_KSPACE, percentile=0.99, scaling_factor_key=TransformKey.SCALING_FACTOR)[source]#

Bases: DirectModule

Calculates scaling factor.

Scaling factor is for the input data based on either to the percentile or to the maximum of normalize_key.

__init__(normalize_key=TransformKey.MASKED_KSPACE, percentile=0.99, scaling_factor_key=TransformKey.SCALING_FACTOR)[source]#

Inits ComputeScalingFactorModule.

Parameters:
  • normalize_key (Optional[TransformKey]) – Key name to compute the data for. If the maximum has to be computed on the ACS, ensure the reconstruction on the ACS is available (typically body_coil_image). Default: “masked_kspace”.

  • percentile (Optional[float]) – Rescale data with the given percentile. If None, the division is done by the maximum. Default: 0.99.

  • scaling_factor_key (TransformKey) – Name of how the scaling factor will be stored. Default: “scaling_factor”.

forward(sample)[source]#

Forward pass of ComputeScalingFactorModule.

Parameters:

sample (dict[str, Any]) – Sample with key normalize_key to compute scaling_factor.

Return type:

dict[str, Any]

Returns:

Sample with key scaling_factor_key.

class direct.data.mri_transforms.NormalizeModule(scaling_factor_key=TransformKey.SCALING_FACTOR, keys_to_normalize=None)[source]#

Bases: DirectModule

Normalize the input data.

__init__(scaling_factor_key=TransformKey.SCALING_FACTOR, keys_to_normalize=None)[source]#

Inits NormalizeModule.

Parameters:
  • scaling_factor_key (TransformKey) – Name of scaling factor key expected in sample. Default: ‘scaling_factor’.

  • keys_to_normalize (Optional[list[TransformKey]]) – List of keys to normalize.

forward(sample)[source]#

Forward pass of NormalizeModule.

Parameters:

sample (dict[str, Any]) – Sample to normalize.

Return type:

dict[str, Any]

Returns:

Sample with normalized values if their respective key is in keys_to_normalize and key scaling_factor_key exists in sample.

class direct.data.mri_transforms.WhitenDataModule(epsilon=1e-10, key='complex_image')[source]#

Bases: DirectModule

Whitens complex data Module.

__init__(epsilon=1e-10, key='complex_image')[source]#

Inits WhitenDataModule.

Parameters:
  • epsilon (float) – Default: 1e-10.

  • key (str) – Key to whiten. Default: “complex_image”.

complex_whiten(complex_image)[source]#

Whiten complex image.

Parameters:

complex_image (Tensor) – Complex image tensor to whiten.

Return type:

tuple[Tensor, Tensor, Tensor]

Returns:

Tuple of (mean, std, whitened_image).

forward(sample)[source]#

Forward pass of WhitenDataModule.

Parameters:

sample (dict[str, Any]) – Sample with key key.

Return type:

dict[str, Any]

Returns:

Sample with value of key whitened.

class direct.data.mri_transforms.ModuleWrapper(module, toggle_dims)[source]#

Bases: object

class SubWrapper(transform, toggle_dims)[source]#

Bases: object

__init__(transform, toggle_dims)[source]#
__init__(module, toggle_dims)[source]#
class direct.data.mri_transforms.ToTensor[source]#

Bases: DirectTransform

Transforms all np.array-like values in sample to torch.tensors.

__call__(sample)[source]#

Calls ToTensor.

Parameters:

sample (dict[str, Any]) – Contains key ‘kspace’ with value a np.array of shape (coil, height, width) (2D) or (coil, slice, height, width) (3D)

Return type:

dict[str, Any]

Returns:

Dictionary containing key ‘kspace’ with value a torch.Tensor of shape (coil, height, width) (2D) or (coil, slice, height, width) (3D)

direct.data.mri_transforms.build_pre_mri_transforms(forward_operator, backward_operator, mask_func, crop=None, crop_type='uniform', rescale=None, rescale_mode=RescaleMode.NEAREST, rescale_2d_if_3d=False, pad=None, image_center_crop=True, random_rotation_degrees=(-90, 90), random_rotation_probability=0.0, random_flip_type=RandomFlipType.RANDOM, random_flip_probability=0.0, padding_eps=0.0001, estimate_body_coil_image=False, use_seed=True, pad_coils=None)[source]#

Builds pre (on cpu) supervised MRI transforms.

More specifically, the following transformations are applied:

  • Converts input to (complex-valued) tensor.

  • Applies k-space (center) crop if requested.

  • Applies random augmentations (rotation, flip, reverse) if requested.

  • Adds a sampling mask if mask_func is defined.

  • Pads the coil dimension if requested.

Parameters:
  • forward_operator (Callable) – The forward operator, e.g. some form of FFT (centered or uncentered).

  • backward_operator (Callable) – The backward operator, e.g. some form of inverse FFT (centered or uncentered).

  • mask_func (Optional[Callable]) – A function which creates a sampling mask of the appropriate shape.

  • crop (Union[tuple[int, int], str, None]) – If not None, this will transform the “kspace” to an image domain, crop it, and transform it back. If a tuple of integers is given then it will crop the backprojected kspace to that size. If “reconstruction_size” is given, then it will crop the backprojected kspace according to it, but a key “reconstruction_size” must be present in the sample. Default: None.

  • crop_type (Optional[str]) – Type of cropping, either “gaussian” or “uniform”. This will be ignored if crop is None. Default: “uniform”.

  • rescale (Union[tuple[int, int], list[int], None]) – If not None, this will transform the “kspace” to the image domain, rescale it, and transform it back. Must correspond to (height, width). This is ignored if rescale is None. Default: None. It is not recommended to be used in combination with crop.

  • rescale_mode (Optional[RescaleMode]) – Mode to be used for rescaling. Can be RescaleMode.AREA, RescaleMode.BICUBIC, RescaleMode.BILINEAR, RescaleMode.NEAREST, RescaleMode.NEAREST_EXACT, or RescaleMode.TRILINEAR. Note that not all modes are supported for 2D or 3D data. Default: RescaleMode.NEAREST.

  • rescale_2d_if_3d (Optional[bool]) – If True and k-space data is 3D, rescaling will be done only on the height and width dimensions, by combining the slice/time dimension with the batch dimension. This is ignored if rescale is None. Default: False.

  • pad (Union[tuple[int, int], list[int], None]) – If not None, this will zero-pad the “kspace” to the given size. Must correspond to (height, width) or (slice/time, height, width). Default: None.

  • image_center_crop (bool) – If True the backprojected kspace will be cropped around the center, otherwise randomly. This will be ignored if crop is None. Default: True.

  • random_rotation_degrees (Optional[Sequence[int]]) – Sequence of integers. Default: (-90, 90).

  • random_rotation_probability (float) – If greater than 0.0, random rotations will be applied of random_rotation_degrees degrees, with probability random_rotation_probability. Default: 0.0.

  • random_flip_type (Optional[RandomFlipType]) – Default: RandomFlipType.RANDOM.

  • random_flip_probability (float) – If greater than 0.0, random rotation of random_flip_type type, with probability random_flip_probability. Default: 0.0.

  • padding_eps (float) – Padding epsilon. Default: 0.0001.

  • estimate_body_coil_image (bool) – Estimate body coil image. Default: False.

  • use_seed (bool) – If true, a pseudo-random number based on the filename is computed so that every slice of the volume get the same mask every time. Default: True.

Return type:

DirectTransform

Returns:

DirectTransform An MRI transformation object.

direct.data.mri_transforms.build_post_mri_transforms(backward_operator, estimate_sensitivity_maps=True, sensitivity_maps_type=SensitivityMapType.RSS_ESTIMATE, sensitivity_maps_gaussian=None, sensitivity_maps_espirit_threshold=0.05, sensitivity_maps_espirit_kernel_size=6, sensitivity_maps_espirit_crop=0.95, sensitivity_maps_espirit_max_iters=30, delete_acs_mask=True, delete_kspace=True, image_recon_type=ReconstructionType.RSS, scaling_key=TransformKey.MASKED_KSPACE, scale_percentile=0.99)[source]#

Builds post (can be put on gpu) supervised MRI transforms.

More specifically, the following transformations are applied:

  • Adds coil sensitivities and / or the body coil_image

  • Masks the fully sampled k-space, if there is a mask function or a mask in the sample.

  • Computes a scaling factor based on the masked k-space and normalizes data.

  • Computes a target (image).

  • Deletes the acs mask and the fully sampled k-space if requested.

Parameters:
  • backward_operator (Callable) – The backward operator, e.g. some form of inverse FFT (centered or uncentered).

  • estimate_sensitivity_maps (bool) – Estimate sensitivity maps using the acs region. Default: True.

  • sensitivity_maps_type (SensitivityMapType) – Can be SensitivityMapType.RSS_ESTIMATE, SensitivityMapType.UNIT or SensitivityMapType.ESPIRIT. Will be ignored if estimate_sensitivity_maps is equal to False. Default: SensitivityMapType.RSS_ESTIMATE.

  • sensitivity_maps_gaussian (Optional[float]) – Optional sigma for gaussian weighting of sensitivity map.

  • sensitivity_maps_espirit_threshold (Optional[float]) – Threshold for the calibration matrix when type_of_map is equal to “espirit”. Default: 0.05.

  • sensitivity_maps_espirit_kernel_size (Optional[int]) – Kernel size for the calibration matrix when type_of_map is equal to “espirit”. Default: 6.

  • sensitivity_maps_espirit_crop (Optional[float]) – Output eigenvalue cropping threshold when type_of_map is equal to “espirit”. Default: 0.95.

  • sensitivity_maps_espirit_max_iters (Optional[int]) – Power method iterations when type_of_map is equal to “espirit”. Default: 30.

  • delete_acs_mask (bool) – If True will delete key acs_mask. Default: True.

  • delete_kspace (bool) – If True will delete key kspace (fully sampled k-space). Default: True.

  • image_recon_type (ReconstructionType) – Type to reconstruct target image. Default: ReconstructionType.RSS.

  • scaling_key (TransformKey) – Key in sample to scale scalable items in sample. Default: TransformKey.MASKED_KSPACE.

  • scale_percentile (Optional[float]) – Data will be rescaled with the given percentile. If None, the division is done by the maximum. Default: 0.99

Return type:

DirectTransform

Returns:

DirectTransform An MRI transformation object.

direct.data.mri_transforms.build_supervised_mri_transforms(forward_operator, backward_operator, mask_func, crop=None, crop_type='uniform', rescale=None, rescale_mode=RescaleMode.NEAREST, rescale_2d_if_3d=False, pad=None, image_center_crop=True, random_rotation_degrees=(-90, 90), random_rotation_probability=0.0, random_flip_type=RandomFlipType.RANDOM, random_flip_probability=0.0, random_reverse_probability=0.0, padding_eps=0.0001, estimate_body_coil_image=False, estimate_sensitivity_maps=True, sensitivity_maps_type=SensitivityMapType.RSS_ESTIMATE, sensitivity_maps_gaussian=None, sensitivity_maps_espirit_threshold=0.05, sensitivity_maps_espirit_kernel_size=6, sensitivity_maps_espirit_crop=0.95, sensitivity_maps_espirit_max_iters=30, delete_acs_mask=True, delete_kspace=True, image_recon_type=ReconstructionType.RSS, compress_coils=None, pad_coils=None, scaling_key=TransformKey.MASKED_KSPACE, scale_percentile=0.99, use_seed=True)[source]#

Builds supervised MRI transforms.

More specifically, the following transformations are applied:

  • Converts input to (complex-valued) tensor.

  • Applies k-space (center) crop if requested.

  • Applies k-space rescaling if requested.

  • Applies k-space padding if requested.

  • Applies random augmentations (rotation, flip, reverse) if requested.

  • Adds a sampling mask if mask_func is defined.

  • Compreses the coil dimension if requested.

  • Pads the coil dimension if requested.

  • Adds coil sensitivities and / or the body coil_image

  • Masks the fully sampled k-space, if there is a mask function or a mask in the sample.

  • Computes a scaling factor based on the masked k-space and normalizes data.

  • Computes a target (image).

  • Deletes the acs mask and the fully sampled k-space if requested.

Parameters:
  • forward_operator (Callable) – The forward operator, e.g. some form of FFT (centered or uncentered).

  • backward_operator (Callable) – The backward operator, e.g. some form of inverse FFT (centered or uncentered).

  • mask_func (Optional[Callable]) – A function which creates a sampling mask of the appropriate shape.

  • crop (Union[tuple[int, int], str, None]) – If not None, this will transform the “kspace” to an image domain, crop it, and transform it back.

  • None (If not)

  • domain (this will transform the "kspace" to an image)

  • it (then it will crop the backprojected kspace according to)

  • back. (and transform it)

  • given (If a tuple of integers is given then it will crop the backprojected kspace to that size. If "reconstruction_size" is) – None.

  • it – None.

  • Default (Estimate body coil image.) – None.

  • crop_type (Optional[str]) – Type of cropping, either “gaussian” or “uniform”. This will be ignored if crop is None. Default: “uniform”.

  • rescale (Union[tuple[int, int], list[int], None]) – If not None, this will transform the “kspace” to the image domain, rescale it, and transform it back. Must correspond to (height, width). This is ignored if rescale is None. Default: None. It is not recommended to be used in combination with crop.

  • rescale_mode (Optional[RescaleMode]) – Mode to be used for rescaling. Can be RescaleMode.AREA, RescaleMode.BICUBIC, RescaleMode.BILINEAR, RescaleMode.NEAREST, RescaleMode.NEAREST_EXACT, or RescaleMode.TRILINEAR. Note that not all modes are supported for 2D or 3D data. Default: RescaleMode.NEAREST.

  • rescale_2d_if_3d (Optional[bool]) – If True and k-space data is 3D, rescaling will be done only on the height and width dimensions, by combining the slice/time dimension with the batch dimension. This is ignored if rescale is None. Default: False.

  • pad (Union[tuple[int, int], list[int], None]) – If not None, this will zero-pad the “kspace” to the given size. Must correspond to (height, width) or (slice/time, height, width). Default: None.

  • image_center_crop (bool) – If True the backprojected kspace will be cropped around the center, otherwise randomly. This will be ignored if crop is None. Default: True.

  • random_rotation_degrees (Optional[Sequence[int]]) – Sequence of integers. Default: (-90, 90).

  • random_rotation_probability (float) – If greater than 0.0, random rotations will be applied of random_rotation_degrees degrees, with probability random_rotation_probability. Default: 0.0.

  • random_flip_type (Optional[RandomFlipType]) – Default: RandomFlipType.RANDOM.

  • random_flip_probability (float) – If greater than 0.0, random rotation of random_flip_type type, with probability random_flip_probability. Default: 0.0.

  • random_reverse_probability (float) – If greater than 0.0, will perform random reversion along the time or slice dimension (2) with probability random_reverse_probability. Default: 0.0.

  • padding_eps (float) – Padding epsilon. Default: 0.0001.

  • estimate_body_coil_image (bool) – Estimate body coil image. Default: False.

  • Default – False.

  • estimate_sensitivity_maps (bool) – Estimate sensitivity maps using the acs region. Default: True.

  • sensitivity_maps_type (SensitivityMapType) – Can be SensitivityMapType.RSS_ESTIMATE, SensitivityMapType.UNIT or SensitivityMapType.ESPIRIT. Will be ignored if estimate_sensitivity_maps is False. Default: SensitivityMapType.RSS_ESTIMATE.

  • sensitivity_maps_gaussian (Optional[float]) – Optional sigma for gaussian weighting of sensitivity map.

  • sensitivity_maps_espirit_threshold (Optional[float]) – Threshold for the calibration matrix when type_of_map is set to SensitivityMapType.ESPIRIT. Default: 0.05.

  • sensitivity_maps_espirit_kernel_size (Optional[int]) – Kernel size for the calibration matrix when type_of_map is set to SensitivityMapType.ESPIRIT. Default: 6.

  • sensitivity_maps_espirit_crop (Optional[float]) – Output eigenvalue cropping threshold when type_of_map is set to SensitivityMapType.ESPIRIT. Default: 0.95.

  • sensitivity_maps_espirit_max_iters (Optional[int]) – Power method iterations when type_of_map is set to SensitivityMapType.ESPIRIT. Default: 30.

  • delete_acs_mask (bool) – If True will delete key acs_mask. Default: True.

  • delete_kspace (bool) – If True will delete key kspace (fully sampled k-space). Default: True.

  • kspace (If True will delete key) – True.

  • image_recon_type (ReconstructionType) – Type to reconstruct target image. Default: ReconstructionType.RSS.

  • compress_coils (Optional[int]) – Number of coils to compress input k-space. It is not recommended to be used in combination with pad_coils. Default: None.

  • pad_coils (Optional[int]) – Number of coils to pad data to.

  • scaling_key (TransformKey) – Key in sample to scale scalable items in sample. Default: TransformKey.MASKED_KSPACE.

  • scale_percentile (Optional[float]) – Data will be rescaled with the given percentile. If None, the division is done by the maximum. Default: 0.99

  • use_seed (bool) – If true, a pseudo-random number based on the filename is computed so that every slice of the volume get the same mask every time. Default: True.

Return type:

DirectTransform

Returns:

DirectTransform An MRI transformation object.

class direct.data.mri_transforms.TransformsType(value, names=_not_given, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]#

Bases: DirectEnum

SUPERVISED = 'supervised'#
SSL_SSDU = 'ssl_ssdu'#
direct.data.mri_transforms.build_mri_transforms(forward_operator, backward_operator, mask_func, crop=None, crop_type='uniform', rescale=None, rescale_mode=RescaleMode.NEAREST, rescale_2d_if_3d=False, pad=None, image_center_crop=True, random_rotation_degrees=(-90, 90), random_rotation_probability=0.0, random_flip_type=RandomFlipType.RANDOM, random_flip_probability=0.0, random_reverse_probability=0.0, padding_eps=0.0001, estimate_body_coil_image=False, estimate_sensitivity_maps=True, sensitivity_maps_type=SensitivityMapType.RSS_ESTIMATE, sensitivity_maps_gaussian=None, sensitivity_maps_espirit_threshold=0.05, sensitivity_maps_espirit_kernel_size=6, sensitivity_maps_espirit_crop=0.95, sensitivity_maps_espirit_max_iters=30, delete_acs_mask=True, delete_kspace=True, image_recon_type=ReconstructionType.RSS, compress_coils=None, pad_coils=None, scaling_key=TransformKey.MASKED_KSPACE, scale_percentile=0.99, use_seed=True, transforms_type=TransformsType.SUPERVISED, mask_split_ratio=0.4, mask_split_acs_region=(0, 0), mask_split_keep_acs=False, mask_split_type=MaskSplitterType.GAUSSIAN, mask_split_gaussian_std=3.0, mask_split_half_direction=HalfSplitType.VERTICAL)[source]#

Build transforms for MRI.

More specifically, the following transformations are applied:

  • Converts input to (complex-valued) tensor.

  • Applies k-space (center) crop if requested.

  • Applies k-space rescaling if requested.

  • Applies k-space padding if requested.

  • Applies random augmentations (rotation, flip, reverse) if requested.

  • Adds a sampling mask if mask_func is defined.

  • Compreses the coil dimension if requested.

  • Pads the coil dimension if requested.

  • Adds coil sensitivities and / or the body coil_image

  • Masks the fully sampled k-space, if there is a mask function or a mask in the sample.

  • Computes a scaling factor based on the masked k-space and normalizes data.

  • Computes a target (image).

  • Deletes the acs mask and the fully sampled k-space if requested.

  • Splits the mask if requested for self-supervised learning.

Parameters:
  • forward_operator (Callable) – The forward operator, e.g. some form of FFT (centered or uncentered).

  • backward_operator (Callable) – The backward operator, e.g. some form of inverse FFT (centered or uncentered).

  • mask_func (Optional[Callable]) – A function which creates a sampling mask of the appropriate shape.

  • crop (Union[tuple[int, int], str, None]) – If not None, this will transform the “kspace” to an image domain, crop it, and transform it back.

  • None (If not)

  • domain (this will transform the "kspace" to an image)

  • it (then it will crop the backprojected kspace according to)

  • back. (and transform it)

  • given (If a tuple of integers is given then it will crop the backprojected kspace to that size. If "reconstruction_size" is) – None.

  • it – None.

  • Default (but a key "reconstruction_size" must be present in the sample.) – None.

  • crop_type (Optional[str]) – Type of cropping, either “gaussian” or “uniform”. This will be ignored if crop is None. Default: “uniform”.

  • rescale (Union[tuple[int, int], list[int], None]) – If not None, this will transform the “kspace” to the image domain, rescale it, and transform it back. Must correspond to (height, width). This is ignored if rescale is None. Default: None. It is not recommended to be used in combination with crop.

  • rescale_mode (Optional[RescaleMode]) – Mode to be used for rescaling. Can be RescaleMode.AREA, RescaleMode.BICUBIC, RescaleMode.BILINEAR, RescaleMode.NEAREST, RescaleMode.NEAREST_EXACT, or RescaleMode.TRILINEAR. Note that not all modes are supported for 2D or 3D data. Default: RescaleMode.NEAREST.

  • rescale_2d_if_3d (Optional[bool]) – If True and k-space data is 3D, rescaling will be done only on the height and width dimensions, by combining the slice/time dimension with the batch dimension. This is ignored if rescale is None. Default: False.

  • pad (Union[tuple[int, int], list[int], None]) – If not None, this will zero-pad the “kspace” to the given size. Must correspond to (height, width) or (slice/time, height, width). Default: None.

  • image_center_crop (bool) – If True the backprojected kspace will be cropped around the center, otherwise randomly. This will be ignored if crop is None. Default: True.

  • random_rotation_degrees (Optional[Sequence[int]]) – Sequence of integers. Default: (-90, 90).

  • random_rotation_probability (float) – If greater than 0.0, random rotations will be applied of random_rotation_degrees degrees, with probability random_rotation_probability. Default: 0.0.

  • random_flip_type (Optional[RandomFlipType]) – Default: RandomFlipType.RANDOM.

  • random_flip_probability (float) – If greater than 0.0, random rotation of random_flip_type type, with probability random_flip_probability. Default: 0.0.

  • RescaleMode.AREA (Mode to be used for rescaling. Can be)

  • RescaleMode.BICUBIC

  • RescaleMode.BILINEAR

:param : :param RescaleMode.NEAREST: :param RescaleMode.NEAREST_EXACT: :param or RescaleMode.TRILINEAR. Note that not all modes are: :param supported for 2D or 3D data. Default: RescaleMode.NEAREST. :param rescale_2d_if_3d: If True and k-space data is 3D, rescaling will be done only on the height and width dimensions, by combining the slice/time dimension with the batch dimension. This is ignored if rescale is None. Default: False. :param pad: If not None, this will zero-pad the “kspace” to the given size. Must correspond to (height, width) or (slice/time, height, width). Default: None. :param image_center_crop: If True the backprojected kspace will be cropped around the center, otherwise randomly.

This will be ignored if crop is None. Default: True.

Parameters:
  • random_rotation_degrees – Sequence of integers. Default: (-90, 90).

  • random_rotation_probability – If greater than 0.0, random rotations will be applied of random_rotation_degrees degrees, with probability random_rotation_probability. Default: 0.0.

  • random_flip_type – Default: RandomFlipType.RANDOM.

  • random_flip_probability – If greater than 0.0, random rotation of random_flip_type type, with probability random_flip_probability. Default: 0.0.

  • random_reverse_probability (float) – If greater than 0.0, will perform random reversion along the time or slice dimension (2) with probability random_reverse_probability. Default: 0.0.

  • padding_eps (float) – Padding epsilon. Default: 0.0001.

  • estimate_body_coil_image (bool) – Estimate body coil image. Default: False.

  • estimate_sensitivity_maps (bool) – Estimate sensitivity maps using the acs region. Default: True.

  • sensitivity_maps_type (SensitivityMapType) – Can be SensitivityMapType.RSS_ESTIMATE, SensitivityMapType.UNIT or SensitivityMapType.ESPIRIT. Will be ignored if estimate_sensitivity_maps is False. Default: SensitivityMapType.RSS_ESTIMATE.

  • sensitivity_maps_gaussian (Optional[float]) – Optional sigma for gaussian weighting of sensitivity map.

  • sensitivity_maps_espirit_threshold (Optional[float]) – Threshold for the calibration matrix when type_of_map is set to SensitivityMapType.ESPIRIT.

  • sensitivity_maps_espirit_kernel_size (Optional[int]) – Kernel size for the calibration matrix when type_of_map is set to SensitivityMapType.ESPIRIT. Default: 6.

  • sensitivity_maps_espirit_crop (Optional[float]) – Output eigenvalue cropping threshold when type_of_map is set to SensitivityMapType.ESPIRIT. Default: 0.95.

  • sensitivity_maps_espirit_max_iters (Optional[int]) – Power method iterations when type_of_map is set to SensitivityMapType.ESPIRIT. Default: 30.

  • delete_acs_mask (bool) – If True will delete key acs_mask. Default: True.

  • delete_kspace (bool) – If True will delete key kspace (fully sampled k-space). Default: True.

  • image_recon_type (ReconstructionType) – Type to reconstruct target image. Default: ReconstructionType.RSS.

  • compress_coils (Optional[int]) – Number of coils to compress input k-space. It is not recommended to be used in combination with pad_coils. Default: None.

  • pad_coils (Optional[int]) – Number of coils to pad data to.

  • scaling_key (TransformKey) – Key in sample to scale scalable items in sample. Default: TransformKey.MASKED_KSPACE.

  • scale_percentile (Optional[float]) – Data will be rescaled with the given percentile. If None, the division is done by the maximum. Default: 0.99

  • use_seed (bool) – If true, a pseudo-random number based on the filename is computed so that every slice of the volume get the same mask every time. Default: True.

  • transforms_type (Optional[TransformsType]) – Can be TransformsType.SUPERVISED for supervised learning transforms or TransformsType.SSL_SSDU for self-supervised learning transforms. Default: TransformsType.SUPERVISED.

  • mask_split_ratio (Union[float, list[float], tuple[float, ...]]) – The ratio(s) of the sampling mask splitting. If transforms_type is TransformsKey.SUPERVISED, this is ignored.

  • mask_split_acs_region (Union[list[int], tuple[int, int]]) – A rectangle for the acs region that will be used in the input mask. This applies only if transforms_type is set to TransformsKey.SSL_SSDU. Default: (0, 0).

  • mask_split_keep_acs (Optional[bool]) – If True, acs region according to the “acs_mask” of the sample will be used in both mask splits. This applies only if transforms_type is set to TransformsKey.SSL_SSDU. Default: False.

  • mask_split_type (MaskSplitterType) – How the sampling mask will be split. Can be MaskSplitterType.UNIFORM, MaskSplitterType.GAUSSIAN, or

  • Default (set to TransformsKey.SSL_SSDU.) – MaskSplitterType.GAUSSIAN. This applies only if transforms_type is

  • Default – MaskSplitterType.GAUSSIAN.

  • mask_split_gaussian_std (float) – Standard deviation of gaussian mask splitting. This applies only if transforms_type is

  • MaskSplitterType.GAUSSIAN. (set to TransformsKey.SSL_SSDU. Ignored if mask_split_type is not set to)

  • Default – 3.0.

  • mask_split_half_direction (HalfSplitType) – Split type if mask_split_type is MaskSplitterType.HALF. Can be HalfSplitType.VERTICAL, HalfSplitType.HORIZONTAL, HalfSplitType.DIAGONAL_LEFT or HalfSplitType.DIAGONAL_RIGHT. This applies only if transforms_type is set to TransformsKey.SSL_SSDU. Ignored if mask_split_type is not set to MaskSplitterType.HALF. Default: HalfSplitType.VERTICAL.

Return type:

DirectTransform

Returns:

DirectTransform An MRI transformation object.

direct.data.samplers module#

Module containing all sampler logic.

class direct.data.samplers.DistributedSampler(size, shuffle=True, seed=None)[source]#

Bases: Sampler

In training, we only care about the “infinite stream” of training data.

So this sampler produces an infinite stream of indices and all workers cooperate to correctly shuffle the indices and sample different indices. The samplers in each worker effectively produces indices[worker_id::num_workers] where indices is an infinite stream of indices consisting of shuffle(range(size)) + shuffle(range(size)) + ... (if shuffle is True) or range(size) + range(size) + ... (if shuffle is False).

__init__(size, shuffle=True, seed=None)[source]#

Inits DistributedSampler.

Parameters:
  • size (int) – Size of underlying dataset.

  • shuffle (bool) – If True, the indices will be shuffled. Default: True.

  • seed (Optional[int]) – Initial seed of the shuffle, must be the same across all workers! Default: None.

class direct.data.samplers.DistributedSequentialSampler(dataset, num_replicas=None, rank=None, limit_number_of_volumes=None)[source]#

Bases: Sampler

Sequential Sampler that restricts data loading to a subset of the dataset.

It is useful during evaluation. It is especially useful when combined with torch.nn.parallel.DistributedDataParallel. Such that each process gets a subpart of the dataset.

Note

Dataset is assumed to be of constant size.

__init__(dataset, num_replicas=None, rank=None, limit_number_of_volumes=None)[source]#
class direct.data.samplers.BatchVolumeSampler(sampler, batch_size)[source]#

Bases: Sampler

Wraps another sampler to yield a mini-batch of indices which all belong to the same volume.

This can mean that some batches have less samples then the requested batch size.

Based on Pytorch 1.5.1 BatchSampler: https://pytorch.org/docs/1.5.1/_modules/torch/utils/data/sampler.html#BatchSampler

__init__(sampler, batch_size)[source]#
class direct.data.samplers.ConcatDatasetBatchSampler(datasets, batch_size, seed=None)[source]#

Bases: Sampler

This sampler takes a ConcatDataset and samples complete batches of one of the underlying datasets randomly based on the total size of the dataset.

Based on Pytorch 1.5.1 BatchSampler: https://pytorch.org/docs/1.5.1/_modules/torch/utils/data/sampler.html#BatchSampler

__init__(datasets, batch_size, seed=None)[source]#
batch_sampler(sampler, sampler_offset)[source]#
static cumsum(sequence)[source]#

direct.data.sens module#

direct.data.sens.simulate_sensitivity_maps(shape, num_coils, var=1, seed=None)[source]#

Simulates coil sensitivities using bi-variate or tri-variate gaussian distribution.

Parameters:
  • shape (Union[List[int], Tuple[int]]) – Spatial shape (nx, ny) or (nx, ny, nz).

  • num_coils (int) – Number of coils to be simulated.

  • var (float) – Variance. Default: 1.

  • seed (Optional[int]) – If not None, a seed will be used to produce an offset for the gaussian mean \(\mu\). Default: None.

Return type:

ndarray

Returns:

Simulated coil sensitivity maps of shape (num_coils, *shape).

Note

Sensitivity maps are normalized such that:

\[\sum_{k=1}^{n_c} {S^{k}}^{*}S^{k} = I.\]

direct.data.transforms module#

Direct transforms module.

This module contains functions for complex-valued data manipulation in PyTorch. This includes functions for complex multiplication, division, modulus, fft, ifft, fftshift, ifftshift, and more. The functions are designed to work with complex-valued data where the last axis denotes the real and imaginary parts respectively. The functions are designed to work with complex-valued data where the last axis denotes the real and imaginary parts respectively.

direct.data.transforms.to_tensor(data)[source]#

Convert numpy array to PyTorch tensor.

Complex arrays will have real and imaginary parts on the last axis.

Parameters:

data (ndarray) – Input numpy array.

Return type:

Tensor

Returns:

PyTorch tensor.

direct.data.transforms.verify_fft_dtype_possible(data, dims)[source]#

fft and ifft can only be performed on GPU in float16 if the shapes are powers of 2.

This function verifies if this is the case.

Parameters:
  • data (Tensor) – Input tensor.

  • dims (tuple[int, int] | tuple[int, int, int]) – Tuple of two or three ints.

Return type:

bool

Returns:

True if FFT can be performed on the data.

direct.data.transforms.view_as_complex(data)[source]#

Returns a view of input as a complex tensor.

For an input tensor of size (N, ..., 2) where the last dimension of size 2 represents the real and imaginary components of complex numbers, this function returns a new complex tensor of size (N, ...).

Parameters:

data – Input data with torch.dtype torch.float64 and torch.float32 with complex axis (last) of dimension 2 and of shape (N, *, 2).

Returns:

Output complex-valued data of shape (N, *) with complex torch.dtype.

direct.data.transforms.view_as_real(data)[source]#

Returns a view of data as a real tensor.

For an input complex tensor of size (N, ...) this function returns a new real tensor of size (N, ..., 2) where the last dimension of size 2 represents the real and imaginary components of complex numbers.

Parameters:

data – Input data with complex torch.dtype of shape (N, *).

Returns:

Output real-valued data of shape (N, *, 2).

direct.data.transforms.fft2(data, dim=(1, 2), centered=True, normalized=True, complex_input=True)[source]#

Apply centered two-dimensional Inverse Fast Fourier Transform.

Can be performed in half precision when input shapes are powers of two. Version for PyTorch >= 1.7.0.

Parameters:
  • data (Tensor) – Complex-valued input tensor. Should be of shape (*, 2) and dim is in *.

  • dim (tuple[int, int]) – Dimensions over which to compute. Should be positive. Negative indexing not supported. Default: (1, 2), corresponding to ('height', 'width').

  • centered (bool) – Whether to apply a centered fft (center of kspace is in the center versus in the corners). For FastMRI dataset this has to be True and for the Calgary-Campinas dataset False. Default: True.

  • normalized (bool) – Whether to normalize the fft. For the FastMRI this has to be True and for the Calgary-Campinas dataset False. Default: True.

  • complex_input (bool) – True if input is complex [real-valued] tensor (complex dim = 2). False if complex-valued tensor is inputted. Default: True.

Return type:

Tensor

Returns:

The Fast Fourier transform of the data.

direct.data.transforms.ifft2(data, dim=(1, 2), centered=True, normalized=True, complex_input=True)[source]#

Apply centered two-dimensional Inverse Fast Fourier Transform.

Can be performed in half precision when input shapes are powers of two. Version for PyTorch >= 1.7.0.

Parameters:
  • data (Tensor) – Complex-valued input tensor. Should be of shape (*, 2) and dim is in *.

  • dim (tuple[int, int]) – Dimensions over which to compute. Should be positive. Negative indexing not supported. Default: (1, 2), corresponding to ('height', 'width').

  • centered (bool) – Whether to apply a centered ifft (center of kspace is in the center versus in the corners). For FastMRI dataset this has to be True and for the Calgary-Campinas dataset False. Default: True.

  • normalized (bool) – Whether to normalize the ifft. For the FastMRI this has to be True and for the Calgary-Campinas dataset False. Default: True.

  • complex_input (bool) – True if input is complex [real-valued] tensor (complex dim = 2). False if complex-valued tensor is inputted. Default: True.

Return type:

Tensor

Returns:

The Inverse Fast Fourier transform of the data.

direct.data.transforms.safe_divide(input_tensor, other_tensor)[source]#

Divide input_tensor and other_tensor safely, set the output to zero where the divisor is zero.

Parameters:
  • input_tensor (Tensor) – Numerator tensor.

  • other_tensor (Tensor) – Denominator tensor.

Return type:

Tensor

Returns:

The division result.

direct.data.transforms.modulus(data, complex_axis=-1)[source]#

Compute modulus of complex input data.

Assumes there is a complex axis (of dimension 2) in the data.

Parameters:
  • data (Tensor) – Input tensor.

  • complex_axis (int) – Complex dimension along which the modulus will be calculated. Default: -1.

Return type:

Tensor

Returns:

Modulus of data.

direct.data.transforms.modulus_if_complex(data, complex_axis=-1)[source]#

Compute modulus if complex tensor (has complex axis).

Parameters:
  • data (Tensor) – Input tensor.

  • complex_axis – Complex dimension along which the modulus will be calculated if that dimension is complex. Default: -1.

Return type:

Tensor

Returns:

Modulus if complex, otherwise the original data.

direct.data.transforms.roll_one_dim(data, shift, dim)[source]#

Similar to roll but only for one dim

Parameters:
  • data (Tensor) – Input tensor.

  • shift (int) – Shift amount.

  • dim (int) – Dimension along which to roll.

Return type:

Tensor

Returns:

Rolled tensor.

direct.data.transforms.roll(data, shift, dim)[source]#

Similar to numpy roll but applies to pytorch tensors.

Parameters:
  • data (Tensor) – Input tensor.

  • shift (list[int]) – Shift amounts.

  • dim (Union[list[int], tuple[int, ...]]) – Dimensions along which to roll.

Return type:

Tensor

Returns:

Rolled version of data.

direct.data.transforms.fftshift(data, dim=None)[source]#

Similar to numpy fftshift but applies to pytorch tensors.

Parameters:
  • data (Tensor) – Input data.

  • dim (Union[list[int], tuple[int, ...], None]) – Dimensions to shift. Default: None.

Return type:

Tensor

Returns:

Shifted tensor.

direct.data.transforms.ifftshift(data, dim=None)[source]#

Similar to numpy ifftshift but applies to pytorch tensors.

Parameters:
  • data (Tensor) – Input data.

  • dim (Union[list[int], tuple[int, ...], None]) – Dimensions to shift. Default: None.

Return type:

Tensor

Returns:

Shifted tensor.

direct.data.transforms.complex_multiplication(input_tensor, other_tensor)[source]#

Multiplies two complex-valued tensors. Assumes input tensors are complex (last axis has dimension 2).

Parameters:
  • input_tensor (Tensor) – First complex-valued input tensor.

  • other_tensor (Tensor) – Second complex-valued input tensor.

Return type:

Tensor

Returns:

Complex multiplication result.

direct.data.transforms.complex_dot_product(a, b, dim)[source]#

Computes the dot product of the complex tensors \(a\) and \(b\).

Computes \(a^{*}b = <a, b>\).

Parameters:
  • a (Tensor) – First complex tensor.

  • b (Tensor) – Second complex tensor.

  • dim (list[int]) – Dimensions which will be suppressed. Useful when inputs are batched.

Return type:

Tensor

Returns:

Dot product of \(a\) and \(b\).

direct.data.transforms.complex_division(input_tensor, other_tensor)[source]#

Divides two complex-valued tensors.

Assumes input tensors are complex (last axis has dimension 2).

Parameters:
  • input_tensor (Tensor) – First complex-valued input tensor.

  • other_tensor (Tensor) – Second complex-valued input tensor.

Return type:

Tensor

Returns:

Complex multiplication result.

direct.data.transforms.complex_mm(input_tensor, other_tensor)[source]#

Performs a matrix multiplication of the 2D complex matrices input_tensor and other_tensor. If input_tensor is a (n×m) tensor, other_tensor is a (m×p) tensor, out will be a (n×p) tensor.

Parameters:
  • input_tensor (Tensor) – Input 2D tensor.

  • other_tensor (Tensor) – Other 2D tensor.

Return type:

Tensor

Returns:

Complex-multiplied 2D output tensor.

direct.data.transforms.complex_bmm(input_tensor, other_tensor)[source]#

Complex batch multiplication.

Parameters:
  • input_tensor (Tensor) – Input tensor.

  • other_tensor (Tensor) – Other tensor.

Return type:

Tensor

Returns:

Batch complex-multiplied output tensor.

direct.data.transforms.conjugate(data)[source]#

Compute the complex conjugate of a torch tensor.

The last axis denotes the real and complex part (last axis has dimension 2).

Parameters:

data (Tensor) – Input tensor.

Return type:

Tensor

Returns:

Complex conjugate tensor.

direct.data.transforms.apply_padding(data, padding)[source]#

Applies zero padding to data.

Parameters:
  • data (Tensor) – Batched or not input to be padded of shape (batch, *, height, width, *).

  • padding (Optional[Tensor]) – Binary tensor of shape (batch, 1, height, width, 1). Entries in padding with non-zero value point to samples in data that will be zero-padded. If None, data will be returned.

Return type:

Tensor

Returns:

Padded data.

direct.data.transforms.apply_mask(kspace, mask_func, seed=None, return_mask=True)[source]#

Subsample kspace by setting kspace to zero as given by a binary mask.

Parameters:
  • kspace (Tensor) – k-space as a complex-valued tensor.

  • mask_func (Union[Callable, Tensor]) – Masking function, taking a shape and returning a mask with this shape or can be broadcast as such. Can also be a sampling mask.

  • seed (Optional[int]) – Seed for the random number generator. Default: None.

  • return_mask (bool) – If True, mask will be returned. Default: True.

Return type:

Union[tuple[Tensor, Tensor], Tensor]

Returns:

Tuple of masked data and mask if return_mask is True, otherwise just masked data.

direct.data.transforms.tensor_to_complex_numpy(data)[source]#

Converts a complex pytorch tensor to a complex numpy array.

The last axis denote the real and imaginary parts respectively.

Parameters:

data (Tensor) – Input data.

Return type:

ndarray

Returns:

Complex valued numpy array.

direct.data.transforms.root_sum_of_squares(data, dim=0, complex_dim=-1)[source]#

Compute the root sum of squares (RSS) transform along a given dimension of the input tensor.

\[x_{\textrm{RSS}} = \sqrt{\sum_{i \in \textrm{coil}} |x_i|^2}\]
Parameters:
  • data (Tensor) – Input tensor.

  • dim (int) – Coil dimension. Default: 0 as the first dimension is always the coil dimension.

  • complex_dim (int) – Complex channel dimension. Default: -1. If data not complex this is ignored.

Return type:

Tensor

Returns:

RSS of the input tensor.

direct.data.transforms.center_crop(data, shape)[source]#

Apply a center crop along the last two dimensions.

Parameters:
  • data (Tensor) – Input tensor.

  • shape (Union[list[int], tuple[int, ...]]) – The output shape, should be smaller than the corresponding data dimensions.

Return type:

Tensor

Returns:

The center cropped data.

direct.data.transforms.complex_center_crop(data_list, crop_shape, offset=1, contiguous=False)[source]#

Apply a center crop to the input data, or to a list of complex images.

Parameters:
  • data_list (Union[list[Tensor], Tensor]) – The complex input tensor to be center cropped. It should have at least 3 dimensions and the cropping is applied along dimensions didx and didx+1 and the last dimensions should have a size of 2.

  • crop_shape (Union[list[int], tuple[int, ...]]) – The output shape. The shape should be smaller than the corresponding dimensions of data. If one value is None, this is filled in by the image shape.

  • offset (int) – Starting dimension for cropping. Default: 1.

  • contiguous (bool) – Return as a contiguous array. Useful for fast reshaping or viewing. Default: False.

Return type:

Union[list[Tensor], Tensor]

Returns:

The center cropped input_image(s).

direct.data.transforms.complex_random_crop(data_list, crop_shape, offset=1, contiguous=False, sampler='uniform', sigma=None, seed=None)[source]#

Apply a random crop to the input data tensor or a list of complex.

Parameters:
  • data_list (Union[list[Tensor], Tensor]) – The complex input tensor to be center cropped. It should have at least 3 dimensions and the cropping is applied along dimensions -3 and -2 and the last dimensions should have a size of 2.

  • crop_shape (Union[list[int], tuple[int, ...]]) – The output shape. The shape should be smaller than the corresponding dimensions of data.

  • offset (int) – Starting dimension for cropping. Default: 1.

  • contiguous (bool) – Return as a contiguous array. Useful for fast reshaping or viewing. Default: False.

  • sampler (str) – Select the random indices from either a "uniform" or "gaussian" distribution (around the center). Default: "uniform".

  • sigma (Union[float, list[float], None]) – Standard variance of the gaussian when sampler is "gaussian". If not set will take 1/3th of image shape. Default: None.

  • seed (Union[None, int, Buffer, _SupportsArray[dtype[Any]], _NestedSequence[_SupportsArray[dtype[Any]]], bool, float, complex, str, bytes, _NestedSequence[Union[bool, int, float, complex, str, bytes]]]) – Random seed. Default: None.

Return type:

Union[list[Tensor], Tensor]

Returns:

The center cropped input tensor or list of tensors.

direct.data.transforms.crop_to_acs(acs_mask, kspace)[source]#

Crops k-space to autocalibration region given the acs_mask.

Parameters:
  • acs_mask (Tensor) – Autocalibration mask of shape (height, width).

  • kspace (Tensor) – K-space of shape (coil, height, width, *).

Return type:

Tensor

Returns:

Cropped k-space of shape (coil, height', width', *), where height' and width' are the new dimensions derived from the acs_mask.

direct.data.transforms.reduce_operator(coil_data, sensitivity_map, dim=0)[source]#

Given zero-filled reconstructions from multiple coils and coil sensitivity maps it returns combined image.

Given zero-filled reconstructions from multiple coils \(\{x_i\}_{i=1}^{N_c}\) and coil sensitivity maps \(\{S_i\}_{i=1}^{N_c}\) it returns:

\[R(x_{1}, .., x_{N_c}, S_1, .., S_{N_c}) = \sum_{i=1}^{N_c} {S_i}^{*} \times x_i.\]

Adapted from [3].

Parameters:
  • coil_data (Tensor) – Zero-filled reconstructions from coils. Should be a complex tensor (with complex dim of size 2).

  • sensitivity_map (Tensor) – Coil sensitivity maps. Should be complex tensor (with complex dim of size 2).

  • dim (int) – Coil dimension. Default: 0.

Return type:

Tensor

Returns:

Combined individual coil images.

References

direct.data.transforms.expand_operator(data, sensitivity_map, dim=0)[source]#

Given a reconstructed image and coil sensitivity maps, returns zero-filled reconstructions from each coil.

Given a reconstructed image \(x\) and coil sensitivity maps \(\{S_i\}_{i=1}^{N_c}\), it returns

\[E(x) = (S_1 \times x, .., S_{N_c} \times x) = (x_1, .., x_{N_c}).\]

Adapted from [4].

Parameters:
  • data (Tensor) – Image data. Should be a complex tensor (with complex dim of size 2).

  • sensitivity_map (Tensor) – Coil sensitivity maps. Should be complex tensor (with complex dim of size 2).

  • dim (int) – Coil dimension. Default: 0.

Return type:

Tensor

Returns:

Zero-filled reconstructions from each coil.

References

direct.data.transforms.complex_image_resize(complex_image, resize_shape, mode='nearest')[source]#

Resize a complex tensor to a new size.

Parameters:
  • complex_image (Tensor) – Complex image tensor with shape (B, C, [D], [H,] W, 2) representing real and imaginary parts.

  • resize_shape (Union[tuple[int, int], list[int]]) – Shape to resize image to.

  • mode (str) – Algorithm used for upsampling: "nearest" | "linear" | "bilinear" | "bicubic" | "trilinear" | "area" | "nearest-exact". Default: "nearest".

Return type:

Tensor

Returns:

Resized complex image tensor with shape (B, C, [new_depth,] [new_height,] new_width, 2).

direct.data.transforms.pad_tensor(input_image, target_shape, value=0)[source]#

Pads an input image tensor to a desired shape.

Parameters:
  • input_image (Tensor) – The input image tensor of shape (..., x, y) or (..., z, x, y).

  • target_shape (tuple[int, int]) – The desired shape (X, Y) or (Z, X, Y) for the padded image.

  • value (float) – Padding value. Default: 0.

Return type:

Tensor

Returns:

The padded image tensor.

Module contents#

DIRECT data module.