Skip to content

data_model

Data configuration.

Float = Annotated[float, PlainSerializer(np_float_to_scientific_str, return_type=str)] module-attribute #

Annotated float type, used to serialize floats to strings.

DataConfig #

Bases: BaseModel

Data configuration.

If std is specified, mean must be specified as well. Note that setting the std first and then the mean (if they were both None before) will raise a validation error. Prefer instead set_mean_and_std to set both at once. Means and stds are expected to be lists of floats, one for each channel. For supervised tasks, the mean and std of the target could be different from the input data.

All supported transforms are defined in the SupportedTransform enum.

Examples:

Minimum example:

>>> data = DataConfig(
...     data_type="array", # defined in SupportedData
...     patch_size=[128, 128],
...     batch_size=4,
...     axes="YX"
... )

To change the image_means and image_stds of the data:

>>> data.set_means_and_stds(image_means=[214.3], image_stds=[84.5])

One can pass also a list of transformations, by keyword, using the SupportedTransform value:

>>> from careamics.config.support import SupportedTransform
>>> data = DataConfig(
...     data_type="tiff",
...     patch_size=[128, 128],
...     batch_size=4,
...     axes="YX",
...     transforms=[
...         {
...             "name": "XYFlip",
...         }
...     ]
... )
Source code in src/careamics/config/data_model.py
 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
