synapse_net.training.dataloaders

  1from typing import Optional, Tuple, Union
  2
  3import torch
  4import torch_em
  5from torch_em.data import RawDatasetWithMasks
  6
  7
  8def _adjust_patch_shape(data_shape, patch_shape):
  9    # If data is 2D and patch_shape is 3D, drop the extra dimension in patch_shape
 10    if data_shape == 2 and len(patch_shape) == 3:
 11        return patch_shape[1:]  # Remove the leading dimension in patch_shape
 12    return patch_shape  # Return the original patch_shape for 3D data
 13
 14
 15def _determine_ndim(patch_shape):
 16    # Check for 2D or 3D training
 17    try:
 18        z, y, x = patch_shape
 19    except ValueError:
 20        y, x = patch_shape
 21        z = 1
 22    is_2d = z == 1
 23    ndim = 2 if is_2d else 3
 24    return is_2d, ndim
 25
 26
 27def get_supervised_loader(
 28    data_paths: Tuple[str],
 29    raw_key: str,
 30    label_key: str,
 31    patch_shape: Tuple[int, int, int],
 32    batch_size: int,
 33    n_samples: Optional[int],
 34    add_boundary_transform: bool = True,
 35    label_dtype=torch.float32,
 36    rois: Optional[Tuple[Tuple[slice]]] = None,
 37    sampler: Optional[Union[callable, bool]] = None,
 38    ignore_label: Optional[int] = None,
 39    label_transform: Optional[callable] = None,
 40    label_paths: Optional[Tuple[str]] = None,
 41    raw_transform: Optional[callable] = None,
 42    transform: Optional[callable] = None,
 43    **loader_kwargs,
 44) -> torch.utils.data.DataLoader:
 45    """Get a dataloader for supervised segmentation training.
 46
 47    Args:
 48        data_paths: The filepaths to the hdf5 files containing the training data.
 49        raw_key: The key that holds the raw data inside of the hdf5.
 50        label_key: The key that holds the labels inside of the hdf5.
 51        patch_shape: The patch shape used for a training example.
 52            In order to run 2d training pass a patch shape with a singleton in the z-axis,
 53            e.g. 'patch_shape = [1, 512, 512]'.
 54        batch_size: The batch size for training.
 55        n_samples: The number of samples per epoch. By default this will be estimated
 56            based on the patch_shape and size of the volumes used for training.
 57        add_boundary_transform: Whether to add a boundary channel to the training data.
 58        label_dtype: The datatype of the labels returned by the dataloader.
 59        rois: Optional region of interests for training.
 60        sampler: Optional sampler to accept or reject patches for training.
 61            By default a minimum instance sampler will be used, pass `False` to disable.
 62        ignore_label: Ignore label in the ground-truth. The areas marked by this label will be
 63            ignored in the loss computation. By default this option is not used.
 64        label_transform: Label transform that is applied to the segmentation to compute the targets.
 65            If no label transform is passed (the default) a boundary transform is used.
 66        label_paths: Optional paths containing the labels / annotations for training.
 67            If not given, the labels are expected to be contained in the `data_paths`.
 68        raw_transform: Normalization applied to the raw data. By default the torch_em standardization is used.
 69        transform: Joint transformation applied to the raw data and the labels, after the
 70            `label_transform`. By default padding and the standard augmentations are applied.
 71        loader_kwargs: Additional keyword arguments for the dataloader.
 72
 73    Returns:
 74        The PyTorch dataloader.
 75    """
 76    _, ndim = _determine_ndim(patch_shape)
 77    if label_transform is not None:  # A specific label transform was passed, do nothing.
 78        pass
 79    elif add_boundary_transform:
 80        if ignore_label is None:
 81            label_transform = torch_em.transform.BoundaryTransform(add_binary_target=True)
 82        else:
 83            label_transform = torch_em.transform.label.BoundaryTransformWithIgnoreLabel(
 84                add_binary_target=True, ignore_label=ignore_label
 85            )
 86
 87    else:
 88        if ignore_label is not None:
 89            raise NotImplementedError
 90        label_transform = torch_em.transform.label.connected_components
 91
 92    if transform is not None:  # A specific joint transform was passed, do nothing.
 93        pass
 94    elif ndim == 2:
 95        adjusted_patch_shape = _adjust_patch_shape(ndim, patch_shape)
 96        transform = torch_em.transform.Compose(
 97            torch_em.transform.PadIfNecessary(adjusted_patch_shape), torch_em.transform.get_augmentations(2)
 98        )
 99    else:
