Skip to content

data_module

Next-Generation CAREamics DataModule.

InputType = Union[ItemType, Sequence[ItemType], None] module-attribute #

Type of input data passed to the dataset.

ItemType = Union[Path, str, NDArray[Any]] module-attribute #

Type of input items passed to the dataset.

CareamicsDataModule #

Bases: LightningDataModule

Data module for Careamics dataset.

Parameters:

Name Type Description Default
data_config DataConfig

Pydantic model for CAREamics data configuration.

required
train_data Optional[InputType]

Training data, can be a path to a folder, a list of paths, or a numpy array.

None
train_data_target Optional[InputType]

Training data target, can be a path to a folder, a list of paths, or a numpy array.

None
train_data_mask InputType (when filtering is needed)

Training data mask, can be a path to a folder, a list of paths, or a numpy array. Used for coordinate filtering. Only required when using coordinate-based patch filtering.

None
val_data Optional[InputType]

Validation data, can be a path to a folder, a list of paths, or a numpy array.

None
val_data_target Optional[InputType]

Validation data target, can be a path to a folder, a list of paths, or a numpy array.

None
pred_data Optional[InputType]

Prediction data, can be a path to a folder, a list of paths, or a numpy array.

None
pred_data_target Optional[InputType]

Prediction data target, can be a path to a folder, a list of paths, or a numpy array.

None
read_source_func Optional[Callable]

Function to read the source data. Only used for custom data type (see DataModel).

None
read_kwargs Optional[dict[str, Any]]

The kwargs for the read source function.

None
image_stack_loader Optional[ImageStackLoader]

The image stack loader.

None
image_stack_loader_kwargs Optional[dict[str, Any]]

The image stack loader kwargs.

None
extension_filter str

Filter for file extensions. Only used for custom data types (see DataModel).

""
val_percentage Optional[float]

Percentage of the training data to use for validation. Only used if val_data is None.

None
val_minimum_split int

Minimum number of patches or files to split from the training data for validation. Only used if val_data is None.

5
use_in_memory bool

Load data in memory dataset if possible, by default True.

True

Attributes:

Name Type Description
config DataConfig

Pydantic model for CAREamics data configuration.

data_type str

Type of data, one of SupportedData.

batch_size int

Batch size for the dataloaders.

use_in_memory bool

Whether to load data in memory if possible.

extension_filter str

Filter for file extensions, by default "".

read_source_func Optional[Callable], default=None

Function to read the source data.

read_kwargs Optional[dict[str, Any]], default=None

The kwargs for the read source function.

val_percentage Optional[float]

Percentage of the training data to use for validation.

val_minimum_split int, default=5

Minimum number of patches or files to split from the training data for validation.

train_data Optional[Any]

Training data, can be a path to a folder, a list of paths, or a numpy array.

train_data_target Optional[Any]

Training data target, can be a path to a folder, a list of paths, or a numpy array.

train_data_mask Optional[Any]

Training data mask, can be a path to a folder, a list of paths, or a numpy array.

val_data Optional[Any]

Validation data, can be a path to a folder, a list of paths, or a numpy array.

val_data_target Optional[Any]

Validation data target, can be a path to a folder, a list of paths, or a numpy array.

pred_data Optional[Any]

Prediction data, can be a path to a folder, a list of paths, or a numpy array.

pred_data_target Optional[Any]

Prediction data target, can be a path to a folder, a list of paths, or a numpy array.

Raises:

Type Description
ValueError

If at least one of train_data, val_data or pred_data is not provided.

ValueError

If input and target data types are not consistent.