class DataConfig(BaseModel):
    """
    Data configuration.

    If std is specified, mean must be specified as well. Note that setting the std first
    and then the mean (if they were both `None` before) will raise a validation error.
    Prefer instead `set_mean_and_std` to set both at once. Means and stds are expected
    to be lists of floats, one for each channel. For supervised tasks, the mean and std
    of the target could be different from the input data.

    All supported transforms are defined in the SupportedTransform enum.

    Examples
    --------
    Minimum example:

    >>> data = DataConfig(
    ...     data_type="array", # defined in SupportedData
    ...     patch_size=[128, 128],
    ...     batch_size=4,
    ...     axes="YX"
    ... )

    To change the image_means and image_stds of the data:
    >>> data.set_means_and_stds(image_means=[214.3], image_stds=[84.5])

    One can pass also a list of transformations, by keyword, using the
    SupportedTransform value:
    >>> from careamics.config.support import SupportedTransform
    >>> data = DataConfig(
    ...     data_type="tiff",
    ...     patch_size=[128, 128],
    ...     batch_size=4,
    ...     axes="YX",
    ...     transforms=[
    ...         {
    ...             "name": "XYFlip",
    ...         }
    ...     ]
    ... )
    """

    # Pydantic class configuration
    model_config = ConfigDict(
        validate_assignment=True,
    )

    # Dataset configuration
    data_type: Literal["array", "tiff", "custom"]
    """Type of input data, numpy.ndarray (array) or paths (tiff and custom), as defined
    in SupportedData."""

    axes: str
    """Axes of the data, as defined in SupportedAxes."""

    patch_size: Union[list[int]] = Field(..., min_length=2, max_length=3)
    """Patch size, as used during training."""

    batch_size: int = Field(default=1, ge=1, validate_default=True)
    """Batch size for training."""

    # Optional fields
    image_means: Optional[list[Float]] = Field(
        default=None, min_length=0, max_length=32
    )
    """Means of the data across channels, used for normalization."""

    image_stds: Optional[list[Float]] = Field(default=None, min_length=0, max_length=32)
    """Standard deviations of the data across channels, used for normalization."""

    target_means: Optional[list[Float]] = Field(
        default=None, min_length=0, max_length=32
    )
    """Means of the target data across channels, used for normalization."""

    target_stds: Optional[list[Float]] = Field(
        default=None, min_length=0, max_length=32
    )
    """Standard deviations of the target data across channels, used for
    normalization."""

    transforms: list[TRANSFORMS_UNION] = Field(
        default=[
            {
                "name": SupportedTransform.XY_FLIP.value,
            },
            {
                "name": SupportedTransform.XY_RANDOM_ROTATE90.value,
            },
            {
                "name": SupportedTransform.N2V_MANIPULATE.value,
            },
        ],
        validate_default=True,
    )
    """List of transformations to apply to the data, available transforms are defined
    in SupportedTransform. The default values are set for Noise2Void."""

    dataloader_params: Optional[dict] = None
    """Dictionary of PyTorch dataloader parameters."""

    @field_validator("patch_size")
    @classmethod
    def all_elements_power_of_2_minimum_8(
        cls, patch_list: Union[list[int]]
    ) -> Union[list[int]]:
        """
        Validate patch size.

        Patch size must be powers of 2 and minimum 8.

        Parameters
        ----------
        patch_list : list of int
            Patch size.

        Returns
        -------
        list of int
            Validated patch size.

        Raises
        ------
        ValueError
            If the patch size is smaller than 8.
        ValueError
            If the patch size is not a power of 2.
        """
        patch_size_ge_than_8_power_of_2(patch_list)

        return patch_list

    @field_validator("axes")
    @classmethod
    def axes_valid(cls, axes: str) -> str:
        """
        Validate axes.

        Axes must:
        - be a combination of 'STCZYX'
        - not contain duplicates
        - contain at least 2 contiguous axes: X and Y
        - contain at most 4 axes
        - not contain both S and T axes

        Parameters
        ----------
        axes : str
            Axes to validate.

        Returns
        -------
        str
            Validated axes.

        Raises
        ------
        ValueError
            If axes are not valid.
        """
        # Validate axes
        check_axes_validity(axes)

        return axes

    @field_validator("transforms")
    @classmethod
    def validate_prediction_transforms(
        cls, transforms: list[TRANSFORMS_UNION]
    ) -> list[TRANSFORMS_UNION]:
        """
        Validate N2VManipulate transform position in the transform list.

        Parameters
        ----------
        transforms : list[Transformations_Union]
            Transforms.

        Returns
        -------
        list of transforms
            Validated transforms.

        Raises
        ------
        ValueError
            If multiple instances of N2VManipulate are found.
        """
        transform_list = [t.name for t in transforms]

        if SupportedTransform.N2V_MANIPULATE in transform_list:
            # multiple N2V_MANIPULATE
            if transform_list.count(SupportedTransform.N2V_MANIPULATE.value) > 1:
                raise ValueError(
                    f"Multiple instances of "
                    f"{SupportedTransform.N2V_MANIPULATE} transforms "
                    f"are not allowed."
                )

            # N2V_MANIPULATE not the last transform
            elif transform_list[-1] != SupportedTransform.N2V_MANIPULATE:
                index = transform_list.index(SupportedTransform.N2V_MANIPULATE.value)
                transform = transforms.pop(index)
                transforms.append(transform)

        return transforms

    @model_validator(mode="after")
    def std_only_with_mean(self: Self) -> Self:
        """
        Check that mean and std are either both None, or both specified.

        Returns
        -------
        Self
            Validated data model.

        Raises
        ------
        ValueError
            If std is not None and mean is None.
        """
        # check that mean and std are either both None, or both specified
        if (self.image_means and not self.image_stds) or (
            self.image_stds and not self.image_means
        ):
            raise ValueError(
                "Mean and std must be either both None, or both specified."
            )

        elif (self.image_means is not None and self.image_stds is not None) and (
            len(self.image_means) != len(self.image_stds)
        ):
            raise ValueError("Mean and std must be specified for each input channel.")

        if (self.target_means and not self.target_stds) or (
            self.target_stds and not self.target_means
        ):
            raise ValueError(
                "Mean and std must be either both None, or both specified "
            )

        elif self.target_means is not None and self.target_stds is not None:
            if len(self.target_means) != len(self.target_stds):
                raise ValueError(
                    "Mean and std must be either both None, or both specified for each "
                    "target channel."
                )

        return self

    @model_validator(mode="after")
    def validate_dimensions(self: Self) -> Self:
        """
        Validate 2D/3D dimensions between axes, patch size and transforms.

        Returns
        -------
        Self
            Validated data model.

        Raises
        ------
        ValueError
            If the transforms are not valid.
        """
        if "Z" in self.axes:
            if len(self.patch_size) != 3:
                raise ValueError(
                    f"Patch size must have 3 dimensions if the data is 3D "
                    f"({self.axes})."
                )

        else:
            if len(self.patch_size) != 2:
                raise ValueError(
                    f"Patch size must have 3 dimensions if the data is 3D "
                    f"({self.axes})."
                )

        return self

    def __str__(self) -> str:
        """
        Pretty string reprensenting the configuration.

        Returns
        -------
        str
            Pretty string.
        """
        return pformat(self.model_dump())

    def _update(self, **kwargs: Any) -> None:
        """
        Update multiple arguments at once.

        Parameters
        ----------
        **kwargs : Any
            Keyword arguments to update.
        """
        self.__dict__.update(kwargs)
        self.__class__.model_validate(self.__dict__)

    def has_n2v_manipulate(self) -> bool:
        """
        Check if the transforms contain N2VManipulate.

        Returns
        -------
        bool
            True if the transforms contain N2VManipulate, False otherwise.
        """
        return any(
            transform.name == SupportedTransform.N2V_MANIPULATE.value
            for transform in self.transforms
        )

    def add_n2v_manipulate(self) -> None:
        """Add N2VManipulate to the transforms."""
        if not self.has_n2v_manipulate():
            self.transforms.append(
                N2VManipulateModel(name=SupportedTransform.N2V_MANIPULATE.value)
            )

    def remove_n2v_manipulate(self) -> None:
        """Remove N2VManipulate from the transforms."""
        if self.has_n2v_manipulate():
            self.transforms.pop(-1)

    def set_means_and_stds(
        self,
        image_means: Union[NDArray, tuple, list, None],
        image_stds: Union[NDArray, tuple, list, None],
        target_means: Optional[Union[NDArray, tuple, list, None]] = None,
        target_stds: Optional[Union[NDArray, tuple, list, None]] = None,
    ) -> None:
        """
        Set mean and standard deviation of the data across channels.

        This method should be used instead setting the fields directly, as it would
        otherwise trigger a validation error.

        Parameters
        ----------
        image_means : numpy.ndarray, tuple or list
            Mean values for normalization.
        image_stds : numpy.ndarray, tuple or list
            Standard deviation values for normalization.
        target_means : numpy.ndarray, tuple or list, optional
            Target mean values for normalization, by default ().
        target_stds : numpy.ndarray, tuple or list, optional
            Target standard deviation values for normalization, by default ().
        """
        # make sure we pass a list
        if image_means is not None:
            image_means = list(image_means)
        if image_stds is not None:
            image_stds = list(image_stds)
        if target_means is not None:
            target_means = list(target_means)
        if target_stds is not None:
            target_stds = list(target_stds)

        self._update(
            image_means=image_means,
            image_stds=image_stds,
            target_means=target_means,
            target_stds=target_stds,
        )

    def set_3D(self, axes: str, patch_size: list[int]) -> None:
        """
        Set 3D parameters.

        Parameters
        ----------
        axes : str
            Axes.
        patch_size : list of int
            Patch size.
        """
        self._update(axes=axes, patch_size=patch_size)

    def set_N2V2(self, use_n2v2: bool) -> None:
        """
        Set N2V2.

        Parameters
        ----------
        use_n2v2 : bool
            Whether to use N2V2.

        Raises
        ------
        ValueError
            If the N2V pixel manipulate transform is not found in the transforms.
        """
        if use_n2v2:
            self.set_N2V2_strategy("median")
        else:
            self.set_N2V2_strategy("uniform")

    def set_N2V2_strategy(self, strategy: Literal["uniform", "median"]) -> None:
        """
        Set N2V2 strategy.

        Parameters
        ----------
        strategy : Literal["uniform", "median"]
            Strategy to use for N2V2.

        Raises
        ------
        ValueError
            If the N2V pixel manipulate transform is not found in the transforms.
        """
        found_n2v = False

        for transform in self.transforms:
            if transform.name == SupportedTransform.N2V_MANIPULATE.value:
                transform.strategy = strategy
                found_n2v = True

        if not found_n2v:
            transforms = [t.name for t in self.transforms]
            raise ValueError(
                f"N2V_Manipulate transform not found in the transforms list "
                f"({transforms})."
            )

    def set_structN2V_mask(
        self, mask_axis: Literal["horizontal", "vertical", "none"], mask_span: int
    ) -> None:
        """
        Set structN2V mask parameters.

        Setting `mask_axis` to `none` will disable structN2V.

        Parameters
        ----------
        mask_axis : Literal["horizontal", "vertical", "none"]
            Axis along which to apply the mask. `none` will disable structN2V.
        mask_span : int
            Total span of the mask in pixels.

        Raises
        ------
        ValueError
            If the N2V pixel manipulate transform is not found in the transforms.
        """
        found_n2v = False

        for transform in self.transforms:
            if transform.name == SupportedTransform.N2V_MANIPULATE.value:
                transform.struct_mask_axis = mask_axis
                transform.struct_mask_span = mask_span
                found_n2v = True

        if not found_n2v:
            transforms = [t.name for t in self.transforms]
            raise ValueError(
                f"N2V pixel manipulate transform not found in the transforms "
                f"({transforms})."
            )