100        transform = torch_em.transform.Compose(
101            torch_em.transform.PadIfNecessary(patch_shape), torch_em.transform.get_augmentations(3)
102        )
103
104    num_workers = loader_kwargs.pop("num_workers", 4 * batch_size)
105    shuffle = loader_kwargs.pop("shuffle", True)
106
107    if sampler is None:
108        sampler = torch_em.data.sampler.MinInstanceSampler(min_num_instances=4)
109    elif sampler is False:
110        sampler = None
111
112    if label_paths is None:
113        label_paths = data_paths
114    elif len(label_paths) != len(data_paths):
115        raise ValueError(f"Data paths and label paths don't match: {len(data_paths)} != {len(label_paths)}")
116
117    loader = torch_em.default_segmentation_loader(
118        data_paths, raw_key,
119        label_paths, label_key, sampler=sampler,
120        batch_size=batch_size, patch_shape=patch_shape, ndim=ndim,
121        is_seg_dataset=True, label_transform=label_transform, transform=transform,
122        num_workers=num_workers, shuffle=shuffle, n_samples=n_samples,
123        label_dtype=label_dtype, rois=rois, raw_transform=raw_transform, **loader_kwargs,
124    )
125    return loader
126
127
128def get_unsupervised_loader(
129    data_paths: Tuple[str],
130    raw_key: str,
131    patch_shape: Tuple[int, int, int],
132    batch_size: int,
133    n_samples: Optional[int],
134    sample_mask_paths: Optional[Tuple[str]] = None,
135    sample_mask_key: Optional[str] = None,
136    bg_mask_paths: Optional[Tuple[str]] = None,
137    bg_mask_key: Optional[str] = None,
138    sampler: Optional[callable] = None,
139    exclude_top_and_bottom: bool = False,
140    raw_transform: Optional[callable] = None,
141) -> torch.utils.data.DataLoader:
142    """Get a dataloader for unsupervised segmentation training.
143
144    Args:
145        data_paths: The filepaths to the hdf5 files containing the training data.
146        raw_key: The key that holds the raw data inside of the hdf5.
147        patch_shape: The patch shape used for a training example.
148            In order to run 2d training pass a patch shape with a singleton in the z-axis,
149            e.g. 'patch_shape = [1, 512, 512]'.
150        batch_size: The batch size for training.
151        n_samples: The number of samples per epoch. By default this will be estimated
152            based on the patch_shape and size of the volumes used for training.
153        sample_mask_paths: The filepaths to the corresponding sample masks for each tomogram.
154        sample_mask_key: The key to the sample mask dataset inside each file.
155        bg_mask_paths: The filepaths to the background masks for each tomogram.
156        bg_mask_key: The key to the background mask dataset inside each file.
157        sampler: Optional sampler to accept or reject patches for training.
158        exclude_top_and_bottom: Whether to exclude the five top and bottom slices to
159            avoid artifacts at the border of tomograms.
160        raw_transform: Normalization applied to the raw data. By default the torch_em standardization is used.
161
162    Returns:
163        The PyTorch dataloader.
164    """
165    if exclude_top_and_bottom:
166        roi = (slice(5, -5), slice(None), slice(None))
167    else:
168        roi = None
169
170    if sample_mask_paths is not None:
171        assert len(data_paths) == len(sample_mask_paths), (
172            "Expected equal number of data_paths and sample_mask_paths, "
173            f"got {len(data_paths)} and {len(sample_mask_paths)}."
174        )
175    if bg_mask_paths is not None:
176        assert len(data_paths) == len(bg_mask_paths), \
177            f"Expected equal number of data_paths and bg_mask_paths, got {len(data_paths)} and {len(bg_mask_paths)}."
178
179    _, ndim = _determine_ndim(patch_shape)
180    if raw_transform is None:
181        raw_transform = torch_em.transform.get_raw_transform()
182    transform = torch_em.transform.get_augmentations(ndim=ndim)
183
184    if n_samples is None:
185        n_samples_per_ds = None
186    else:
187        n_samples_per_ds = int(n_samples / len(data_paths))
188
189    datasets = [
190        RawDatasetWithMasks(
191            raw_path=data_path,
192            raw_key=raw_key,
193            patch_shape=patch_shape,
194            raw_transform=raw_transform,
195            transform=transform,
196            roi=roi,
197            n_samples=n_samples_per_ds,
198            sampler=sampler,
199            ndim=ndim,
200            augmentations=None,
201            sample_mask_path=sample_mask_paths[i] if sample_mask_paths is not None else None,
202            sample_mask_key=sample_mask_key,
203            bg_mask_path=bg_mask_paths[i] if bg_mask_paths is not None else None,
204            bg_mask_key=bg_mask_key,
205        )
206        for i, data_path in enumerate(data_paths)
207    ]
208    ds = torch.utils.data.ConcatDataset(datasets)
209
210    num_workers = 4 * batch_size
211    loader = torch_em.segmentation.get_data_loader(ds, batch_size=batch_size,
212                                                   num_workers=num_workers, shuffle=True)
213    return loader
def get_supervised_loader( data_paths: Tuple[str], raw_key: str, label_key: str, patch_shape: Tuple[int, int, int], batch_size: int, n_samples: Optional[int], add_boundary_transform: bool = True, label_dtype=torch.float32, rois: Optional[Tuple[Tuple[slice]]] = None, sampler: Union[<built-in function callable>, bool, NoneType] = None, ignore_label: Optional[int] = None, label_transform: Optional[<built-in function callable>] = None, label_paths: Optional[Tuple[str]] = None, raw_transform: Optional[<built-in function callable>] = None, transform: Optional[<built-in function callable>] = None, **loader_kwargs) -> torch.utils.data.dataloader.DataLoader:
 28def get_supervised_loader(
 29    data_paths: Tuple[str],
 30    raw_key: str,
 31    label_key: str,
 32    patch_shape: Tuple[int, int, int],
 33    batch_size: int,
 34    n_samples: Optional[int],
 35    add_boundary_transform: bool = True,
 36    label_dtype=torch.float32,
 37    rois: Optional[Tuple[Tuple[slice]]] = None,
 38    sampler: Optional[Union[callable, bool]] = None,
 39    ignore_label: Optional[int] = None,
 40    label_transform: Optional[callable] = None,
 41    label_paths: Optional[Tuple[str]] = None,
 42    raw_transform: Optional[callable] = None,
 43    transform: Optional[callable] = None,
 44    **loader_kwargs,
 45) -> torch.utils.data.DataLoader:
 46    """Get a dataloader for supervised segmentation training.
 47
 48    Args:
 49        data_paths: The filepaths to the hdf5 files containing the training data.
 50        raw_key: The key that holds the raw data inside of the hdf5.
 51        label_key: The key that holds the labels inside of the hdf5.
 52        patch_shape: The patch shape used for a training example.
 53            In order to run 2d training pass a patch shape with a singleton in the z-axis,
 54            e.g. 'patch_shape = [1, 512, 512]'.
 55        batch_size: The batch size for training.
 56        n_samples: The number of samples per epoch. By default this will be estimated
 57            based on the patch_shape and size of the volumes used for training.
 58        add_boundary_transform: Whether to add a boundary channel to the training data.
 59        label_dtype: The datatype of the labels returned by the dataloader.
 60        rois: Optional region of interests for training.
 61        sampler: Optional sampler to accept or reject patches for training.
 62            By default a minimum instance sampler will be used, pass `False` to disable.
 63        ignore_label: Ignore label in the ground-truth. The areas marked by this label will be
 64            ignored in the loss computation. By default this option is not used.
 65        label_transform: Label transform that is applied to the segmentation to compute the targets.
 66            If no label transform is passed (the default) a boundary transform is used.
 67        label_paths: Optional paths containing the labels / annotations for training.
 68            If not given, the labels are expected to be contained in the `data_paths`.
 69        raw_transform: Normalization applied to the raw data. By default the torch_em standardization is used.
 70        transform: Joint transformation applied to the raw data and the labels, after the
 71            `label_transform`. By default padding and the standard augmentations are applied.
 72        loader_kwargs: Additional keyword arguments for the dataloader.
 73
 74    Returns:
 75        The PyTorch dataloader.
 76    """
 77    _, ndim = _determine_ndim(patch_shape)
 78    if label_transform is not None:  # A specific label transform was passed, do nothing.
 79        pass
 80    elif add_boundary_transform:
 81        if ignore_label is None:
 82            label_transform = torch_em.transform.BoundaryTransform(add_binary_target=True)
 83        else:
 84            label_transform = torch_em.transform.label.BoundaryTransformWithIgnoreLabel(
 85                add_binary_target=True, ignore_label=ignore_label
 86            )
 87
 88    else:
 89        if ignore_label is not None:
 90            raise NotImplementedError
 91        label_transform = torch_em.transform.label.connected_components
 92
 93    if transform is not None:  # A specific joint transform was passed, do nothing.
 94        pass
 95    elif ndim == 2:
 96        adjusted_patch_shape = _adjust_patch_shape(ndim, patch_shape)
 97        transform = torch_em.transform.Compose(
 98            torch_em.transform.PadIfNecessary(adjusted_patch_shape), torch_em.transform.get_augmentations(2)
 99        )