Source code in src/careamics/lightning/dataset_ng/data_module.py
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
class CareamicsDataModule(L.LightningDataModule):
    """Data module for Careamics dataset.

    Parameters
    ----------
    data_config : DataConfig
        Pydantic model for CAREamics data configuration.
    train_data : Optional[InputType]
        Training data, can be a path to a folder, a list of paths, or a numpy array.
    train_data_target : Optional[InputType]
        Training data target, can be a path to a folder,
        a list of paths, or a numpy array.
    train_data_mask : InputType (when filtering is needed)
        Training data mask, can be a path to a folder,
        a list of paths, or a numpy array. Used for coordinate filtering.
        Only required when using coordinate-based patch filtering.
    val_data : Optional[InputType]
        Validation data, can be a path to a folder,
        a list of paths, or a numpy array.
    val_data_target : Optional[InputType]
        Validation data target, can be a path to a folder,
        a list of paths, or a numpy array.
    pred_data : Optional[InputType]
        Prediction data, can be a path to a folder, a list of paths,
        or a numpy array.
    pred_data_target : Optional[InputType]
        Prediction data target, can be a path to a folder,
        a list of paths, or a numpy array.
    read_source_func : Optional[Callable], default=None
        Function to read the source data. Only used for `custom`
        data type (see DataModel).
    read_kwargs : Optional[dict[str, Any]]
        The kwargs for the read source function.
    image_stack_loader : Optional[ImageStackLoader]
        The image stack loader.
    image_stack_loader_kwargs : Optional[dict[str, Any]]
        The image stack loader kwargs.
    extension_filter : str, default=""
        Filter for file extensions. Only used for `custom` data types
        (see DataModel).
    val_percentage : Optional[float]
        Percentage of the training data to use for validation. Only
        used if `val_data` is None.
    val_minimum_split : int, default=5
        Minimum number of patches or files to split from the training data for
        validation. Only used if `val_data` is None.
    use_in_memory : bool
        Load data in memory dataset if possible, by default True.


    Attributes
    ----------
    config : DataConfig
        Pydantic model for CAREamics data configuration.
    data_type : str
        Type of data, one of SupportedData.
    batch_size : int
        Batch size for the dataloaders.
    use_in_memory : bool
        Whether to load data in memory if possible.
    extension_filter : str
        Filter for file extensions, by default "".
    read_source_func : Optional[Callable], default=None
        Function to read the source data.
    read_kwargs : Optional[dict[str, Any]], default=None
        The kwargs for the read source function.
    val_percentage : Optional[float]
        Percentage of the training data to use for validation.
    val_minimum_split : int, default=5
        Minimum number of patches or files to split from the training data for
        validation.
    train_data : Optional[Any]
        Training data, can be a path to a folder, a list of paths, or a numpy array.
    train_data_target : Optional[Any]
        Training data target, can be a path to a folder, a list of paths, or a numpy
        array.
    train_data_mask : Optional[Any]
        Training data mask, can be a path to a folder, a list of paths, or a numpy
        array.
    val_data : Optional[Any]
        Validation data, can be a path to a folder, a list of paths, or a numpy array.
    val_data_target : Optional[Any]
        Validation data target, can be a path to a folder, a list of paths, or a numpy
        array.
    pred_data : Optional[Any]
        Prediction data, can be a path to a folder, a list of paths, or a numpy array.
    pred_data_target : Optional[Any]
        Prediction data target, can be a path to a folder, a list of paths, or a numpy
        array.

    Raises
    ------
    ValueError
        If at least one of train_data, val_data or pred_data is not provided.
    ValueError
        If input and target data types are not consistent.
    """

    # standard use (no mask)
    @overload
    def __init__(
        self,
        data_config: NGDataConfig,
        *,
        train_data: InputType | None = None,
        train_data_target: InputType | None = None,
        val_data: InputType | None = None,
        val_data_target: InputType | None = None,
        pred_data: InputType | None = None,
        pred_data_target: InputType | None = None,
        extension_filter: str = "",
        val_percentage: float | None = None,
        val_minimum_split: int = 5,
        use_in_memory: bool = True,
    ) -> None: ...

    # with training mask for filtering
    @overload
    def __init__(
        self,
        data_config: NGDataConfig,
        *,
        train_data: InputType | None = None,
        train_data_target: InputType | None = None,
        train_data_mask: InputType,
        val_data: InputType | None = None,
        val_data_target: InputType | None = None,
        pred_data: InputType | None = None,
        pred_data_target: InputType | None = None,
        extension_filter: str = "",
        val_percentage: float | None = None,
        val_minimum_split: int = 5,
        use_in_memory: bool = True,
    ) -> None: ...

    # custom read function (no mask)
    @overload
    def __init__(
        self,
        data_config: NGDataConfig,
        *,
        train_data: InputType | None = None,
        train_data_target: InputType | None = None,
        val_data: InputType | None = None,
        val_data_target: InputType | None = None,
        pred_data: InputType | None = None,
        pred_data_target: InputType | None = None,
        read_source_func: Callable,
        read_kwargs: dict[str, Any] | None = None,
        extension_filter: str = "",
        val_percentage: float | None = None,
        val_minimum_split: int = 5,
        use_in_memory: bool = True,
    ) -> None: ...

    # custom read function with training mask
    @overload
    def __init__(
        self,
        data_config: NGDataConfig,
        *,
        train_data: InputType | None = None,
        train_data_target: InputType | None = None,
        train_data_mask: InputType,
        val_data: InputType | None = None,
        val_data_target: InputType | None = None,
        pred_data: InputType | None = None,
        pred_data_target: InputType | None = None,
        read_source_func: Callable,
        read_kwargs: dict[str, Any] | None = None,
        extension_filter: str = "",
        val_percentage: float | None = None,
        val_minimum_split: int = 5,
        use_in_memory: bool = True,
    ) -> None: ...

    # image stack loader (no mask)
    @overload
    def __init__(
        self,
        data_config: NGDataConfig,
        *,
        train_data: Any | None = None,
        train_data_target: Any | None = None,
        val_data: Any | None = None,
        val_data_target: Any | None = None,
        pred_data: Any | None = None,
        pred_data_target: Any | None = None,
        image_stack_loader: ImageStackLoader,
        image_stack_loader_kwargs: dict[str, Any] | None = None,
        extension_filter: str = "",
        val_percentage: float | None = None,
        val_minimum_split: int = 5,
        use_in_memory: bool = True,
    ) -> None: ...

    # image stack loader with training mask
    @overload
    def __init__(
        self,
        data_config: NGDataConfig,
        *,
        train_data: Any | None = None,
        train_data_target: Any | None = None,
        train_data_mask: Any,
        val_data: Any | None = None,
        val_data_target: Any | None = None,
        pred_data: Any | None = None,
        pred_data_target: Any | None = None,
        image_stack_loader: ImageStackLoader,
        image_stack_loader_kwargs: dict[str, Any] | None = None,
        extension_filter: str = "",
        val_percentage: float | None = None,
        val_minimum_split: int = 5,
        use_in_memory: bool = True,
    ) -> None: ...

    def __init__(
        self,
        data_config: NGDataConfig,
        *,
        train_data: Any | None = None,
        train_data_target: Any | None = None,
        train_data_mask: Any | None = None,
        val_data: Any | None = None,
        val_data_target: Any | None = None,
        pred_data: Any | None = None,
        pred_data_target: Any | None = None,
        read_source_func: Callable | None = None,
        read_kwargs: dict[str, Any] | None = None,
        image_stack_loader: ImageStackLoader | None = None,
        image_stack_loader_kwargs: dict[str, Any] | None = None,
        extension_filter: str = "",
        val_percentage: float | None = None,
        val_minimum_split: int = 5,
        use_in_memory: bool = True,
    ) -> None:
        """
        Data module for Careamics dataset initialization.

        Create a lightning datamodule that handles creating datasets for training,
        validation, and prediction.

        Parameters
        ----------
        data_config : NGDataConfig
            Pydantic model for CAREamics data configuration.
        train_data : Optional[InputType]
            Training data, can be a path to a folder, a list of paths, or a numpy array.
        train_data_target : Optional[InputType]
            Training data target, can be a path to a folder,
            a list of paths, or a numpy array.
        train_data_mask : InputType (when filtering is needed)
            Training data mask, can be a path to a folder,
            a list of paths, or a numpy array. Used for coordinate filtering.
            Only required when using coordinate-based patch filtering.
        val_data : Optional[InputType]
            Validation data, can be a path to a folder,
            a list of paths, or a numpy array.
        val_data_target : Optional[InputType]
            Validation data target, can be a path to a folder,
            a list of paths, or a numpy array.
        pred_data : Optional[InputType]
            Prediction data, can be a path to a folder, a list of paths,
            or a numpy array.
        pred_data_target : Optional[InputType]
            Prediction data target, can be a path to a folder,
            a list of paths, or a numpy array.
        read_source_func : Optional[Callable]
            Function to read the source data, by default None. Only used for `custom`
            data type (see DataModel).
        read_kwargs : Optional[dict[str, Any]]
            The kwargs for the read source function.
        image_stack_loader : Optional[ImageStackLoader]
            The image stack loader.
        image_stack_loader_kwargs : Optional[dict[str, Any]]
            The image stack loader kwargs.
        extension_filter : str
            Filter for file extensions, by default "". Only used for `custom` data types
            (see DataModel).
        val_percentage : Optional[float]
            Percentage of the training data to use for validation. Only
            used if `val_data` is None.
        val_minimum_split : int
            Minimum number of patches or files to split from the training data for
            validation, by default 5. Only used if `val_data` is None.
        use_in_memory : bool
            Load data in memory dataset if possible, by default True.
        """
        super().__init__()

        if train_data is None and val_data is None and pred_data is None:
            raise ValueError(
                "At least one of train_data, val_data or pred_data must be provided."
            )
        elif train_data is None != val_data is None:
            raise ValueError(
                "If one of train_data or val_data is provided, both must be provided."
            )

        self.config: NGDataConfig = data_config
        self.data_type: str = data_config.data_type
        self.batch_size: int = data_config.batch_size
        self.use_in_memory: bool = use_in_memory

        self.extension_filter: str = (
            extension_filter  # list_files pulls the correct ext
        )
        self.read_source_func = read_source_func
        self.read_kwargs = read_kwargs
        self.image_stack_loader = image_stack_loader
        self.image_stack_loader_kwargs = image_stack_loader_kwargs

        # TODO: implement the validation split logic
        self.val_percentage = val_percentage
        self.val_minimum_split = val_minimum_split
        if self.val_percentage is not None:
            raise NotImplementedError("Validation split is not implemented.")

        custom_loader = self.image_stack_loader is not None
        self.train_data, self.train_data_target = initialize_data_pair(
            self.data_type,
            train_data,
            train_data_target,
            extension_filter,
            custom_loader,
        )
        self.train_data_mask, _ = initialize_data_pair(
            self.data_type, train_data_mask, None, extension_filter, custom_loader
        )

        self.val_data, self.val_data_target = initialize_data_pair(
            self.data_type, val_data, val_data_target, extension_filter, custom_loader
        )

        # The pred_data_target can be needed to count metrics on the prediction
        self.pred_data, self.pred_data_target = initialize_data_pair(
            self.data_type, pred_data, pred_data_target, extension_filter, custom_loader
        )

    def setup(self, stage: str) -> None:
        """
        Setup datasets.

        Lightning hook that is called at the beginning of fit (train + validate),
        validate, test, or predict. Creates the datasets for a given stage.

        Parameters
        ----------
        stage : str
            The stage to set up datasets for.
            Is either 'fit', 'validate', 'test', or 'predict'.

        Raises
        ------
        NotImplementedError
            If stage is not one of "fit", "validate" or "predict".
        """
        if stage == "fit":
            self.train_dataset = create_dataset(
                mode=Mode.TRAINING,
                inputs=self.train_data,
                targets=self.train_data_target,
                masks=self.train_data_mask,
                config=self.config,
                in_memory=self.use_in_memory,
                read_func=self.read_source_func,
                read_kwargs=self.read_kwargs,
                image_stack_loader=self.image_stack_loader,
                image_stack_loader_kwargs=self.image_stack_loader_kwargs,
            )
            # TODO: ugly, need to find a better solution
            self.stats = self.train_dataset.input_stats
            self.config.set_means_and_stds(
                self.train_dataset.input_stats.means,
                self.train_dataset.input_stats.stds,
                self.train_dataset.target_stats.means,
                self.train_dataset.target_stats.stds,
            )
            self.val_dataset = create_dataset(
                mode=Mode.VALIDATING,
                inputs=self.val_data,
                targets=self.val_data_target,
                config=self.config,
                in_memory=self.use_in_memory,
                read_func=self.read_source_func,
                read_kwargs=self.read_kwargs,
                image_stack_loader=self.image_stack_loader,
                image_stack_loader_kwargs=self.image_stack_loader_kwargs,
            )
        elif stage == "validate":
            self.val_dataset = create_dataset(
                mode=Mode.VALIDATING,
                inputs=self.val_data,
                targets=self.val_data_target,
                config=self.config,
                in_memory=self.use_in_memory,
                read_func=self.read_source_func,
                read_kwargs=self.read_kwargs,
                image_stack_loader=self.image_stack_loader,
                image_stack_loader_kwargs=self.image_stack_loader_kwargs,
            )
            self.stats = self.val_dataset.input_stats
        elif stage == "predict":
            self.predict_dataset = create_dataset(
                mode=Mode.PREDICTING,
                inputs=self.pred_data,
                targets=self.pred_data_target,
                config=self.config,
                in_memory=self.use_in_memory,
                read_func=self.read_source_func,
                read_kwargs=self.read_kwargs,
                image_stack_loader=self.image_stack_loader,
                image_stack_loader_kwargs=self.image_stack_loader_kwargs,
            )
            self.stats = self.predict_dataset.input_stats
        else:
            raise NotImplementedError(f"Stage {stage} not implemented")

    def _sampler(self, dataset: Literal["train", "val", "predict"]) -> Sampler | None:
        sampler: GroupedIndexSampler | None
        rng = np.random.default_rng(self.config.seed)
        if not self.use_in_memory and self.config.data_type == SupportedData.TIFF:
            match dataset:
                case "train":
                    ds = self.train_dataset
                case "val":
                    ds = self.val_dataset
                case "predict":
                    ds = self.predict_dataset
                case _:
                    raise (
                        f"Unrecognized dataset '{dataset}', should be one of 'train', "
                        "'val' or 'predict'."
                    )
            sampler = GroupedIndexSampler.from_dataset(ds, rng=rng)
        else:
            sampler = None
        return sampler

    def train_dataloader(self) -> DataLoader:
        """
        Create a dataloader for training.

        Returns
        -------
        DataLoader
            Training dataloader.
        """
        sampler = self._sampler("train")
        dataloader_params = copy.deepcopy(self.config.train_dataloader_params)
        # have to remove shuffle with sampler because of torch error:
        #   ValueError: sampler option is mutually exclusive with shuffle
        # TODO: there might be other parameters mutually exclusive with sampler
        if (sampler is not None) and ("shuffle" in dataloader_params):
            del dataloader_params["shuffle"]
        return DataLoader(
            self.train_dataset,
            batch_size=self.batch_size,
            collate_fn=default_collate,
            sampler=sampler,
            **dataloader_params,
        )

    def val_dataloader(self) -> DataLoader:
        """
        Create a dataloader for validation.

        Returns
        -------
        DataLoader
            Validation dataloader.
        """
        sampler = self._sampler("val")
        dataloader_params = copy.deepcopy(self.config.val_dataloader_params)
        if (sampler is not None) and ("shuffle" in dataloader_params):
            del dataloader_params["shuffle"]
        return DataLoader(
            self.val_dataset,
            batch_size=self.batch_size,
            collate_fn=default_collate,
            sampler=sampler,
            **dataloader_params,
        )

    def predict_dataloader(self) -> DataLoader:
        """
        Create a dataloader for prediction.

        Returns
        -------
        DataLoader
            Prediction dataloader.
        """
        return DataLoader(
            self.predict_dataset,
            batch_size=self.batch_size,
            collate_fn=default_collate,
            **self.config.test_dataloader_params,
        )