axes: str instance-attribute #

Axes of the data, as defined in SupportedAxes.

batch_size: int = Field(default=1, ge=1, validate_default=True) class-attribute instance-attribute #

Batch size for training.

data_type: Literal['array', 'tiff', 'custom'] instance-attribute #

Type of input data, numpy.ndarray (array) or paths (tiff and custom), as defined in SupportedData.

dataloader_params: Optional[dict] = None class-attribute instance-attribute #

Dictionary of PyTorch dataloader parameters.

image_means: Optional[list[Float]] = Field(default=None, min_length=0, max_length=32) class-attribute instance-attribute #

Means of the data across channels, used for normalization.

image_stds: Optional[list[Float]] = Field(default=None, min_length=0, max_length=32) class-attribute instance-attribute #

Standard deviations of the data across channels, used for normalization.

patch_size: Union[list[int]] = Field(..., min_length=2, max_length=3) class-attribute instance-attribute #

Patch size, as used during training.

target_means: Optional[list[Float]] = Field(default=None, min_length=0, max_length=32) class-attribute instance-attribute #

Means of the target data across channels, used for normalization.

target_stds: Optional[list[Float]] = Field(default=None, min_length=0, max_length=32) class-attribute instance-attribute #

Standard deviations of the target data across channels, used for normalization.

