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][source]#

Extract bbox from images, coordinates can be negative.

Parameters:
data: np.ndarray or torch.Tensor

nD array or torch tensor.

bbox: list or tuple

bbox 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: number

if bounding box would be out of the image, this is value the patch will be padded with.

Returns:
out: np.ndarray or torch.Tensor

Numpy array or torch tensor of data cropped to BoundingBox

Return type:

Union[ndarray, Tensor]

direct.data.bbox.crop_to_largest(data, pad_value=0)[source][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[np.ndarray, torch.Tensor]]
pad_value: int
Returns:
List[Union[np.ndarray, torch.Tensor]]
Return type:

List[Union[ndarray, Tensor]]

direct.data.datasets module#

DIRECT datasets module.

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][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_rootpathlib.Path

Root directory to data.

transformCallable, optional

A list of transforms to be applied on the generated samples. Default is None.

filenames_filterlist[PathOrString], optional

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_listslist[PathOrString], optional

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_rootPathOrString, optional

Root of filenames_lists. Ignored if filename_lists is None. Default: None.

kspace_keystr

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: tuple of strings, optional

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: str

Description of dataset, can be useful for logging.

compute_maskbool

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_contextstr, optional

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

NUM_ACS_LINES = 24#
VALID_CHALLENGE_ACCELERATIONS = {'mask04', 'mask08', 'mask10'}#
get_slice_data(filename, slice_no, key, extra_keys=None)[source][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:
filenamePathOrString

Path to the mat file.

slice_noint

Slice number (corresponding to dataset index) to retrieve.

keystr

Key to load the data from the mat file.

extra_keys_type_, optional

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

Returns:
tuple[np.ndarray, Any]

The retrieved data and the extra data.

Return type:

tuple[ndarray, Any]

parse_filenames_data(filenames, extra_mats=None)[source][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:
filenameslist[pathlib.Path]

List of filenames to parse.

extra_matstuple[str], optional

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][source]#

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

Parameters:
filenamepathlib.Path

Path to the mat file.

extra_matstuple[str]

Tuple of keys of the extra mats to verify.

Return type:

None

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][source]#

Bases: H5SliceData

Calgary-Campinas challenge dataset.

class direct.data.datasets.ConcatDataset(datasets)[source][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: sequence

List of datasets to be concatenated

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

list[int]

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][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: list or tuple of ints.

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: int

Seed. Default is None.

filenames: List of strings or string.

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: bool

Pass the attributes of the generated sample.

text_description: str

Description of dataset, can be useful for logging.

kspace_context: bool

If true corresponds to 3D reconstruction, else reconstruction is 2D.

parse_filenames_data(filenames)[source][source]#
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][source]#

Bases: H5SliceData

FastMRI challenge dataset.

Parameters:
data_rootpathlib.Path

Root directory to data.

transformCallable, optional

A list of transforms to be applied on the generated samples. Default is None.

filenames_filterlist[PathOrString], optional

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_listslist[PathOrString], optional

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_rootPathOrString, optional

Root of filenames_lists. Ignored if filename_lists is None. Default: None.

regex_filter: str

Regular expression filter on the absolute filename. Will be applied after any filenames filter.

pass_maskbool

If True this will load in the sample a sampling mask saved in the h5 file. Default: False.

pass_maxbool

If True this will load the maximum k-space magnitude value saved in the h5 file.

initial_images
initial_images_key
noise_data
pass_h5s: 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 first instance be convenient when you want to pass sensitivity maps as well. So 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 filename.h5. kwargs : dict

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

ndarray

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][source]#

Bases: Dataset

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

Notes

This dataset reconstructs into a single volume.

References

[1]

Gach, H. Michael, Costin Tanase, and Fernando Boada. “2D & 3D Shepp-Logan phantom standards for MRI.” 2008 19th International Conference on Systems Engineering. IEEE, 2008.

DEFAULT_NUM_ELLIPSOIDS: int = 15#
ELLIPSOID_NUM_PARAMS: int = 13#
GYROMAGNETIC_RATIO: float = 267.52219#
IMAGE_INTENSITIES: list[str] = ['PROTON', 'T1', 'T2']#
static default_mr_ellipsoid_parameters()[source][source]#

Returns default parameters of ellipsoids as in [1].

Returns:
ellipsoidsnp.ndarray

Array containing the parameters for the ellipsoids used to construct the phantom. Each row of the form [x, y, z, a, b, c, heta, 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 * heta: 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 imes B_0^{C} * T2: denotes the T2 value * chi: denotes the chi value

Return type:

ndarray

References

[1]

Gach, H. Michael, Costin Tanase, and Fernando Boada. “2D & 3D Shepp-Logan phantom standards for MRI.” 2008 19th International Conference on Systems Engineering. IEEE, 2008.

static fft(x)[source][source]#
sample_image(idx)[source][source]#
Return type:

ndarray

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][source]#

Bases: SheppLoganDataset

Creates an instance of SheppLoganDataset with PROTON intensity.

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][source]#

Bases: SheppLoganDataset

Creates an instance of SheppLoganDataset with T1 intensity.

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][source]#

Bases: SheppLoganDataset

Creates an instance of SheppLoganDataset with T2 intensity.