__init__(data_config, *, train_data=None, train_data_target=None, train_data_mask=None, val_data=None, val_data_target=None, pred_data=None, pred_data_target=None, read_source_func=None, read_kwargs=None, image_stack_loader=None, image_stack_loader_kwargs=None, extension_filter='', val_percentage=None, val_minimum_split=5, use_in_memory=True) #

__init__(data_config: NGDataConfig, *, train_data: InputType | None = None, train_data_target: InputType | None = None, val_data: InputType | None = None, val_data_target: InputType | None = None, pred_data: InputType | None = None, pred_data_target: InputType | None = None, extension_filter: str = '', val_percentage: float | None = None, val_minimum_split: int = 5, use_in_memory: bool = True) -> None
__init__(data_config: NGDataConfig, *, train_data: InputType | None = None, train_data_target: InputType | None = None, train_data_mask: InputType, val_data: InputType | None = None, val_data_target: InputType | None = None, pred_data: InputType | None = None, pred_data_target: InputType | None = None, extension_filter: str = '', val_percentage: float | None = None, val_minimum_split: int = 5, use_in_memory: bool = True) -> None
__init__(data_config: NGDataConfig, *, train_data: InputType | None = None, train_data_target: InputType | None = None, val_data: InputType | None = None, val_data_target: InputType | None = None, pred_data: InputType | None = None, pred_data_target: InputType | None = None, read_source_func: Callable, read_kwargs: dict[str, Any] | None = None, extension_filter: str = '', val_percentage: float | None = None, val_minimum_split: int = 5, use_in_memory: bool = True) -> None
__init__(data_config: NGDataConfig, *, train_data: InputType | None = None, train_data_target: InputType | None = None, train_data_mask: InputType, val_data: InputType | None = None, val_data_target: InputType | None = None, pred_data: InputType | None = None, pred_data_target: InputType | None = None, read_source_func: Callable, read_kwargs: dict[str, Any] | None = None, extension_filter: str = '', val_percentage: float | None = None, val_minimum_split: int = 5, use_in_memory: bool = True) -> None
__init__(data_config: NGDataConfig, *, train_data: Any | None = None, train_data_target: Any | None = None, val_data: Any | None = None, val_data_target: Any | None = None, pred_data: Any | None = None, pred_data_target: Any | None = None, image_stack_loader: ImageStackLoader, image_stack_loader_kwargs: dict[str, Any] | None = None, extension_filter: str = '', val_percentage: float | None = None, val_minimum_split: int = 5, use_in_memory: bool = True) -> None
__init__(data_config: NGDataConfig, *, train_data: Any | None = None, train_data_target: Any | None = None, train_data_mask: Any, val_data: Any | None = None, val_data_target: Any | None = None, pred_data: Any | None = None, pred_data_target: Any | None = None, image_stack_loader: ImageStackLoader, image_stack_loader_kwargs: dict[str, Any] | None = None, extension_filter: str = '', val_percentage: float | None = None, val_minimum_split: int = 5, use_in_memory: bool = True) -> None