transforms: list[TRANSFORMS_UNION] = Field(default=[{'name': SupportedTransform.XY_FLIP.value}, {'name': SupportedTransform.XY_RANDOM_ROTATE90.value}, {'name': SupportedTransform.N2V_MANIPULATE.value}], validate_default=True) class-attribute instance-attribute #

List of transformations to apply to the data, available transforms are defined in SupportedTransform. The default values are set for Noise2Void.

__str__() #

Pretty string reprensenting the configuration.

Returns:

Type Description
str

Pretty string.

Source code in src/careamics/config/data_model.py
def __str__(self) -> str:
    """
    Pretty string reprensenting the configuration.

    Returns
    -------
    str
        Pretty string.
    """
    return pformat(self.model_dump())

add_n2v_manipulate() #

Add N2VManipulate to the transforms.

Source code in src/careamics/config/data_model.py
def add_n2v_manipulate(self) -> None:
    """Add N2VManipulate to the transforms."""
    if not self.has_n2v_manipulate():
        self.transforms.append(
            N2VManipulateModel(name=SupportedTransform.N2V_MANIPULATE.value)
        )

all_elements_power_of_2_minimum_8(patch_list) classmethod #

Validate patch size.

Patch size must be powers of 2 and minimum 8.

Parameters:

Name Type Description Default
patch_list list of int

Patch size.

required

Returns:

Type Description
list of int

Validated patch size.

Raises:

Type Description
ValueError

If the patch size is smaller than 8.

ValueError

If the patch size is not a power of 2.