direct.data.datasets.build_dataset_from_input(transforms, dataset_config, **kwargs)[source][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: object, Callable

Transformation object.

dataset_config: DictConfig

Dataset configuration file.

kwargs: dict[str, Any]
Can include:
  • initial_images: list[pathlib.Path]

    Path to initial_images.

  • initial_kspaces: pathlib.Path

    Path to initial kspace images.

  • filenames_filter: Optional[list[PathOrString]]

    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.

  • data_root: pathlib.Path or str

    Root path to the data for the dataset class.

  • pass_dictionaries: Optional[dict[str, dict]]

Returns:
Dataset
Return type:

Dataset

direct.data.datasets_config module#

Classes holding the typed configurations for the datasets.

class direct.data.datasets_config.AugmentationTransformConfig(rescale: 'Optional[tuple[int, ...]]' = None, rescale_mode: 'Optional[RescaleMode]' = <RescaleMode.NEAREST: 'nearest'>, rescale_2d_if_3d: 'Optional[bool]' = False, pad: 'Optional[tuple[int, ...]]' = None)[source][source]#

Bases: BaseConfig

pad: Optional[tuple[int, ...]] = None#
rescale: Optional[tuple[int, ...]] = None#
rescale_2d_if_3d: Optional[bool] = False#
rescale_mode: Optional[RescaleMode] = 'nearest'#
class direct.data.datasets_config.CMRxReconConfig(name: 'str' = '???', transforms: 'BaseConfig' = TransformsConfig(masking=MaskingConfig(name='???', accelerations=(5.0, ), center_fractions=(0.1, ), uniform_range=False, mode=<MaskFuncMode.STATIC: 'static'>, val_accelerations=(5.0, 10.0), val_center_fractions=(0.1, 0.05)), cropping=CropTransformConfig(crop=None, crop_type='uniform', image_center_crop=False), augmentation=AugmentationTransformConfig(rescale=None, rescale_mode=<RescaleMode.NEAREST: 'nearest'>, rescale_2d_if_3d=False, pad=None), random_augmentations=RandomAugmentationTransformsConfig(random_rotation_degrees=(-90, 90), random_rotation_probability=0.0, random_flip_type=<RandomFlipType.RANDOM: 'random'>, random_flip_probability=0.0, random_reverse_probability=0.0), padding_eps=0.001, estimate_body_coil_image=False, sensitivity_map_estimation=SensitivityMapEstimationTransformConfig(estimate_sensitivity_maps=True, sensitivity_maps_type=<SensitivityMapType.RSS_ESTIMATE: '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), normalization=NormalizationTransformConfig(scaling_key='masked_kspace', scale_percentile=0.99), delete_acs_mask=True, delete_kspace=True, image_recon_type=<ReconstructionType.RSS: 'rss'>, compress_coils=None, pad_coils=None, use_seed=True, transforms_type=<TransformsType.SUPERVISED: 'supervised'>, mask_split_ratio=(0.4, ), mask_split_acs_region=(0, 0), mask_split_keep_acs=False, mask_split_type=<MaskSplitterType.GAUSSIAN: 'gaussian'>, mask_split_gaussian_std=3.0, mask_split_half_direction=<HalfSplitType.VERTICAL: 'vertical'>), text_description: 'Optional[str]' = None, regex_filter: 'Optional[str]' = None, data_root: 'Optional[str]' = None, filenames_filter: 'Optional[list[str]]' = None, filenames_lists: 'Optional[list[str]]' = None, filenames_lists_root: 'Optional[str]' = None, kspace_key: 'str' = 'kspace_full', compute_mask: 'bool' = False, extra_keys: 'Optional[list[str]]' = None, kspace_context: 'Optional[str]' = None)[source][source]#

Bases: DatasetConfig

compute_mask: bool = False#
data_root: Optional[str] = None#
extra_keys: Optional[list[str]] = None#
filenames_filter: Optional[list[str]] = None#
filenames_lists: Optional[list[str]] = None#
filenames_lists_root: Optional[str] = None#
kspace_context: Optional[str] = None#
kspace_key: str = 'kspace_full'#
regex_filter: Optional[str] = None#
class direct.data.datasets_config.CalgaryCampinasConfig(name: 'str' = '???', transforms: 'BaseConfig' = TransformsConfig(masking=MaskingConfig(name='???', accelerations=(5.0, ), center_fractions=(0.1, ), uniform_range=False, mode=<MaskFuncMode.STATIC: 'static'>, val_accelerations=(5.0, 10.0), val_center_fractions=(0.1, 0.05)), cropping=CropTransformConfig(crop=None, crop_type='uniform', image_center_crop=False), augmentation=AugmentationTransformConfig(rescale=None, rescale_mode=<RescaleMode.NEAREST: 'nearest'>, rescale_2d_if_3d=False, pad=None), random_augmentations=RandomAugmentationTransformsConfig(random_rotation_degrees=(-90, 90), random_rotation_probability=0.0, random_flip_type=<RandomFlipType.RANDOM: 'random'>, random_flip_probability=0.0, random_reverse_probability=0.0), padding_eps=0.001, estimate_body_coil_image=False, sensitivity_map_estimation=SensitivityMapEstimationTransformConfig(estimate_sensitivity_maps=True, sensitivity_maps_type=<SensitivityMapType.RSS_ESTIMATE: '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), normalization=NormalizationTransformConfig(scaling_key='masked_kspace', scale_percentile=0.99), delete_acs_mask=True, delete_kspace=True, image_recon_type=<ReconstructionType.RSS: 'rss'>, compress_coils=None, pad_coils=None, use_seed=True, transforms_type=<TransformsType.SUPERVISED: 'supervised'>, mask_split_ratio=(0.4, ), mask_split_acs_region=(0, 0), mask_split_keep_acs=False, mask_split_type=<MaskSplitterType.GAUSSIAN: 'gaussian'>, mask_split_gaussian_std=3.0, mask_split_half_direction=<HalfSplitType.VERTICAL: 'vertical'>), text_description: 'Optional[str]' = None, regex_filter: 'Optional[str]' = None, input_kspace_key: 'Optional[str]' = None, input_image_key: 'Optional[str]' = None, kspace_context: 'int' = 0, pass_mask: 'bool' = False, data_root: 'Optional[str]' = None, filenames_filter: 'Optional[list[str]]' = None, filenames_lists: 'Optional[list[str]]' = None, filenames_lists_root: 'Optional[str]' = None, crop_outer_slices: 'bool' = False)[source][source]#

Bases: H5SliceConfig

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

Bases: BaseConfig

crop: Optional[str] = None#
crop_type: Optional[str] = 'uniform'#
image_center_crop: bool = False#
class direct.data.datasets_config.DatasetConfig(name: 'str' = '???', transforms: 'BaseConfig' = TransformsConfig(masking=MaskingConfig(name='???', accelerations=(5.0, ), center_fractions=(0.1, ), uniform_range=False, mode=<MaskFuncMode.STATIC: 'static'>, val_accelerations=(5.0, 10.0), val_center_fractions=(0.1, 0.05)), cropping=CropTransformConfig(crop=None, crop_type='uniform', image_center_crop=False), augmentation=AugmentationTransformConfig(rescale=None, rescale_mode=<RescaleMode.NEAREST: 'nearest'>, rescale_2d_if_3d=False, pad=None), random_augmentations=RandomAugmentationTransformsConfig(random_rotation_degrees=(-90, 90), random_rotation_probability=0.0, random_flip_type=<RandomFlipType.RANDOM: 'random'>, random_flip_probability=0.0, random_reverse_probability=0.0), padding_eps=0.001, estimate_body_coil_image=False, sensitivity_map_estimation=SensitivityMapEstimationTransformConfig(estimate_sensitivity_maps=True, sensitivity_maps_type=<SensitivityMapType.RSS_ESTIMATE: '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), normalization=NormalizationTransformConfig(scaling_key='masked_kspace', scale_percentile=0.99), delete_acs_mask=True, delete_kspace=True, image_recon_type=<ReconstructionType.RSS: 'rss'>, compress_coils=None, pad_coils=None, use_seed=True, transforms_type=<TransformsType.SUPERVISED: 'supervised'>, mask_split_ratio=(0.4, ), mask_split_acs_region=(0, 0), mask_split_keep_acs=False, mask_split_type=<MaskSplitterType.GAUSSIAN: 'gaussian'>, mask_split_gaussian_std=3.0, mask_split_half_direction=<HalfSplitType.VERTICAL: 'vertical'>), text_description: 'Optional[str]' = None)[source][source]#

Bases: BaseConfig

name: str = '???'#
text_description: Optional[str] = None#
transforms: BaseConfig = TransformsConfig(masking=MaskingConfig(name='???', accelerations=(5.0,), center_fractions=(0.1,), uniform_range=False, mode=<MaskFuncMode.STATIC: 'static'>, val_accelerations=(5.0, 10.0), val_center_fractions=(0.1, 0.05)), cropping=CropTransformConfig(crop=None, crop_type='uniform', image_center_crop=False), augmentation=AugmentationTransformConfig(rescale=None, rescale_mode=<RescaleMode.NEAREST: 'nearest'>, rescale_2d_if_3d=False, pad=None), random_augmentations=RandomAugmentationTransformsConfig(random_rotation_degrees=(-90, 90), random_rotation_probability=0.0, random_flip_type=<RandomFlipType.RANDOM: 'random'>, random_flip_probability=0.0, random_reverse_probability=0.0), padding_eps=0.001, estimate_body_coil_image=False, sensitivity_map_estimation=SensitivityMapEstimationTransformConfig(estimate_sensitivity_maps=True, sensitivity_maps_type=<SensitivityMapType.RSS_ESTIMATE: '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), normalization=NormalizationTransformConfig(scaling_key='masked_kspace', scale_percentile=0.99), delete_acs_mask=True, delete_kspace=True, image_recon_type=<ReconstructionType.RSS: 'rss'>, compress_coils=None, pad_coils=None, use_seed=True, transforms_type=<TransformsType.SUPERVISED: 'supervised'>, mask_split_ratio=(0.4,), mask_split_acs_region=(0, 0), mask_split_keep_acs=False, mask_split_type=<MaskSplitterType.GAUSSIAN: 'gaussian'>, mask_split_gaussian_std=3.0, mask_split_half_direction=<HalfSplitType.VERTICAL: 'vertical'>)#
class direct.data.datasets_config.FakeMRIBlobsConfig(name: 'str' = '???', transforms: 'BaseConfig' = TransformsConfig(masking=MaskingConfig(name='???', accelerations=(5.0, ), center_fractions=(0.1, ), uniform_range=False, mode=<MaskFuncMode.STATIC: 'static'>, val_accelerations=(5.0, 10.0), val_center_fractions=(0.1, 0.05)), cropping=CropTransformConfig(crop=None, crop_type='uniform', image_center_crop=False), augmentation=AugmentationTransformConfig(rescale=None, rescale_mode=<RescaleMode.NEAREST: 'nearest'>, rescale_2d_if_3d=False, pad=None), random_augmentations=RandomAugmentationTransformsConfig(random_rotation_degrees=(-90, 90), random_rotation_probability=0.0, random_flip_type=<RandomFlipType.RANDOM: 'random'>, random_flip_probability=0.0, random_reverse_probability=0.0), padding_eps=0.001, estimate_body_coil_image=False, sensitivity_map_estimation=SensitivityMapEstimationTransformConfig(estimate_sensitivity_maps=True, sensitivity_maps_type=<SensitivityMapType.RSS_ESTIMATE: '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), normalization=NormalizationTransformConfig(scaling_key='masked_kspace', scale_percentile=0.99), delete_acs_mask=True, delete_kspace=True, image_recon_type=<ReconstructionType.RSS: 'rss'>, compress_coils=None, pad_coils=None, use_seed=True, transforms_type=<TransformsType.SUPERVISED: 'supervised'>, mask_split_ratio=(0.4, ), mask_split_acs_region=(0, 0), mask_split_keep_acs=False, mask_split_type=<MaskSplitterType.GAUSSIAN: 'gaussian'>, mask_split_gaussian_std=3.0, mask_split_half_direction=<HalfSplitType.VERTICAL: 'vertical'>), text_description: 'Optional[str]' = None, pass_attrs: 'bool' = True)[source][source]#

Bases: DatasetConfig

pass_attrs: bool = True#
class direct.data.datasets_config.FastMRIConfig(name: 'str' = '???', transforms: 'BaseConfig' = TransformsConfig(masking=MaskingConfig(name='???', accelerations=(5.0, ), center_fractions=(0.1, ), uniform_range=False, mode=<MaskFuncMode.STATIC: 'static'>, val_accelerations=(5.0, 10.0), val_center_fractions=(0.1, 0.05)), cropping=CropTransformConfig(crop=None, crop_type='uniform', image_center_crop=False), augmentation=AugmentationTransformConfig(rescale=None, rescale_mode=<RescaleMode.NEAREST: 'nearest'>, rescale_2d_if_3d=False, pad=None), random_augmentations=RandomAugmentationTransformsConfig(random_rotation_degrees=(-90, 90), random_rotation_probability=0.0, random_flip_type=<RandomFlipType.RANDOM: 'random'>, random_flip_probability=0.0, random_reverse_probability=0.0), padding_eps=0.001, estimate_body_coil_image=False, sensitivity_map_estimation=SensitivityMapEstimationTransformConfig(estimate_sensitivity_maps=True, sensitivity_maps_type=<SensitivityMapType.RSS_ESTIMATE: '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), normalization=NormalizationTransformConfig(scaling_key='masked_kspace', scale_percentile=0.99), delete_acs_mask=True, delete_kspace=True, image_recon_type=<ReconstructionType.RSS: 'rss'>, compress_coils=None, pad_coils=None, use_seed=True, transforms_type=<TransformsType.SUPERVISED: 'supervised'>, mask_split_ratio=(0.4, ), mask_split_acs_region=(0, 0), mask_split_keep_acs=False, mask_split_type=<MaskSplitterType.GAUSSIAN: 'gaussian'>, mask_split_gaussian_std=3.0, mask_split_half_direction=<HalfSplitType.VERTICAL: 'vertical'>), text_description: 'Optional[str]' = None, regex_filter: 'Optional[str]' = None, input_kspace_key: 'Optional[str]' = None, input_image_key: 'Optional[str]' = None, kspace_context: 'int' = 0, pass_mask: 'bool' = False, data_root: 'Optional[str]' = None, filenames_filter: 'Optional[list[str]]' = None, filenames_lists: 'Optional[list[str]]' = None, filenames_lists_root: 'Optional[str]' = None, pass_attrs: 'bool' = True)[source][source]#

Bases: H5SliceConfig

pass_attrs: bool = True#
class direct.data.datasets_config.H5SliceConfig(name: 'str' = '???', transforms: 'BaseConfig' = TransformsConfig(masking=MaskingConfig(name='???', accelerations=(5.0, ), center_fractions=(0.1, ), uniform_range=False, mode=<MaskFuncMode.STATIC: 'static'>, val_accelerations=(5.0, 10.0), val_center_fractions=(0.1, 0.05)), cropping=CropTransformConfig(crop=None, crop_type='uniform', image_center_crop=False), augmentation=AugmentationTransformConfig(rescale=None, rescale_mode=<RescaleMode.NEAREST: 'nearest'>, rescale_2d_if_3d=False, pad=None), random_augmentations=RandomAugmentationTransformsConfig(random_rotation_degrees=(-90, 90), random_rotation_probability=0.0, random_flip_type=<RandomFlipType.RANDOM: 'random'>, random_flip_probability=0.0, random_reverse_probability=0.0), padding_eps=0.001, estimate_body_coil_image=False, sensitivity_map_estimation=SensitivityMapEstimationTransformConfig(estimate_sensitivity_maps=True, sensitivity_maps_type=<SensitivityMapType.RSS_ESTIMATE: '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), normalization=NormalizationTransformConfig(scaling_key='masked_kspace', scale_percentile=0.99), delete_acs_mask=True, delete_kspace=True, image_recon_type=<ReconstructionType.RSS: 'rss'>, compress_coils=None, pad_coils=None, use_seed=True, transforms_type=<TransformsType.SUPERVISED: 'supervised'>, mask_split_ratio=(0.4, ), mask_split_acs_region=(0, 0), mask_split_keep_acs=False, mask_split_type=<MaskSplitterType.GAUSSIAN: 'gaussian'>, mask_split_gaussian_std=3.0, mask_split_half_direction=<HalfSplitType.VERTICAL: 'vertical'>), text_description: 'Optional[str]' = None, regex_filter: 'Optional[str]' = None, input_kspace_key: 'Optional[str]' = None, input_image_key: 'Optional[str]' = None, kspace_context: 'int' = 0, pass_mask: 'bool' = False, data_root: 'Optional[str]' = None, filenames_filter: 'Optional[list[str]]' = None, filenames_lists: 'Optional[list[str]]' = None, filenames_lists_root: 'Optional[str]' = None)[source][source]#

Bases: DatasetConfig

data_root: Optional[str] = None#
filenames_filter: Optional[list[str]] = None#
filenames_lists: Optional[list[str]] = None#
filenames_lists_root: Optional[str] = None#
input_image_key: Optional[str] = None#
input_kspace_key: Optional[str] = None#
kspace_context: int = 0#
pass_mask: bool = False#
regex_filter: Optional[str] = None#
class direct.data.datasets_config.NormalizationTransformConfig(scaling_key: 'Optional[str]' = 'masked_kspace', scale_percentile: 'Optional[float]' = 0.99)[source][source]#

Bases: BaseConfig

scale_percentile: Optional[float] = 0.99#
scaling_key: Optional[str] = 'masked_kspace'#
class direct.data.datasets_config.RandomAugmentationTransformsConfig(random_rotation_degrees: 'tuple[int, ...]' = (-90, 90), random_rotation_probability: 'float' = 0.0, random_flip_type: 'Optional[RandomFlipType]' = <RandomFlipType.RANDOM: 'random'>, random_flip_probability: 'float' = 0.0, random_reverse_probability: 'float' = 0.0)[source][source]#

Bases: BaseConfig

random_flip_probability: float = 0.0#
random_flip_type: Optional[RandomFlipType] = 'random'#
random_reverse_probability: float = 0.0#
random_rotation_degrees: tuple[int, ...] = (-90, 90)#
random_rotation_probability: float = 0.0#
class direct.data.datasets_config.SensitivityMapEstimationTransformConfig(estimate_sensitivity_maps: 'bool' = True, sensitivity_maps_type: 'SensitivityMapType' = <SensitivityMapType.RSS_ESTIMATE: 'rss_estimate'>, sensitivity_maps_espirit_threshold: 'Optional[float]' = 0.05, sensitivity_maps_espirit_kernel_size: 'Optional[int]' = 6, sensitivity_maps_espirit_crop: 'Optional[float]' = 0.95, sensitivity_maps_espirit_max_iters: 'Optional[int]' = 30, sensitivity_maps_gaussian: 'Optional[float]' = 0.7)[source][source]#

Bases: BaseConfig

estimate_sensitivity_maps: bool = True#
sensitivity_maps_espirit_crop: Optional[float] = 0.95#
sensitivity_maps_espirit_kernel_size: Optional[int] = 6#
sensitivity_maps_espirit_max_iters: Optional[int] = 30#
sensitivity_maps_espirit_threshold: Optional[float] = 0.05#
sensitivity_maps_gaussian: Optional[float] = 0.7#
sensitivity_maps_type: SensitivityMapType = 'rss_estimate'#
class direct.data.datasets_config.SheppLoganDatasetConfig(name: 'str' = '???', transforms: 'BaseConfig' = TransformsConfig(masking=MaskingConfig(name='???', accelerations=(5.0, ), center_fractions=(0.1, ), uniform_range=False, mode=<MaskFuncMode.STATIC: 'static'>, val_accelerations=(5.0, 10.0), val_center_fractions=(0.1, 0.05)), cropping=CropTransformConfig(crop=None, crop_type='uniform', image_center_crop=False), augmentation=AugmentationTransformConfig(rescale=None, rescale_mode=<RescaleMode.NEAREST: 'nearest'>, rescale_2d_if_3d=False, pad=None), random_augmentations=RandomAugmentationTransformsConfig(random_rotation_degrees=(-90, 90), random_rotation_probability=0.0, random_flip_type=<RandomFlipType.RANDOM: 'random'>, random_flip_probability=0.0, random_reverse_probability=0.0), padding_eps=0.001, estimate_body_coil_image=False, sensitivity_map_estimation=SensitivityMapEstimationTransformConfig(estimate_sensitivity_maps=True, sensitivity_maps_type=<SensitivityMapType.RSS_ESTIMATE: '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), normalization=NormalizationTransformConfig(scaling_key='masked_kspace', scale_percentile=0.99), delete_acs_mask=True, delete_kspace=True, image_recon_type=<ReconstructionType.RSS: 'rss'>, compress_coils=None, pad_coils=None, use_seed=True, transforms_type=<TransformsType.SUPERVISED: 'supervised'>, mask_split_ratio=(0.4, ), mask_split_acs_region=(0, 0), mask_split_keep_acs=False, mask_split_type=<MaskSplitterType.GAUSSIAN: 'gaussian'>, mask_split_gaussian_std=3.0, mask_split_half_direction=<HalfSplitType.VERTICAL: 'vertical'>), text_description: 'Optional[str]' = None, shape: 'tuple[int, int, int]' = (100, 100, 30), num_coils: 'int' = 12, seed: 'Optional[int]' = None, B0: 'float' = 3.0, zlimits: 'tuple[float, float]' = (-0.929, 0.929))[source][source]#

Bases: DatasetConfig

B0: float = 3.0#
num_coils: int = 12#
seed: Optional[int] = None#
shape: tuple[int, int, int] = (100, 100, 30)#
zlimits: tuple[float, float] = (-0.929, 0.929)#
class direct.data.datasets_config.SheppLoganProtonConfig(name: 'str' = '???', transforms: 'BaseConfig' = TransformsConfig(masking=MaskingConfig(name='???', accelerations=(5.0, ), center_fractions=(0.1, ), uniform_range=False, mode=<MaskFuncMode.STATIC: 'static'>, val_accelerations=(5.0, 10.0), val_center_fractions=(0.1, 0.05)), cropping=CropTransformConfig(crop=None, crop_type='uniform', image_center_crop=False), augmentation=AugmentationTransformConfig(rescale=None, rescale_mode=<RescaleMode.NEAREST: 'nearest'>, rescale_2d_if_3d=False, pad=None), random_augmentations=RandomAugmentationTransformsConfig(random_rotation_degrees=(-90, 90), random_rotation_probability=0.0, random_flip_type=<RandomFlipType.RANDOM: 'random'>, random_flip_probability=0.0, random_reverse_probability=0.0), padding_eps=0.001, estimate_body_coil_image=False, sensitivity_map_estimation=SensitivityMapEstimationTransformConfig(estimate_sensitivity_maps=True, sensitivity_maps_type=<SensitivityMapType.RSS_ESTIMATE: '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), normalization=NormalizationTransformConfig(scaling_key='masked_kspace', scale_percentile=0.99), delete_acs_mask=True, delete_kspace=True, image_recon_type=<ReconstructionType.RSS: 'rss'>, compress_coils=None, pad_coils=None, use_seed=True, transforms_type=<TransformsType.SUPERVISED: 'supervised'>, mask_split_ratio=(0.4, ), mask_split_acs_region=(0, 0), mask_split_keep_acs=False, mask_split_type=<MaskSplitterType.GAUSSIAN: 'gaussian'>, mask_split_gaussian_std=3.0, mask_split_half_direction=<HalfSplitType.VERTICAL: 'vertical'>), text_description: 'Optional[str]' = None, shape: 'tuple[int, int, int]' = (100, 100, 30), num_coils: 'int' = 12, seed: 'Optional[int]' = None, B0: 'float' = 3.0, zlimits: 'tuple[float, float]' = (-0.929, 0.929))[source][source]#

Bases: SheppLoganDatasetConfig

class direct.data.datasets_config.SheppLoganT1Config(name: 'str' = '???', transforms: 'BaseConfig' = TransformsConfig(masking=MaskingConfig(name='???', accelerations=(5.0, ), center_fractions=(0.1, ), uniform_range=False, mode=<MaskFuncMode.STATIC: 'static'>, val_accelerations=(5.0, 10.0), val_center_fractions=(0.1, 0.05)), cropping=CropTransformConfig(crop=None, crop_type='uniform', image_center_crop=False), augmentation=AugmentationTransformConfig(rescale=None, rescale_mode=<RescaleMode.NEAREST: 'nearest'>, rescale_2d_if_3d=False, pad=None), random_augmentations=RandomAugmentationTransformsConfig(random_rotation_degrees=(-90, 90), random_rotation_probability=0.0, random_flip_type=<RandomFlipType.RANDOM: 'random'>, random_flip_probability=0.0, random_reverse_probability=0.0), padding_eps=0.001, estimate_body_coil_image=False, sensitivity_map_estimation=SensitivityMapEstimationTransformConfig(estimate_sensitivity_maps=True, sensitivity_maps_type=<SensitivityMapType.RSS_ESTIMATE: '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), normalization=NormalizationTransformConfig(scaling_key='masked_kspace', scale_percentile=0.99), delete_acs_mask=True, delete_kspace=True, image_recon_type=<ReconstructionType.RSS: 'rss'>, compress_coils=None, pad_coils=None, use_seed=True, transforms_type=<TransformsType.SUPERVISED: 'supervised'>, mask_split_ratio=(0.4, ), mask_split_acs_region=(0, 0), mask_split_keep_acs=False, mask_split_type=<MaskSplitterType.GAUSSIAN: 'gaussian'>, mask_split_gaussian_std=3.0, mask_split_half_direction=<HalfSplitType.VERTICAL: 'vertical'>), text_description: 'Optional[str]' = None, shape: 'tuple[int, int, int]' = (100, 100, 30), num_coils: 'int' = 12, seed: 'Optional[int]' = None, B0: 'float' = 3.0, zlimits: 'tuple[float, float]' = (-0.929, 0.929))[source][source]#

Bases: SheppLoganDatasetConfig

class direct.data.datasets_config.SheppLoganT2Config(name: 'str' = '???', transforms: 'BaseConfig' = TransformsConfig(masking=MaskingConfig(name='???', accelerations=(5.0, ), center_fractions=(0.1, ), uniform_range=False, mode=<MaskFuncMode.STATIC: 'static'>, val_accelerations=(5.0, 10.0), val_center_fractions=(0.1, 0.05)), cropping=CropTransformConfig(crop=None, crop_type='uniform', image_center_crop=False), augmentation=AugmentationTransformConfig(rescale=None, rescale_mode=<RescaleMode.NEAREST: 'nearest'>, rescale_2d_if_3d=False, pad=None), random_augmentations=RandomAugmentationTransformsConfig(random_rotation_degrees=(-90, 90), random_rotation_probability=0.0, random_flip_type=<RandomFlipType.RANDOM: 'random'>, random_flip_probability=0.0, random_reverse_probability=0.0), padding_eps=0.001, estimate_body_coil_image=False, sensitivity_map_estimation=SensitivityMapEstimationTransformConfig(estimate_sensitivity_maps=True, sensitivity_maps_type=<SensitivityMapType.RSS_ESTIMATE: '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), normalization=NormalizationTransformConfig(scaling_key='masked_kspace', scale_percentile=0.99), delete_acs_mask=True, delete_kspace=True, image_recon_type=<ReconstructionType.RSS: 'rss'>, compress_coils=None, pad_coils=None, use_seed=True, transforms_type=<TransformsType.SUPERVISED: 'supervised'>, mask_split_ratio=(0.4, ), mask_split_acs_region=(0, 0), mask_split_keep_acs=False, mask_split_type=<MaskSplitterType.GAUSSIAN: 'gaussian'>, mask_split_gaussian_std=3.0, mask_split_half_direction=<HalfSplitType.VERTICAL: 'vertical'>), text_description: 'Optional[str]' = None, shape: 'tuple[int, int, int]' = (100, 100, 30), num_coils: 'int' = 12, seed: 'Optional[int]' = None, B0: 'float' = 3.0, zlimits: 'tuple[float, float]' = (-0.929, 0.929), T2_star: 'bool' = False)[source][source]#

Bases: SheppLoganDatasetConfig

T2_star: bool = False#
class direct.data.datasets_config.TransformsConfig(masking=MaskingConfig(name='???', accelerations=(5.0, ), center_fractions=(0.1, ), uniform_range=False, mode=<MaskFuncMode.STATIC: 'static'>, val_accelerations=(5.0, 10.0), val_center_fractions=(0.1, 0.05)), cropping=CropTransformConfig(crop=None, crop_type='uniform', image_center_crop=False), augmentation=AugmentationTransformConfig(rescale=None, rescale_mode=<RescaleMode.NEAREST: 'nearest'>, rescale_2d_if_3d=False, pad=None), random_augmentations=RandomAugmentationTransformsConfig(random_rotation_degrees=(-90, 90), random_rotation_probability=0.0, random_flip_type=<RandomFlipType.RANDOM: 'random'>, random_flip_probability=0.0, random_reverse_probability=0.0), padding_eps=0.001, estimate_body_coil_image=False, sensitivity_map_estimation=SensitivityMapEstimationTransformConfig(estimate_sensitivity_maps=True, sensitivity_maps_type=<SensitivityMapType.RSS_ESTIMATE: '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), normalization=NormalizationTransformConfig(scaling_key='masked_kspace', scale_percentile=0.99), 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][source]#

Bases: BaseConfig

Configuration for the transforms.

Attributes:
maskingMaskingConfig

Configuration for the masking.

croppingCropTransformConfig

Configuration for the cropping.

augmentationAugmentationTransformConfig

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

random_augmentationsRandomAugmentationTransformsConfig

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

padding_epsfloat

Padding epsilon. Default is 0.001.

estimate_body_coil_imagebool

Estimate body coil image. Default is False.

sensitivity_map_estimationSensitivityMapEstimationTransformConfig

Configuration for the sensitivity map estimation.

normalizationNormalizationTransformConfig

Configuration for the normalization.

delete_acs_maskbool

Delete ACS mask after its use. Default is True.

delete_kspacebool

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_typeReconstructionType

Image reconstruction type. Default is ReconstructionType.RSS.

compress_coilsint, optional

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

pad_coilsint, optional

Pad coils. Default is None.

use_seedbool

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_typeTransformsType

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_ratiotuple[float, …]

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_regiontuple[int, int]

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_acsbool, optional

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

mask_split_typeMaskSplitterType

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_stdfloat

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_directionHalfSplitType

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.

augmentation: AugmentationTransformConfig = AugmentationTransformConfig(rescale=None, rescale_mode=<RescaleMode.NEAREST: 'nearest'>, rescale_2d_if_3d=False, pad=None)#
compress_coils: Optional[int] = None#
cropping: CropTransformConfig = CropTransformConfig(crop=None, crop_type='uniform', image_center_crop=False)#
delete_acs_mask: bool = True#
delete_kspace: bool = True#
estimate_body_coil_image: bool = False#
image_recon_type: ReconstructionType = 'rss'#
mask_split_acs_region: tuple[int, int] = (0, 0)#
mask_split_gaussian_std: float = 3.0#
mask_split_half_direction: HalfSplitType = 'vertical'#
mask_split_keep_acs: Optional[bool] = False#
mask_split_ratio: tuple[float, ...] = (0.4,)#
mask_split_type: MaskSplitterType = 'gaussian'#
masking: Optional[MaskingConfig] = MaskingConfig(name='???', accelerations=(5.0,), center_fractions=(0.1,), uniform_range=False, mode=<MaskFuncMode.STATIC: 'static'>, val_accelerations=(5.0, 10.0), val_center_fractions=(0.1, 0.05))#
normalization: NormalizationTransformConfig = NormalizationTransformConfig(scaling_key='masked_kspace', scale_percentile=0.99)#
pad_coils: Optional[int] = None#
padding_eps: float = 0.001#
random_augmentations: RandomAugmentationTransformsConfig = RandomAugmentationTransformsConfig(random_rotation_degrees=(-90, 90), random_rotation_probability=0.0, random_flip_type=<RandomFlipType.RANDOM: 'random'>, random_flip_probability=0.0, random_reverse_probability=0.0)#
sensitivity_map_estimation: SensitivityMapEstimationTransformConfig = SensitivityMapEstimationTransformConfig(estimate_sensitivity_maps=True, sensitivity_maps_type=<SensitivityMapType.RSS_ESTIMATE: '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)#
transforms_type: TransformsType = 'supervised'#
use_seed: bool = True#

direct.data.fake module#

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

Bases: object

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

get_kspace(spatial_shape, num_coils)[source][source]#
Parameters:
spatial_shape: List of ints or tuple of ints.
num_coils: int
Return type:

ndarray

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

Generates gaussian blobs in ‘num_coils’ classes and scales them the interval.

[0, slice] x [0, height] x [0, width].

Return type:

Tuple[ndarray, ndarray, ndarray]

set_attrs(sample)[source][source]#

Sets metadata attributes of sample.

Return type:

Dict

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

Fast Fourier Transform.

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

Inverse Fast Fourier Transform.

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

Root Sum of Squares Estimate, given kspace data.

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

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

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][source]#

Bases: Dataset

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

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

direct.data.lr_scheduler module#

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

Bases: _LRScheduler

state_dict()[source][source]#

Returns the state of the scheduler as a dict.

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

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

Bases: _LRScheduler

get_lr()[source][source]#
Return type:

List[float]

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][source]#

Bases: _LRScheduler

get_lr()[source][source]#
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.AddBooleanKeysModule(keys, values)[source][source]#

Bases: DirectModule

Adds keys with boolean values to sample.

forward(sample)[source][source]#

Adds boolean keys to the input sample dictionary.

Parameters:
sampledict[str, Any]

The input sample dictionary.

Returns:
dict[str, Any]

The modified sample with added boolean keys.

Return type:

dict[str, Any]

training: bool#
class direct.data.mri_transforms.ApplyMaskModule(sampling_mask_key='sampling_mask', input_kspace_key=KspaceKey.KSPACE, target_kspace_key=KspaceKey.MASKED_KSPACE)[source][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.

forward(sample)[source][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.

Returns:
dict[str, Any]

Sample with (new) key target_kspace_key.

Return type:

dict[str, Any]

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

Bases: DirectTransform

Applies zero padding present in multi-coil kspace input.

class direct.data.mri_transforms.Compose(transforms)[source][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.

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

Bases: DirectModule

Compresses k-space coils using SVD.

forward(sample)[source][source]#

Performs coil compression to input k-space.

Parameters:
sampledict[str, Any]

Dict sample containing key kspace_key. Assumes coil dimension is first axis.

Returns:
sampledict[str, Any]

Dict sample with kspace_key compressed to num_coils.

Return type:

dict[str, Any]

training: bool#
class direct.data.mri_transforms.ComputeImageModule(kspace_key, target_key, backward_operator, type_reconstruction=ReconstructionType.RSS)[source][source]#

Bases: DirectModule

Compute Image transform.

forward(sample)[source][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).

Returns:
sample: dict

Contains 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.

Return type:

dict[str, Any]

training: bool#
class direct.data.mri_transforms.ComputeScalingFactorModule(normalize_key=TransformKey.MASKED_KSPACE, percentile=0.99, scaling_factor_key=TransformKey.SCALING_FACTOR)[source][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.

forward(sample)[source][source]#

Forward pass of ComputeScalingFactorModule.

Parameters:
sample: dict[str, Any]

Sample with key normalize_key to compute scaling_factor.

Returns:
sample: dict[str, Any]

Sample with key scaling_factor_key.

Return type:

dict[str, Any]

training: bool#
class direct.data.mri_transforms.ComputeZeroPadding(kspace_key=KspaceKey.KSPACE, padding_key='padding', eps=0.0001)[source][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.\]
class direct.data.mri_transforms.CreateSamplingMask(mask_func, shape=None, use_seed=True, return_acs=False)[source][source]#

Bases: DirectTransform

Data Transformer for training MRI reconstruction models.

Creates sampling mask.

class direct.data.mri_transforms.CropKspace(crop, forward_operator=<function fft2>, backward_operator=<function ifft2>, image_space_center_crop=False, random_crop_sampler_type='uniform', random_crop_sampler_use_seed=True, random_crop_sampler_gaussian_sigma=None)[source][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.

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

Bases: DirectModule

Remove keys from the sample if present.

forward(sample)[source][source]#

Forward pass of DeleteKeys.

Parameters:
sample: dict[str, Any]

Dictionary to look for keys and remove them.

Returns:
dict[str, Any]

Dictionary with deleted specified keys.

Return type:

dict[str, Any]

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

Bases: DirectTransform

Estimates body coil image.

class direct.data.mri_transforms.EstimateSensitivityMapModule(kspace_key=KspaceKey.KSPACE, backward_operator=<function 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][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

[1]

Uecker M, Lai P, Murphy MJ, Virtue P, Elad M, Pauly JM, Vasanawala SS, Lustig M. ESPIRiT–an eigenvalue approach to autocalibrating parallel MRI: where SENSE meets GRAPPA. Magn Reson Med. 2014 Mar;71(3):990-1001. doi: 10.1002/mrm.24751. PMID: 23649942; PMCID: PMC4142121.

estimate_acs_image(sample, width_dim=-2)[source][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.

Returns:
acs_image: torch.Tensor

Estimate of the ACS image.

Return type:

Tensor

forward(sample)[source][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).

Returns:
sample: dict[str, Any]

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

Return type:

dict[str, Any]

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

Bases: object

class SubWrapper(transform, toggle_dims)[source][source]#

Bases: object

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

Bases: DirectModule

Normalize the input data.

forward(sample)[source][source]#

Forward pass of NormalizeModule.

Parameters:
sample: dict[str, Any]

Sample to normalize.

Returns:
sample: dict[str, Any]

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

Return type:

dict[str, Any]

training: bool#
class direct.data.mri_transforms.PadCoilDimensionModule(pad_coils=None, key='masked_kspace', coil_dim=1)[source][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.

forward(sample)[source][source]#

Forward pass of PadCoilDimensionModule.

Parameters:
sample: dict[str, Any]

Dictionary with key self.key.

Returns:
sample: dict[str, Any]

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

Return type:

dict[str, Any]

training: bool#
class direct.data.mri_transforms.PadKspace(pad_shape, forward_operator=<function fft2>, backward_operator=<function ifft2>, kspace_key=KspaceKey.KSPACE)[source][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_shapetuple or list of ints

Shape to zero-pad the input. Must be correspond to (height, width) or (slice/time, height, width).

forward_operatorCallable

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

backward_operatorCallable

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

kspace_keyKspaceKey

K-space key. Default: KspaceKey.KSPACE.

class direct.data.mri_transforms.RandomFlip(flip=RandomFlipType.RANDOM, p=0.5, keys_to_flip=(TransformKey.KSPACE,))[source][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.

class direct.data.mri_transforms.RandomFlipType(value)[source][source]#

Bases: DirectEnum

An enumeration.

BOTH = 'both'#
HORIZONTAL = 'horizontal'#
RANDOM = 'random'#
VERTICAL = 'vertical'#
class direct.data.mri_transforms.RandomReverse(dim=1, p=0.5, keys_to_reverse=(TransformKey.KSPACE,))[source][source]#

Bases: DirectTransform

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

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

Bases: DirectTransform

Random \(k\)-space rotation.

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

class direct.data.mri_transforms.ReconstructionType(value)[source][source]#

Bases: DirectEnum

Reconstruction method for ComputeImage transform.

COMPLEX = 'complex'#
COMPLEX_MOD = 'complex_mod'#
IFFT = 'ifft'#
RSS = 'rss'#
SENSE = 'sense'#
SENSE_MOD = 'sense_mod'#
class direct.data.mri_transforms.RenameKeysModule(old_keys, new_keys)[source][source]#

Bases: DirectModule

Rename keys from the sample if present.

forward(sample)[source][source]#

Forward pass of RenameKeys.

Parameters:
sample: dict[str, Any]

Dictionary to look for keys and rename them.

Returns:
dict[str, Any]

Dictionary with renamed specified keys.

Return type:

dict[str, Any]

training: bool#
class direct.data.mri_transforms.RescaleKspace(shape, forward_operator=<function fft2>, backward_operator=<function ifft2>, rescale_mode=RescaleMode.NEAREST, kspace_key=KspaceKey.KSPACE, rescale_2d_if_3d=None)[source][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:
shapetuple or list of ints

Shape to rescale the input. Must be correspond to (height, width).

forward_operatorCallable

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

backward_operatorCallable

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

rescale_modeRescaleMode

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_keyKspaceKey

K-space key. Default: KspaceKey.KSPACE.

rescale_2d_if_3dbool, optional

If True and input k-space data is 3D, rescaling will be done only on the height and width dimensions. Default: False.

class direct.data.mri_transforms.RescaleMode(value)[source][source]#

Bases: DirectEnum

An enumeration.

AREA = 'area'#
BICUBIC = 'bicubic'#
BILINEAR = 'bilinear'#
NEAREST = 'nearest'#
NEAREST_EXACT = 'nearest-exact'#
TRILINEAR = 'trilinear'#
class direct.data.mri_transforms.SensitivityMapType(value)[source][source]#

Bases: DirectEnum

An enumeration.

ESPIRIT = 'espirit'#
RSS_ESTIMATE = 'rss_estimate'#
UNIT = 'unit'#
class direct.data.mri_transforms.ToTensor[source][source]#

Bases: DirectTransform

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

class direct.data.mri_transforms.TransformsType(value)[source][source]#

Bases: DirectEnum

An enumeration.

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

Bases: DirectModule

Whitens complex data Module.

complex_whiten(complex_image)[source][source]#

Whiten complex image.

Parameters:
complex_image: torch.Tensor

Complex image tensor to whiten.

Returns:
mean, std, whitened_image: tuple[torch.Tensor, torch.Tensor, torch.Tensor]
Return type:

tuple[Tensor, Tensor, Tensor]

forward(sample)[source][source]#

Forward pass of WhitenDataModule.

Parameters:
sample: dict[str, Any]

Sample with key key.

Returns:
sample: dict[str, Any]

Sample with value of key whitened.

Return type:

dict[str, Any]

training: bool#
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][source]#

Build transforms for MRI.

More specifically, the following transformations are applied: :rtype: DirectTransform

  • 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_operatorCallable

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

backward_operatorCallable

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

mask_funcCallable or None

A function which creates a sampling mask of the appropriate shape.

croptuple[int, int] or str, Optional

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_typeOptional[str]

Type of cropping, either “gaussian” or “uniform”. This will be ignored if crop is None. Default: “uniform”.

rescaletuple or list, optional

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_modeRescaleMode

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_3dbool, optional

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.

padtuple or list, optional

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_cropbool

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_degreesSequence[int], optional

Default: (-90, 90).

random_rotation_probabilityfloat, optional

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_typeRandomFlipType, optional

Default: RandomFlipType.RANDOM.

random_flip_probabilityfloat, optional

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

random_reverse_probabilityfloat

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_imagebool

Estimate body coil image. Default: False.

estimate_sensitivity_mapsbool

Estimate sensitivity maps using the acs region. Default: True.

sensitivity_maps_type: sensitivity_maps_type

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_gaussianfloat

Optional sigma for gaussian weighting of sensitivity map.

sensitivity_maps_espirit_thresholdfloat, optional

Threshold for the calibration matrix when type_of_map is set to SensitivityMapType.ESPIRIT. Default: 0.05.

sensitivity_maps_espirit_kernel_sizeint, optional

Kernel size for the calibration matrix when type_of_map is set to SensitivityMapType.ESPIRIT. Default: 6.

sensitivity_maps_espirit_cropfloat, optional

Output eigenvalue cropping threshold when type_of_map is set to SensitivityMapType.ESPIRIT. Default: 0.95.

sensitivity_maps_espirit_max_itersint, optional

Power method iterations when type_of_map is set to SensitivityMapType.ESPIRIT. Default: 30.

delete_acs_maskbool

If True will delete key acs_mask. Default: True.

delete_kspacebool

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

image_recon_typeReconstructionType

Type to reconstruct target image. Default: ReconstructionType.RSS.

compress_coilsint, optional

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

pad_coilsint

Number of coils to pad data to.

scaling_keyTransformKey

Key in sample to scale scalable items in sample. Default: TransformKey.MASKED_KSPACE.

scale_percentilefloat, optional

Data will be rescaled with the given percentile. If None, the division is done by the maximum. Default: 0.99

use_seedbool

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_typeTransformsType, optional

Can be TransformsType.SUPERVISED for supervised learning transforms or TransformsType.SSL_SSDU for self-supervised learning transforms. Default: TransformsType.SUPERVISED.

mask_split_ratioUnion[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_regionUnion[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_acsOptional[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_typeMaskSplitterType

How the sampling mask will be split. Can be MaskSplitterType.UNIFORM, MaskSplitterType.GAUSSIAN, or MaskSplitterType.HALF. Default: MaskSplitterType.GAUSSIAN. This applies only if transforms_type is set to TransformsKey.SSL_SSDU. Default: MaskSplitterType.GAUSSIAN.

mask_split_gaussian_stdfloat

Standard deviation of gaussian mask splitting. This applies only if transforms_type is set to TransformsKey.SSL_SSDU. Ignored if mask_split_type is not set to MaskSplitterType.GAUSSIAN. Default: 3.0.

mask_split_half_directionHalfSplitType

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.

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][source]#

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

More specifically, the following transformations are applied: :rtype: DirectTransform

  • 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_operatorCallable

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

estimate_sensitivity_mapsbool

Estimate sensitivity maps using the acs region. Default: True.

sensitivity_maps_type: sensitivity_maps_type

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_gaussianfloat

Optional sigma for gaussian weighting of sensitivity map.

sensitivity_maps_espirit_threshold: float, optional

Threshold for the calibration matrix when type_of_map is equal to “espirit”. Default: 0.05.

sensitivity_maps_espirit_kernel_size: int, optional

Kernel size for the calibration matrix when type_of_map is equal to “espirit”. Default: 6.

sensitivity_maps_espirit_crop: float, optional

Output eigenvalue cropping threshold when type_of_map is equal to “espirit”. Default: 0.95.

sensitivity_maps_espirit_max_iters: int, optional

Power method iterations when type_of_map is equal to “espirit”. Default: 30.

delete_acs_maskbool

If True will delete key acs_mask. Default: True.

delete_kspacebool

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

image_recon_typeReconstructionType

Type to reconstruct target image. Default: ReconstructionType.RSS.

scaling_keyTransformKey

Key in sample to scale scalable items in sample. Default: TransformKey.MASKED_KSPACE.

scale_percentilefloat, optional

Data will be rescaled with the given percentile. If None, the division is done by the maximum. Default: 0.99 the same mask every time. Default: True.

Returns:
DirectTransform

An MRI transformation object.

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][source]#

Builds pre (on cpu) supervised MRI transforms.

More specifically, the following transformations are applied: :rtype: DirectTransform

  • 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_operatorCallable

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

backward_operatorCallable

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

mask_funcCallable or None

A function which creates a sampling mask of the appropriate shape.

croptuple[int, int] or str, Optional

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_typeOptional[str]

Type of cropping, either “gaussian” or “uniform”. This will be ignored if crop is None. Default: “uniform”.

rescaletuple or list, optional

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_modeRescaleMode

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_3dbool, optional

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.

padtuple or list, optional

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_cropbool

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_degreesSequence[int], optional

Default: (-90, 90).

random_rotation_probabilityfloat, optional

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_typeRandomFlipType, optional

Default: RandomFlipType.RANDOM.

random_flip_probabilityfloat, optional

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_imagebool

Estimate body coil image. Default: False.

use_seedbool

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.

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][source]#

Builds supervised MRI transforms.

More specifically, the following transformations are applied: :rtype: DirectTransform

  • 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_operatorCallable

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

backward_operatorCallable

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

mask_funcCallable or None

A function which creates a sampling mask of the appropriate shape.

croptuple[int, int] or str, Optional

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_typeOptional[str]

Type of cropping, either “gaussian” or “uniform”. This will be ignored if crop is None. Default: “uniform”.

rescaletuple or list, optional

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_modeRescaleMode

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_3dbool, optional

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.

padtuple or list, optional

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_cropbool

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_degreesSequence[int], optional

Default: (-90, 90).

random_rotation_probabilityfloat, optional

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_typeRandomFlipType, optional

Default: RandomFlipType.RANDOM.

random_flip_probabilityfloat, optional

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

random_reverse_probabilityfloat

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_imagebool

Estimate body coil image. Default: False.

estimate_sensitivity_mapsbool

Estimate sensitivity maps using the acs region. Default: True.

sensitivity_maps_type: sensitivity_maps_type

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_gaussianfloat

Optional sigma for gaussian weighting of sensitivity map.

sensitivity_maps_espirit_thresholdfloat, optional

Threshold for the calibration matrix when type_of_map is set to SensitivityMapType.ESPIRIT. Default: 0.05.

sensitivity_maps_espirit_kernel_sizeint, optional

Kernel size for the calibration matrix when type_of_map is set to SensitivityMapType.ESPIRIT. Default: 6.

sensitivity_maps_espirit_cropfloat, optional

Output eigenvalue cropping threshold when type_of_map is set to SensitivityMapType.ESPIRIT. Default: 0.95.

sensitivity_maps_espirit_max_itersint, optional

Power method iterations when type_of_map is set to SensitivityMapType.ESPIRIT. Default: 30.

delete_acs_maskbool

If True will delete key acs_mask. Default: True.

delete_kspacebool

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

image_recon_typeReconstructionType

Type to reconstruct target image. Default: ReconstructionType.RSS.

compress_coilsint, optional

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

pad_coilsint

Number of coils to pad data to.

scaling_keyTransformKey

Key in sample to scale scalable items in sample. Default: TransformKey.MASKED_KSPACE.

scale_percentilefloat, optional

Data will be rescaled with the given percentile. If None, the division is done by the maximum. Default: 0.99

use_seedbool

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.

Returns:
DirectTransform

An MRI transformation object.

direct.data.samplers module#

Module containing all sampler logic.

class direct.data.samplers.BatchVolumeSampler(sampler, batch_size)[source][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

class direct.data.samplers.ConcatDatasetBatchSampler(datasets, batch_size, seed=None)[source][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

batch_sampler(sampler, sampler_offset)[source][source]#
static cumsum(sequence)[source][source]#
class direct.data.samplers.DistributedSampler(size, shuffle=True, seed=None)[source][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)

class direct.data.samplers.DistributedSequentialSampler(dataset, num_replicas=None, rank=None, limit_number_of_volumes=None)[source][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.

Notes

Dataset is assumed to be of constant size.

direct.data.sens module#

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

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

Parameters:
shape: List[int] or Tuple[int]

(nx, ny) or (nx, ny, nz).

num_coils: int

Number of coils to be simulated.

var: float

Variance.

seed: int or None

If not None, a seed will be used to produce an offset for the gaussian mean \(\mu\).

Returns:
sensitivity_mapnd.array

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

Return type:

ndarray

Notes

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.apply_mask(kspace, mask_func, seed=None, return_mask=True)[source][source]#

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

Parameters:
kspace: torch.Tensor

k-space as a complex-valued tensor.

mask_func: callable or torch.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: int

Seed for the random number generator

return_mask: bool

If true, mask will be returned

Returns:
masked data, mask: (torch.Tensor, torch.Tensor)
Return type:

Union[tuple[Tensor, Tensor], Tensor]

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

Applies zero padding to data.

Parameters:
datatorch.Tensor

Batched or not input to be padded of shape (batch, *, height, width, *).

paddingtorch.Tensor or None

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.

Returns:
datatorch.Tensor

Padded data.

Return type:

Tensor

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

Apply a center crop along the last two dimensions.

Parameters:
data: torch.Tensor
shape: list or tuple of ints

The output shape, should be smaller than the corresponding data dimensions.

Returns:
torch.Tensor: The center cropped data.
Return type:

Tensor

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

Complex batch multiplication.

Parameters:
input_tensor: torch.Tensor

Input tensor.

other_tensor: torch.Tensor

Other tensor.

Returns:
out: torch.Tensor

Batch complex-multiplied output tensor.

Return type:

Tensor

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

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

Parameters:
data_list: Union[list[torch.Tensor], torch.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: list[int] or 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.

contiguous: bool

Return as a contiguous array. Useful for fast reshaping or viewing.

Returns:
Union[list[torch.Tensor], torch.Tensor]

The center cropped input_image(s).

Return type:

Union[list[Tensor], Tensor]

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

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

Parameters:
input_tensor: torch.Tensor

Input data

other_tensor: torch.Tensor

Input data

Returns:
torch.Tensor
Return type:

Tensor

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

Computes the dot product of the complex tensors \(a\) and \(b\): \(a^{*}b = <a, b>\).

Parameters:
atorch.Tensor

Input \(a\).

btorch.Tensor

Input \(b\).

dimlist[int]

Dimensions which will be suppressed. Useful when inputs are batched.

Returns:
complex_dot_producttorch.Tensor

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

Return type:

Tensor

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

Resize a complex tensor to a new size.

Parameters:
complex_imagetorch.Tensor

Complex image tensor with shape (B, C, [D], [H,] W, 2) representing real and imaginary parts

resize_shapetuple or list of two integers

Shape to resize image to.

modestr

Algorithm used for upsampling: ‘nearest’ | ‘linear’ | ‘bilinear’ | ‘bicubic’ | ‘trilinear’ | ‘area’ | ‘nearest-exact’. Default: ‘nearest’

Returns:
resized_imagetorch.Tensor

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

Return type:

Tensor

direct.data.transforms.complex_mm(input_tensor, other_tensor)[source][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: torch.Tensor

Input 2D tensor.

other_tensor: torch.Tensor

Other 2D tensor.

Returns:
out: torch.Tensor

Complex-multiplied 2D output tensor.

Return type:

Tensor

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

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

Parameters:
input_tensor: torch.Tensor

Input data

other_tensor: torch.Tensor

Input data

Returns:
torch.Tensor
Return type:

Tensor

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

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

Parameters:
data_list: Union[list[torch.Tensor], torch.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: list[int] or tuple[int, …]

The output shape. The shape should be smaller than the corresponding dimensions of data.

offset: int

Starting dimension for cropping.

contiguous: bool

Return as a contiguous array. Useful for fast reshaping or viewing.

sampler: str

Select the random indices from either a uniform or gaussian distribution (around the center)

sigma: float or list of float or None

Standard variance of the gaussian when sampler is gaussian. If not set will take 1/3th of image shape

seed: None, int or ArrayLike
Returns:
Union[list[torch.Tensor], torch.Tensor]

The center cropped input tensor or list of tensors.

Return type:

Union[list[Tensor], Tensor]

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

Compute the complex conjugate of a torch tensor where the last axis denotes the real and complex part (last axis has dimension 2).

Parameters:
data: torch.Tensor
Returns:
conjugate_tensor: torch.Tensor
Return type:

Tensor

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

Crops k-space to autocalibration region given the acs_mask.

Parameters:
acs_masktorch.Tensor

Autocalibration mask of shape (height, width).

kspacetorch.Tensor

K-space of shape (coil, height, width, *).

Returns:
torch.Tensor

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

Return type:

Tensor

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

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

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

Adapted from [1].

Parameters:
data: torch.Tensor

Image data. Should be a complex tensor (with complex dim of size 2).

sensitivity_map: torch.Tensor

Coil sensitivity maps. Should be complex tensor (with complex dim of size 2).

dim: int

Coil dimension. Default: 0.

Returns:
torch.Tensor:

Zero-filled reconstructions from each coil.

References

[1]

Sriram, Anuroop, et al. “End-to-End Variational Networks for Accelerated MRI Reconstruction.” ArXiv:2004.06688 [Cs, Eess], Apr. 2020. arXiv.org, http://arxiv.org/abs/2004.06688.

direct.data.transforms.fft2(data, dim=(1, 2), centered=True, normalized=True, complex_input=True)[source][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: torch.Tensor

Complex-valued input tensor. Should be of shape (*, 2) and dim is in *.

dim: tuple, list or int

Dimensions over which to compute. Should be positive. Negative indexing not supported Default is (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.

normalized: bool

Whether to normalize the fft. For the FastMRI this has to be true and for the Calgary-Campinas dataset false.

complex_input:bool

True if input is complex [real-valued] tensor (complex dim = 2). False if complex-valued tensor is inputted.

Returns:
output_data: torch.Tensor

The Fast Fourier transform of the data.

Return type:

Tensor

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

Similar to numpy fftshift but applies to pytorch tensors.

Parameters:
data: torch.Tensor

Input data.

dim: list or tuple of ints or None

Default: None.

Returns:
torch.Tensor
Return type:

Tensor

direct.data.transforms.ifft2(data, dim=(1, 2), centered=True, normalized=True, complex_input=True)[source][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: torch.Tensor

Complex-valued input tensor. Should be of shape (*, 2) and dim is in *.

dim: tuple, list or int

Dimensions over which to compute. Should be positive. Negative indexing not supported Default is (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.

normalized: bool

Whether to normalize the ifft. For the FastMRI this has to be true and for the Calgary-Campinas dataset false.

complex_input:bool

True if input is complex [real-valued] tensor (complex dim = 2). False if complex-valued tensor is inputted.

Returns:
output_data: torch.Tensor

The Inverse Fast Fourier transform of the data.

Return type:

Tensor

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

Similar to numpy ifftshift but applies to pytorch tensors.

Parameters:
data: torch.Tensor

Input data.

dim: list or tuple of ints or None

Default: None.

Returns:
torch.Tensor
Return type:

Tensor

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

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

Parameters:
data: torch.Tensor
complex_axis: int

Complex dimension along which the modulus will be calculated. Default: -1.

Returns:
output_data: torch.Tensor

Modulus of data.

Return type:

Tensor

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

Compute modulus if complex tensor (has complex axis).

Parameters:
data: torch.Tensor
complex_axis: int

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

Returns:
torch.Tensor
Return type:

Tensor

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

Pads an input image tensor to a desired shape.

Parameters:
input_imagetorch.Tensor

The input image tensor of shape (…, x, y) or (…, z, x, y).

target_shapetuple of integers

The desired shape (X, Y) or (Z, X, Y) for the padded image.

valuefloat

Padding value. Default: 0.

Returns:
torch.Tensor

The padded image tensor

Return type:

Tensor

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

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: :rtype: Tensor

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

Adapted from [1].

Parameters:
coil_data: torch.Tensor

Zero-filled reconstructions from coils. Should be a complex tensor (with complex dim of size 2).

sensitivity_map: torch.Tensor

Coil sensitivity maps. Should be complex tensor (with complex dim of size 2).

dim: int

Coil dimension. Default: 0.

Returns:
torch.Tensor:

Combined individual coil images.

References

[1]

Sriram, Anuroop, et al. “End-to-End Variational Networks for Accelerated MRI Reconstruction.” ArXiv:2004.06688 [Cs, Eess], Apr. 2020. arXiv.org, http://arxiv.org/abs/2004.06688.

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

Similar to numpy roll but applies to pytorch tensors.

Parameters:
data: torch.Tensor
shift: tuple, int
dim: list or tuple of ints
Returns:
torch.Tensor

Rolled version of data

Return type:

Tensor

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

Similar to roll but only for one dim

Parameters:
data: torch.Tensor
shift: tuple, int
dim: int
Returns:
torch.Tensor
Return type:

Tensor

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

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

\[x_{\textrm{RSS}} = \sqrt{\sum_{i \in \textrm{coil}} |x_i|^2}\]
Parameters:
data: torch.Tensor

Input tensor

dim: int

Coil dimension. Default is 0 as the first dimension is always the coil dimension.

complex_dim: int

Complex channel dimension. Default is -1. If data not complex this is ignored.

Returns:
torch.Tensor: RSS of the input tensor.
direct.data.transforms.safe_divide(input_tensor, other_tensor)[source][source]#

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

Parameters:
input_tensor: torch.Tensor
other_tensor: torch.Tensor
Returns:
torch.Tensor: the division.
Return type:

Tensor

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

Converts a complex pytorch tensor to a complex numpy array. The last axis denote the real and imaginary parts respectively.

Parameters:
data: torch.Tensor

Input data

Returns:
out: np.array

Complex valued np.ndarray

Return type:

ndarray

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

Convert numpy array to PyTorch tensor. Complex arrays will have real and imaginary parts on the last axis.

Parameters:
data: np.ndarray
Returns:
torch.Tensor
Return type:

Tensor

direct.data.transforms.verify_fft_dtype_possible(data, dims)[source][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: torch.Tensor
dims: tuple of two or three ints
Returns:
bool
Return type:

bool

direct.data.transforms.view_as_complex(data)[source][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: torch.Tensor

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

Returns:
complex_valued_data: torch.Tensor

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

direct.data.transforms.view_as_real(data)[source][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: torch.Tensor

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

Returns:
real_valued_data: torch.Tensor

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

Module contents#