Data module for Careamics dataset initialization.

Create a lightning datamodule that handles creating datasets for training, validation, and prediction.

Parameters:

Name Type Description Default
data_config NGDataConfig

Pydantic model for CAREamics data configuration.

required
train_data Optional[InputType]

Training data, can be a path to a folder, a list of paths, or a numpy array.

None
train_data_target Optional[InputType]

Training data target, can be a path to a folder, a list of paths, or a numpy array.

None
train_data_mask InputType (when filtering is needed)

Training data mask, can be a path to a folder, a list of paths, or a numpy array. Used for coordinate filtering. Only required when using coordinate-based patch filtering.

None
val_data Optional[InputType]

Validation data, can be a path to a folder, a list of paths, or a numpy array.

None
val_data_target Optional[InputType]

Validation data target, can be a path to a folder, a list of paths, or a numpy array.

None
pred_data Optional[InputType]

Prediction data, can be a path to a folder, a list of paths, or a numpy array.

None
pred_data_target Optional[InputType]

Prediction data target, can be a path to a folder, a list of paths, or a numpy array.

None
read_source_func Optional[Callable]

Function to read the source data, by default None. Only used for custom data type (see DataModel).

None
read_kwargs Optional[dict[str, Any]]

The kwargs for the read source function.

None
image_stack_loader Optional[ImageStackLoader]