Source code in src/careamics/config/data_model.py
@field_validator("patch_size")
@classmethod
def all_elements_power_of_2_minimum_8(
    cls, patch_list: Union[list[int]]
) -> Union[list[int]]:
    """
    Validate patch size.

    Patch size must be powers of 2 and minimum 8.

    Parameters
    ----------
    patch_list : list of int
        Patch size.

    Returns
    -------
    list of int
        Validated patch size.

    Raises
    ------
    ValueError
        If the patch size is smaller than 8.
    ValueError
        If the patch size is not a power of 2.
    """
    patch_size_ge_than_8_power_of_2(patch_list)

    return patch_list

axes_valid(axes) classmethod #

Validate axes.

Axes must: - be a combination of 'STCZYX' - not contain duplicates - contain at least 2 contiguous axes: X and Y - contain at most 4 axes - not contain both S and T axes

Parameters:

Name Type Description Default
axes str

Axes to validate.

required

Returns:

Type Description
str

Validated axes.

Raises:

Type Description
ValueError

If axes are not valid.

Source code in src/careamics/config/data_model.py
@field_validator("axes")
@classmethod
def axes_valid(cls, axes: str) -> str:
    """
    Validate axes.

    Axes must:
    - be a combination of 'STCZYX'
    - not contain duplicates
    - contain at least 2 contiguous axes: X and Y
    - contain at most 4 axes
    - not contain both S and T axes

    Parameters
    ----------
    axes : str
        Axes to validate.

    Returns
    -------
    str
        Validated axes.

    Raises
    ------
    ValueError
        If axes are not valid.
    """
    # Validate axes
    check_axes_validity(axes)

    return axes

has_n2v_manipulate() #

Check if the transforms contain N2VManipulate.

Returns:

Type Description
bool

True if the transforms contain N2VManipulate, False otherwise.

Source code in src/careamics/config/data_model.py
def has_n2v_manipulate(self) -> bool:
    """
    Check if the transforms contain N2VManipulate.

    Returns
    -------
    bool
        True if the transforms contain N2VManipulate, False otherwise.
    """
    return any(
        transform.name == SupportedTransform.N2V_MANIPULATE.value
        for transform in self.transforms
    )

remove_n2v_manipulate() #

Remove N2VManipulate from the transforms.

Source code in src/careamics/config/data_model.py
def remove_n2v_manipulate(self) -> None:
    """Remove N2VManipulate from the transforms."""
    if self.has_n2v_manipulate():
        self.transforms.pop(-1)

set_3D(axes, patch_size) #

Set 3D parameters.

Parameters:

Name Type Description Default
axes str

Axes.

required
patch_size list of int

Patch size.

required
Source code in src/careamics/config/data_model.py
def set_3D(self, axes: str, patch_size: list[int]) -> None:
    """
    Set 3D parameters.

    Parameters
    ----------
    axes : str
        Axes.
    patch_size : list of int
        Patch size.
    """
    self._update(axes=axes, patch_size=patch_size)

set_N2V2(use_n2v2) #

Set N2V2.

Parameters:

Name Type Description Default
use_n2v2 bool

Whether to use N2V2.

required

Raises:

Type Description
ValueError

If the N2V pixel manipulate transform is not found in the transforms.

Source code in src/careamics/config/data_model.py
def set_N2V2(self, use_n2v2: bool) -> None:
    """
    Set N2V2.

    Parameters
    ----------
    use_n2v2 : bool
        Whether to use N2V2.

    Raises
    ------
    ValueError
        If the N2V pixel manipulate transform is not found in the transforms.
    """
    if use_n2v2:
        self.set_N2V2_strategy("median")
    else:
        self.set_N2V2_strategy("uniform")

set_N2V2_strategy(strategy) #

Set N2V2 strategy.

Parameters:

Name Type Description Default
strategy Literal['uniform', 'median']

Strategy to use for N2V2.

required

Raises:

Type Description
ValueError

If the N2V pixel manipulate transform is not found in the transforms.

Source code in src/careamics/config/data_model.py
def set_N2V2_strategy(self, strategy: Literal["uniform", "median"]) -> None:
    """
    Set N2V2 strategy.

    Parameters
    ----------
    strategy : Literal["uniform", "median"]
        Strategy to use for N2V2.

    Raises
    ------
    ValueError
        If the N2V pixel manipulate transform is not found in the transforms.
    """
    found_n2v = False

    for transform in self.transforms:
        if transform.name == SupportedTransform.N2V_MANIPULATE.value:
            transform.strategy = strategy
            found_n2v = True

    if not found_n2v:
        transforms = [t.name for t in self.transforms]
        raise ValueError(
            f"N2V_Manipulate transform not found in the transforms list "
            f"({transforms})."
        )