100    else:
101        transform = torch_em.transform.Compose(
102            torch_em.transform.PadIfNecessary(patch_shape), torch_em.transform.get_augmentations(3)
103        )
104
105    num_workers = loader_kwargs.pop("num_workers", 4 * batch_size)
106    shuffle = loader_kwargs.pop("shuffle", True)
107
108    if sampler is None:
109        sampler = torch_em.data.sampler.MinInstanceSampler(min_num_instances=4)
110    elif sampler is False:
111        sampler = None
112
113    if label_paths is None:
114        label_paths = data_paths
115    elif len(label_paths) != len(data_paths):
116        raise ValueError(f"Data paths and label paths don't match: {len(data_paths)} != {len(label_paths)}")
117
118    loader = torch_em.default_segmentation_loader(
119        data_paths, raw_key,
120        label_paths, label_key, sampler=sampler,
121        batch_size=batch_size, patch_shape=patch_shape, ndim=ndim,
122        is_seg_dataset=True, label_transform=label_transform, transform=transform,
123        num_workers=num_workers, shuffle=shuffle, n_samples=n_samples,
124        label_dtype=label_dtype, rois=rois, raw_transform=raw_transform, **loader_kwargs,
125    )
126    return loader

Get a dataloader for supervised segmentation training.

Arguments:
  • data_paths: The filepaths to the hdf5 files containing the training data.
  • raw_key: The key that holds the raw data inside of the hdf5.
  • label_key: The key that holds the labels inside of the hdf5.
  • patch_shape: The patch shape used for a training example. In order to run 2d training pass a patch shape with a singleton in the z-axis, e.g. 'patch_shape = [1, 512, 512]'.
  • batch_size: The batch size for training.
  • n_samples: The number of samples per epoch. By default this will be estimated based on the patch_shape and size of the volumes used for training.
  • add_boundary_transform: Whether to add a boundary channel to the training data.
  • label_dtype: The datatype of the labels returned by the dataloader.
  • rois: Optional region of interests for training.
  • sampler: Optional sampler to accept or reject patches for training. By default a minimum instance sampler will be used, pass False to disable.
  • ignore_label: Ignore label in the ground-truth. The areas marked by this label will be ignored in the loss computation. By default this option is not used.
  • label_transform: Label transform that is applied to the segmentation to compute the targets. If no label transform is passed (the default) a boundary transform is used.
  • label_paths: Optional paths containing the labels / annotations for training. If not given, the labels are expected to be contained in the data_paths.
  • raw_transform: Normalization applied to the raw data. By default the torch_em standardization is used.
  • transform: Joint transformation applied to the raw data and the labels, after the label_transform. By default padding and the standard augmentations are applied.
  • loader_kwargs: Additional keyword arguments for the dataloader.