The image stack loader.

None
image_stack_loader_kwargs Optional[dict[str, Any]]

The image stack loader kwargs.

None
extension_filter str

Filter for file extensions, by default "". Only used for custom data types (see DataModel).

''
val_percentage Optional[float]

Percentage of the training data to use for validation. Only used if val_data is None.

None
val_minimum_split int

Minimum number of patches or files to split from the training data for validation, by default 5. Only used if val_data is None.

5
use_in_memory bool

Load data in memory dataset if possible, by default True.

True
Source code in src/careamics/lightning/dataset_ng/data_module.py
def __init__(
    self,
    data_config: NGDataConfig,
    *,
    train_data: Any | None = None,
    train_data_target: Any | None = None,
    train_data_mask: Any | None = None,
    val_data: Any | None = None,
    val_data_target: Any | None = None,
    pred_data: Any | None = None,
    pred_data_target: Any | None = None,
    read_source_func: Callable | None = None,
    read_kwargs: dict[str, Any] | None = None,
    image_stack_loader: ImageStackLoader | None = None,
    image_stack_loader_kwargs: dict[str, Any] | None = None,
    extension_filter: str = "",
    val_percentage: float | None = None,
    val_minimum_split: int = 5,
    use_in_memory: bool = True,
) -> None:
    """
    Data module for Careamics dataset initialization.

    Create a lightning datamodule that handles creating datasets for training,
    validation, and prediction.

    Parameters
    ----------
    data_config : NGDataConfig
        Pydantic model for CAREamics data configuration.
    train_data : Optional[InputType]
        Training data, can be a path to a folder, a list of paths, or a numpy array.
    train_data_target : Optional[InputType]
        Training data target, can be a path to a folder,
        a list of paths, or a numpy array.
    train_data_mask : InputType (when filtering is needed)
        Training data mask, can be a path to a folder,
        a list of paths, or a numpy array. Used for coordinate filtering.
        Only required when using coordinate-based patch filtering.
    val_data : Optional[InputType]
        Validation data, can be a path to a folder,
        a list of paths, or a numpy array.
    val_data_target : Optional[InputType]
        Validation data target, can be a path to a folder,
        a list of paths, or a numpy array.
    pred_data : Optional[InputType]
        Prediction data, can be a path to a folder, a list of paths,
        or a numpy array.
    pred_data_target : Optional[InputType]
        Prediction data target, can be a path to a folder,
        a list of paths, or a numpy array.
    read_source_func : Optional[Callable]
        Function to read the source data, by default None. Only used for `custom`
        data type (see DataModel).
    read_kwargs : Optional[dict[str, Any]]
        The kwargs for the read source function.
    image_stack_loader : Optional[ImageStackLoader]
        The image stack loader.
    image_stack_loader_kwargs : Optional[dict[str, Any]]
        The image stack loader kwargs.
    extension_filter : str
        Filter for file extensions, by default "". Only used for `custom` data types
        (see DataModel).
    val_percentage : Optional[float]
        Percentage of the training data to use for validation. Only
        used if `val_data` is None.
    val_minimum_split : int
        Minimum number of patches or files to split from the training data for
        validation, by default 5. Only used if `val_data` is None.
    use_in_memory : bool
        Load data in memory dataset if possible, by default True.
    """
    super().__init__()

    if train_data is None and val_data is None and pred_data is None:
        raise ValueError(
            "At least one of train_data, val_data or pred_data must be provided."
        )
    elif train_data is None != val_data is None:
        raise ValueError(
            "If one of train_data or val_data is provided, both must be provided."
        )

    self.config: NGDataConfig = data_config
    self.data_type: str = data_config.data_type
    self.batch_size: int = data_config.batch_size
    self.use_in_memory: bool = use_in_memory

    self.extension_filter: str = (
        extension_filter  # list_files pulls the correct ext
    )
    self.read_source_func = read_source_func
    self.read_kwargs = read_kwargs
    self.image_stack_loader = image_stack_loader
    self.image_stack_loader_kwargs = image_stack_loader_kwargs

    # TODO: implement the validation split logic
    self.val_percentage = val_percentage
    self.val_minimum_split = val_minimum_split
    if self.val_percentage is not None:
        raise NotImplementedError("Validation split is not implemented.")

    custom_loader = self.image_stack_loader is not None
    self.train_data, self.train_data_target = initialize_data_pair(
        self.data_type,
        train_data,
        train_data_target,
        extension_filter,
        custom_loader,
    )
    self.train_data_mask, _ = initialize_data_pair(
        self.data_type, train_data_mask, None, extension_filter, custom_loader
    )

    self.val_data, self.val_data_target = initialize_data_pair(
        self.data_type, val_data, val_data_target, extension_filter, custom_loader
    )

    # The pred_data_target can be needed to count metrics on the prediction
    self.pred_data, self.pred_data_target = initialize_data_pair(
        self.data_type, pred_data, pred_data_target, extension_filter, custom_loader
    )