set_means_and_stds(image_means, image_stds, target_means=None, target_stds=None) #

Set mean and standard deviation of the data across channels.

This method should be used instead setting the fields directly, as it would otherwise trigger a validation error.

Parameters:

Name Type Description Default
image_means (ndarray, tuple or list)

Mean values for normalization.

required
image_stds (ndarray, tuple or list)

Standard deviation values for normalization.

required
target_means (ndarray, tuple or list)

Target mean values for normalization, by default ().

None
target_stds (ndarray, tuple or list)

Target standard deviation values for normalization, by default ().

None
Source code in src/careamics/config/data_model.py
def set_means_and_stds(
    self,
    image_means: Union[NDArray, tuple, list, None],
    image_stds: Union[NDArray, tuple, list, None],
    target_means: Optional[Union[NDArray, tuple, list, None]] = None,
    target_stds: Optional[Union[NDArray, tuple, list, None]] = None,
) -> None:
    """
    Set mean and standard deviation of the data across channels.

    This method should be used instead setting the fields directly, as it would
    otherwise trigger a validation error.

    Parameters
    ----------
    image_means : numpy.ndarray, tuple or list
        Mean values for normalization.
    image_stds : numpy.ndarray, tuple or list
        Standard deviation values for normalization.
    target_means : numpy.ndarray, tuple or list, optional
        Target mean values for normalization, by default ().
    target_stds : numpy.ndarray, tuple or list, optional
        Target standard deviation values for normalization, by default ().
    """
    # make sure we pass a list
    if image_means is not None:
        image_means = list(image_means)
    if image_stds is not None:
        image_stds = list(image_stds)
    if target_means is not None:
        target_means = list(target_means)
    if target_stds is not None:
        target_stds = list(target_stds)

    self._update(
        image_means=image_means,
        image_stds=image_stds,
        target_means=target_means,
        target_stds=target_stds,
    )

set_structN2V_mask(mask_axis, mask_span) #

Set structN2V mask parameters.

Setting mask_axis to none will disable structN2V.

Parameters:

Name Type Description Default
mask_axis Literal['horizontal', 'vertical', 'none']

Axis along which to apply the mask. none will disable structN2V.

required
mask_span int

Total span of the mask in pixels.

required

Raises:

Type Description
ValueError

If the N2V pixel manipulate transform is not found in the transforms.

Source code in src/careamics/config/data_model.py
def set_structN2V_mask(
    self, mask_axis: Literal["horizontal", "vertical", "none"], mask_span: int
) -> None:
    """
    Set structN2V mask parameters.

    Setting `mask_axis` to `none` will disable structN2V.

    Parameters
    ----------
    mask_axis : Literal["horizontal", "vertical", "none"]
        Axis along which to apply the mask. `none` will disable structN2V.
    mask_span : int
        Total span of the mask in pixels.

    Raises
    ------
    ValueError
        If the N2V pixel manipulate transform is not found in the transforms.
    """
    found_n2v = False

    for transform in self.transforms:
        if transform.name == SupportedTransform.N2V_MANIPULATE.value:
            transform.struct_mask_axis = mask_axis
            transform.struct_mask_span = mask_span
            found_n2v = True

    if not found_n2v:
        transforms = [t.name for t in self.transforms]
        raise ValueError(
            f"N2V pixel manipulate transform not found in the transforms "
            f"({transforms})."
        )

std_only_with_mean() #

Check that mean and std are either both None, or both specified.

Returns:

Type Description
Self

Validated data model.

Raises:

Type Description
ValueError

If std is not None and mean is None.