Returns:

The PyTorch dataloader.

def get_unsupervised_loader( data_paths: Tuple[str], raw_key: str, patch_shape: Tuple[int, int, int], batch_size: int, n_samples: Optional[int], sample_mask_paths: Optional[Tuple[str]] = None, sample_mask_key: Optional[str] = None, bg_mask_paths: Optional[Tuple[str]] = None, bg_mask_key: Optional[str] = None, sampler: Optional[<built-in function callable>] = None, exclude_top_and_bottom: bool = False, raw_transform: Optional[<built-in function callable>] = None) -> torch.utils.data.dataloader.DataLoader:
129def get_unsupervised_loader(
130    data_paths: Tuple[str],
131    raw_key: str,
132    patch_shape: Tuple[int, int, int],
133    batch_size: int,
134    n_samples: Optional[int],
135    sample_mask_paths: Optional[Tuple[str]] = None,
136    sample_mask_key: Optional[str] = None,
137    bg_mask_paths: Optional[Tuple[str]] = None,
138    bg_mask_key: Optional[str] = None,
139    sampler: Optional[callable] = None,
140    exclude_top_and_bottom: bool = False,
141    raw_transform: Optional[callable] = None,
142) -> torch.utils.data.DataLoader:
143    """Get a dataloader for unsupervised segmentation training.
144
145    Args:
146        data_paths: The filepaths to the hdf5 files containing the training data.
147        raw_key: The key that holds the raw data inside of the hdf5.
148        patch_shape: The patch shape used for a training example.
149            In order to run 2d training pass a patch shape with a singleton in the z-axis,
150            e.g. 'patch_shape = [1, 512, 512]'.
151        batch_size: The batch size for training.
152        n_samples: The number of samples per epoch. By default this will be estimated
153            based on the patch_shape and size of the volumes used for training.
154        sample_mask_paths: The filepaths to the corresponding sample masks for each tomogram.
155        sample_mask_key: The key to the sample mask dataset inside each file.
156        bg_mask_paths: The filepaths to the background masks for each tomogram.
157        bg_mask_key: The key to the background mask dataset inside each file.
158        sampler: Optional sampler to accept or reject patches for training.
159        exclude_top_and_bottom: Whether to exclude the five top and bottom slices to
160            avoid artifacts at the border of tomograms.
161        raw_transform: Normalization applied to the raw data. By default the torch_em standardization is used.
162
163    Returns:
164        The PyTorch dataloader.
165    """
166    if exclude_top_and_bottom:
167        roi = (slice(5, -5), slice(None), slice(None))
168    else:
169        roi = None
170
171    if sample_mask_paths is not None:
172        assert len(data_paths) == len(sample_mask_paths), (
173            "Expected equal number of data_paths and sample_mask_paths, "
174            f"got {len(data_paths)} and {len(sample_mask_paths)}."
175        )
176    if bg_mask_paths is not None:
177        assert len(data_paths) == len(bg_mask_paths), \
178            f"Expected equal number of data_paths and bg_mask_paths, got {len(data_paths)} and {len(bg_mask_paths)}."
179
180    _, ndim = _determine_ndim(patch_shape)
181    if raw_transform is None:
182        raw_transform = torch_em.transform.get_raw_transform()
183    transform = torch_em.transform.get_augmentations(ndim=ndim)
184
185    if n_samples is None:
186        n_samples_per_ds = None
187    else:
188        n_samples_per_ds = int(n_samples / len(data_paths))
189
190    datasets = [
191        RawDatasetWithMasks(
192            raw_path=data_path,
193            raw_key=raw_key,
194            patch_shape=patch_shape,
195            raw_transform=raw_transform,
196            transform=transform,
197            roi=roi,
198            n_samples=n_samples_per_ds,
199            sampler=sampler,
200            ndim=ndim,
201            augmentations=None,
202            sample_mask_path=sample_mask_paths[i] if sample_mask_paths is not None else None,
203            sample_mask_key=sample_mask_key,
204            bg_mask_path=bg_mask_paths[i] if bg_mask_paths is not None else None,
205            bg_mask_key=bg_mask_key,
206        )
207        for i, data_path in enumerate(data_paths)
208    ]
209    ds = torch.utils.data.ConcatDataset(datasets)
210
211    num_workers = 4 * batch_size
212    loader = torch_em.segmentation.get_data_loader(ds, batch_size=batch_size,
213                                                   num_workers=num_workers, shuffle=True)
214    return loader

Get a dataloader for unsupervised segmentation training.

Arguments:
  • data_paths: The filepaths to the hdf5 files containing the training data.
  • raw_key: The key that holds the raw data inside of the hdf5.
  • patch_shape: The patch shape used for a training example. In order to run 2d training pass a patch shape with a singleton in the z-axis, e.g. 'patch_shape = [1, 512, 512]'.
  • batch_size: The batch size for training.
  • n_samples: The number of samples per epoch. By default this will be estimated based on the patch_shape and size of the volumes used for training.
  • sample_mask_paths: The filepaths to the corresponding sample masks for each tomogram.
  • sample_mask_key: The key to the sample mask dataset inside each file.
  • bg_mask_paths: The filepaths to the background masks for each tomogram.
  • bg_mask_key: The key to the background mask dataset inside each file.
  • sampler: Optional sampler to accept or reject patches for training.
  • exclude_top_and_bottom: Whether to exclude the five top and bottom slices to avoid artifacts at the border of tomograms.
  • raw_transform: Normalization applied to the raw data. By default the torch_em standardization is used.
Returns:

The PyTorch dataloader.