predict_dataloader() #

Create a dataloader for prediction.

Returns:

Type Description
DataLoader

Prediction dataloader.

Source code in src/careamics/lightning/dataset_ng/data_module.py
def predict_dataloader(self) -> DataLoader:
    """
    Create a dataloader for prediction.

    Returns
    -------
    DataLoader
        Prediction dataloader.
    """
    return DataLoader(
        self.predict_dataset,
        batch_size=self.batch_size,
        collate_fn=default_collate,
        **self.config.test_dataloader_params,
    )

setup(stage) #

Setup datasets.

Lightning hook that is called at the beginning of fit (train + validate), validate, test, or predict. Creates the datasets for a given stage.

Parameters:

Name Type Description Default
stage str

The stage to set up datasets for. Is either 'fit', 'validate', 'test', or 'predict'.

required

Raises:

Type Description
NotImplementedError

If stage is not one of "fit", "validate" or "predict".

Source code in src/careamics/lightning/dataset_ng/data_module.py
def setup(self, stage: str) -> None:
    """
    Setup datasets.

    Lightning hook that is called at the beginning of fit (train + validate),
    validate, test, or predict. Creates the datasets for a given stage.

    Parameters
    ----------
    stage : str
        The stage to set up datasets for.
        Is either 'fit', 'validate', 'test', or 'predict'.

    Raises
    ------
    NotImplementedError
        If stage is not one of "fit", "validate" or "predict".
    """
    if stage == "fit":
        self.train_dataset = create_dataset(
            mode=Mode.TRAINING,
            inputs=self.train_data,
            targets=self.train_data_target,
            masks=self.train_data_mask,
            config=self.config,
            in_memory=self.use_in_memory,
            read_func=self.read_source_func,
            read_kwargs=self.read_kwargs,
            image_stack_loader=self.image_stack_loader,
            image_stack_loader_kwargs=self.image_stack_loader_kwargs,
        )
        # TODO: ugly, need to find a better solution
        self.stats = self.train_dataset.input_stats
        self.config.set_means_and_stds(
            self.train_dataset.input_stats.means,
            self.train_dataset.input_stats.stds,
            self.train_dataset.target_stats.means,
            self.train_dataset.target_stats.stds,
        )
        self.val_dataset = create_dataset(
            mode=Mode.VALIDATING,
            inputs=self.val_data,
            targets=self.val_data_target,
            config=self.config,
            in_memory=self.use_in_memory,
            read_func=self.read_source_func,
            read_kwargs=self.read_kwargs,
            image_stack_loader=self.image_stack_loader,
            image_stack_loader_kwargs=self.image_stack_loader_kwargs,
        )
    elif stage == "validate":
        self.val_dataset = create_dataset(
            mode=Mode.VALIDATING,
            inputs=self.val_data,
            targets=self.val_data_target,
            config=self.config,
            in_memory=self.use_in_memory,
            read_func=self.read_source_func,
            read_kwargs=self.read_kwargs,
            image_stack_loader=self.image_stack_loader,
            image_stack_loader_kwargs=self.image_stack_loader_kwargs,
        )
        self.stats = self.val_dataset.input_stats
    elif stage == "predict":
        self.predict_dataset = create_dataset(
            mode=Mode.PREDICTING,
            inputs=self.pred_data,
            targets=self.pred_data_target,
            config=self.config,
            in_memory=self.use_in_memory,
            read_func=self.read_source_func,
            read_kwargs=self.read_kwargs,
            image_stack_loader=self.image_stack_loader,
            image_stack_loader_kwargs=self.image_stack_loader_kwargs,
        )
        self.stats = self.predict_dataset.input_stats
    else:
        raise NotImplementedError(f"Stage {stage} not implemented")