Source code in src/careamics/config/data_model.py
@model_validator(mode="after")
def std_only_with_mean(self: Self) -> Self:
    """
    Check that mean and std are either both None, or both specified.

    Returns
    -------
    Self
        Validated data model.

    Raises
    ------
    ValueError
        If std is not None and mean is None.
    """
    # check that mean and std are either both None, or both specified
    if (self.image_means and not self.image_stds) or (
        self.image_stds and not self.image_means
    ):
        raise ValueError(
            "Mean and std must be either both None, or both specified."
        )

    elif (self.image_means is not None and self.image_stds is not None) and (
        len(self.image_means) != len(self.image_stds)
    ):
        raise ValueError("Mean and std must be specified for each input channel.")

    if (self.target_means and not self.target_stds) or (
        self.target_stds and not self.target_means
    ):
        raise ValueError(
            "Mean and std must be either both None, or both specified "
        )

    elif self.target_means is not None and self.target_stds is not None:
        if len(self.target_means) != len(self.target_stds):
            raise ValueError(
                "Mean and std must be either both None, or both specified for each "
                "target channel."
            )

    return self

validate_dimensions() #

Validate 2D/3D dimensions between axes, patch size and transforms.

Returns:

Type Description
Self

Validated data model.

Raises:

Type Description
ValueError

If the transforms are not valid.

Source code in src/careamics/config/data_model.py
@model_validator(mode="after")
def validate_dimensions(self: Self) -> Self:
    """
    Validate 2D/3D dimensions between axes, patch size and transforms.

    Returns
    -------
    Self
        Validated data model.

    Raises
    ------
    ValueError
        If the transforms are not valid.
    """
    if "Z" in self.axes:
        if len(self.patch_size) != 3:
            raise ValueError(
                f"Patch size must have 3 dimensions if the data is 3D "
                f"({self.axes})."
            )

    else:
        if len(self.patch_size) != 2:
            raise ValueError(
                f"Patch size must have 3 dimensions if the data is 3D "
                f"({self.axes})."
            )

    return self

validate_prediction_transforms(transforms) classmethod #

Validate N2VManipulate transform position in the transform list.

Parameters:

Name Type Description Default
transforms list[Transformations_Union]

Transforms.

required

Returns:

Type Description
list of transforms

Validated transforms.

Raises:

Type Description
ValueError

If multiple instances of N2VManipulate are found.

Source code in src/careamics/config/data_model.py
@field_validator("transforms")
@classmethod
def validate_prediction_transforms(
    cls, transforms: list[TRANSFORMS_UNION]
) -> list[TRANSFORMS_UNION]:
    """
    Validate N2VManipulate transform position in the transform list.

    Parameters
    ----------
    transforms : list[Transformations_Union]
        Transforms.

    Returns
    -------
    list of transforms
        Validated transforms.

    Raises
    ------
    ValueError
        If multiple instances of N2VManipulate are found.
    """
    transform_list = [t.name for t in transforms]

    if SupportedTransform.N2V_MANIPULATE in transform_list:
        # multiple N2V_MANIPULATE
        if transform_list.count(SupportedTransform.N2V_MANIPULATE.value) > 1:
            raise ValueError(
                f"Multiple instances of "
                f"{SupportedTransform.N2V_MANIPULATE} transforms "
                f"are not allowed."
            )

        # N2V_MANIPULATE not the last transform
        elif transform_list[-1] != SupportedTransform.N2V_MANIPULATE:
            index = transform_list.index(SupportedTransform.N2V_MANIPULATE.value)
            transform = transforms.pop(index)
            transforms.append(transform)

    return transforms

np_float_to_scientific_str(x) #

Return a string scientific representation of a float.

In particular, this method is used to serialize floats to strings, allowing numpy.float32 to be passed in the Pydantic model and written to a yaml file as str.

Parameters:

Name Type Description Default
x float

Input value.

required

Returns:

Type Description
str

Scientific string representation of the input value.

Source code in src/careamics/config/data_model.py
def np_float_to_scientific_str(x: float) -> str:
    """Return a string scientific representation of a float.

    In particular, this method is used to serialize floats to strings, allowing
    numpy.float32 to be passed in the Pydantic model and written to a yaml file as str.

    Parameters
    ----------
    x : float
        Input value.

    Returns
    -------
    str
        Scientific string representation of the input value.
    """
    return np.format_float_scientific(x, precision=7)