train_dataloader() #

Create a dataloader for training.

Returns:

Type Description
DataLoader

Training dataloader.

Source code in src/careamics/lightning/dataset_ng/data_module.py
def train_dataloader(self) -> DataLoader:
    """
    Create a dataloader for training.

    Returns
    -------
    DataLoader
        Training dataloader.
    """
    sampler = self._sampler("train")
    dataloader_params = copy.deepcopy(self.config.train_dataloader_params)
    # have to remove shuffle with sampler because of torch error:
    #   ValueError: sampler option is mutually exclusive with shuffle
    # TODO: there might be other parameters mutually exclusive with sampler
    if (sampler is not None) and ("shuffle" in dataloader_params):
        del dataloader_params["shuffle"]
    return DataLoader(
        self.train_dataset,
        batch_size=self.batch_size,
        collate_fn=default_collate,
        sampler=sampler,
        **dataloader_params,
    )

val_dataloader() #

Create a dataloader for validation.

Returns:

Type Description
DataLoader

Validation dataloader.

Source code in src/careamics/lightning/dataset_ng/data_module.py
def val_dataloader(self) -> DataLoader:
    """
    Create a dataloader for validation.

    Returns
    -------
    DataLoader
        Validation dataloader.
    """
    sampler = self._sampler("val")
    dataloader_params = copy.deepcopy(self.config.val_dataloader_params)
    if (sampler is not None) and ("shuffle" in dataloader_params):
        del dataloader_params["shuffle"]
    return DataLoader(
        self.val_dataset,
        batch_size=self.batch_size,
        collate_fn=default_collate,
        sampler=sampler,
        **dataloader_params,
    )