careamics 0.1.0rc1__py3-none-any.whl → 0.1.0rc3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of careamics might be problematic. Click here for more details.

Files changed (132) hide show
  1. careamics/__init__.py +14 -4
  2. careamics/callbacks/__init__.py +6 -0
  3. careamics/callbacks/hyperparameters_callback.py +42 -0
  4. careamics/callbacks/progress_bar_callback.py +57 -0
  5. careamics/careamist.py +761 -0
  6. careamics/config/__init__.py +27 -3
  7. careamics/config/algorithm_model.py +167 -0
  8. careamics/config/architectures/__init__.py +17 -0
  9. careamics/config/architectures/architecture_model.py +29 -0
  10. careamics/config/architectures/custom_model.py +150 -0
  11. careamics/config/architectures/register_model.py +101 -0
  12. careamics/config/architectures/unet_model.py +96 -0
  13. careamics/config/architectures/vae_model.py +39 -0
  14. careamics/config/callback_model.py +92 -0
  15. careamics/config/configuration_factory.py +460 -0
  16. careamics/config/configuration_model.py +596 -0
  17. careamics/config/data_model.py +555 -0
  18. careamics/config/inference_model.py +283 -0
  19. careamics/config/noise_models.py +162 -0
  20. careamics/config/optimizer_models.py +181 -0
  21. careamics/config/references/__init__.py +45 -0
  22. careamics/config/references/algorithm_descriptions.py +131 -0
  23. careamics/config/references/references.py +38 -0
  24. careamics/config/support/__init__.py +33 -0
  25. careamics/config/support/supported_activations.py +24 -0
  26. careamics/config/support/supported_algorithms.py +18 -0
  27. careamics/config/support/supported_architectures.py +18 -0
  28. careamics/config/support/supported_data.py +82 -0
  29. careamics/{dataset/extraction_strategy.py → config/support/supported_extraction_strategies.py} +5 -2
  30. careamics/config/support/supported_loggers.py +8 -0
  31. careamics/config/support/supported_losses.py +25 -0
  32. careamics/config/support/supported_optimizers.py +55 -0
  33. careamics/config/support/supported_pixel_manipulations.py +15 -0
  34. careamics/config/support/supported_struct_axis.py +19 -0
  35. careamics/config/support/supported_transforms.py +23 -0
  36. careamics/config/tile_information.py +104 -0
  37. careamics/config/training_model.py +65 -0
  38. careamics/config/transformations/__init__.py +14 -0
  39. careamics/config/transformations/n2v_manipulate_model.py +63 -0
  40. careamics/config/transformations/nd_flip_model.py +32 -0
  41. careamics/config/transformations/normalize_model.py +31 -0
  42. careamics/config/transformations/transform_model.py +44 -0
  43. careamics/config/transformations/xy_random_rotate90_model.py +29 -0
  44. careamics/config/validators/__init__.py +5 -0
  45. careamics/config/validators/validator_utils.py +100 -0
  46. careamics/conftest.py +26 -0
  47. careamics/dataset/__init__.py +5 -0
  48. careamics/dataset/dataset_utils/__init__.py +19 -0
  49. careamics/dataset/dataset_utils/dataset_utils.py +100 -0
  50. careamics/dataset/dataset_utils/file_utils.py +140 -0
  51. careamics/dataset/dataset_utils/read_tiff.py +61 -0
  52. careamics/dataset/dataset_utils/read_utils.py +25 -0
  53. careamics/dataset/dataset_utils/read_zarr.py +56 -0
  54. careamics/dataset/in_memory_dataset.py +321 -131
  55. careamics/dataset/iterable_dataset.py +416 -0
  56. careamics/dataset/patching/__init__.py +8 -0
  57. careamics/dataset/patching/patch_transform.py +44 -0
  58. careamics/dataset/patching/patching.py +212 -0
  59. careamics/dataset/patching/random_patching.py +190 -0
  60. careamics/dataset/patching/sequential_patching.py +206 -0
  61. careamics/dataset/patching/tiled_patching.py +158 -0
  62. careamics/dataset/patching/validate_patch_dimension.py +60 -0
  63. careamics/dataset/zarr_dataset.py +149 -0
  64. careamics/lightning_datamodule.py +665 -0
  65. careamics/lightning_module.py +292 -0
  66. careamics/lightning_prediction_datamodule.py +390 -0
  67. careamics/lightning_prediction_loop.py +116 -0
  68. careamics/losses/__init__.py +4 -1
  69. careamics/losses/loss_factory.py +24 -13
  70. careamics/losses/losses.py +65 -5
  71. careamics/losses/noise_model_factory.py +40 -0
  72. careamics/losses/noise_models.py +524 -0
  73. careamics/model_io/__init__.py +8 -0
  74. careamics/model_io/bioimage/__init__.py +11 -0
  75. careamics/model_io/bioimage/_readme_factory.py +120 -0
  76. careamics/model_io/bioimage/bioimage_utils.py +48 -0
  77. careamics/model_io/bioimage/model_description.py +318 -0
  78. careamics/model_io/bmz_io.py +231 -0
  79. careamics/model_io/model_io_utils.py +80 -0
  80. careamics/models/__init__.py +4 -1
  81. careamics/models/activation.py +35 -0
  82. careamics/models/layers.py +244 -0
  83. careamics/models/model_factory.py +21 -202
  84. careamics/models/unet.py +46 -20
  85. careamics/prediction/__init__.py +1 -3
  86. careamics/prediction/stitch_prediction.py +73 -0
  87. careamics/transforms/__init__.py +41 -0
  88. careamics/transforms/n2v_manipulate.py +113 -0
  89. careamics/transforms/nd_flip.py +93 -0
  90. careamics/transforms/normalize.py +109 -0
  91. careamics/transforms/pixel_manipulation.py +383 -0
  92. careamics/transforms/struct_mask_parameters.py +18 -0
  93. careamics/transforms/tta.py +74 -0
  94. careamics/transforms/xy_random_rotate90.py +95 -0
  95. careamics/utils/__init__.py +10 -13
  96. careamics/utils/base_enum.py +32 -0
  97. careamics/utils/context.py +22 -2
  98. careamics/utils/metrics.py +0 -46
  99. careamics/utils/path_utils.py +24 -0
  100. careamics/utils/ram.py +13 -0
  101. careamics/utils/receptive_field.py +102 -0
  102. careamics/utils/running_stats.py +43 -0
  103. careamics/utils/torch_utils.py +89 -56
  104. careamics-0.1.0rc3.dist-info/METADATA +122 -0
  105. careamics-0.1.0rc3.dist-info/RECORD +109 -0
  106. {careamics-0.1.0rc1.dist-info → careamics-0.1.0rc3.dist-info}/WHEEL +1 -1
  107. careamics/bioimage/__init__.py +0 -15
  108. careamics/bioimage/docs/Noise2Void.md +0 -5
  109. careamics/bioimage/docs/__init__.py +0 -1
  110. careamics/bioimage/io.py +0 -271
  111. careamics/config/algorithm.py +0 -231
  112. careamics/config/config.py +0 -296
  113. careamics/config/config_filter.py +0 -44
  114. careamics/config/data.py +0 -194
  115. careamics/config/torch_optim.py +0 -118
  116. careamics/config/training.py +0 -534
  117. careamics/dataset/dataset_utils.py +0 -115
  118. careamics/dataset/patching.py +0 -493
  119. careamics/dataset/prepare_dataset.py +0 -174
  120. careamics/dataset/tiff_dataset.py +0 -211
  121. careamics/engine.py +0 -954
  122. careamics/manipulation/__init__.py +0 -4
  123. careamics/manipulation/pixel_manipulation.py +0 -158
  124. careamics/prediction/prediction_utils.py +0 -102
  125. careamics/utils/ascii_logo.txt +0 -9
  126. careamics/utils/augment.py +0 -65
  127. careamics/utils/normalization.py +0 -55
  128. careamics/utils/validators.py +0 -156
  129. careamics/utils/wandb.py +0 -121
  130. careamics-0.1.0rc1.dist-info/METADATA +0 -80
  131. careamics-0.1.0rc1.dist-info/RECORD +0 -46
  132. {careamics-0.1.0rc1.dist-info → careamics-0.1.0rc3.dist-info}/licenses/LICENSE +0 -0
@@ -1,5 +0,0 @@
1
- ## Noise2Void
2
- Learning Denoising From Single Noisy Images
3
-
4
- ## Cite Noise2Void
5
- A. Krull, T.-O. Buchholz and F. Jug, "Noise2Void - Learning Denoising From Single Noisy Images," 2019 IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR), 2019, pp. 2124-2132
@@ -1 +0,0 @@
1
- """Default algorithm READMEs for bioimage.io format export."""
careamics/bioimage/io.py DELETED
@@ -1,271 +0,0 @@
1
- """Export to bioimage.io format."""
2
- from pathlib import Path
3
- from typing import Union
4
-
5
- import torch
6
- from bioimageio.core import load_resource_description
7
- from bioimageio.core.build_spec import build_model
8
- from bioimageio.spec.model.raw_nodes import Model
9
-
10
- from careamics.config.config import (
11
- Configuration,
12
- )
13
-
14
- PYTORCH_STATE_DICT = "pytorch_state_dict"
15
-
16
-
17
- def _get_model_doc(name: str) -> str:
18
- """
19
- Return markdown documentation path for the provided model.
20
-
21
- Parameters
22
- ----------
23
- name : str
24
- Model's name.
25
-
26
- Returns
27
- -------
28
- str
29
- Path to the model's markdown documentation.
30
-
31
- Raises
32
- ------
33
- FileNotFoundError
34
- If the documentation file was not found.
35
- """
36
- doc = Path(__file__).parent.joinpath("docs").joinpath(f"{name}.md")
37
- if doc.exists():
38
- return str(doc.absolute())
39
- else:
40
- raise FileNotFoundError(f"Documentation for {name} was not found.")
41
-
42
-
43
- def get_default_model_specs(
44
- name: str, mean: float, std: float, is_3D: bool = False
45
- ) -> dict:
46
- """
47
- Return the default bioimage.io specs for the provided model's name.
48
-
49
- Currently only supports `n2v` model.
50
-
51
- Parameters
52
- ----------
53
- name : str
54
- Algorithm's name.
55
- mean : float
56
- Mean of the dataset.
57
- std : float
58
- Std of the dataset.
59
- is_3D : bool, optional
60
- Whether the model is 3D or not, by default False.
61
-
62
- Returns
63
- -------
64
- dict
65
- Model specs compatible with bioimage.io export.
66
- """
67
- rdf = {
68
- "name": "Noise2Void",
69
- "description": "Self-supervised denoising.",
70
- "license": "BSD-3-Clause",
71
- "authors": [
72
- {"name": "Alexander Krull"},
73
- {"name": "Tim-Oliver Buchholz"},
74
- {"name": "Florian Jug"},
75
- ],
76
- "cite": [
77
- {
78
- "doi": "10.48550/arXiv.1811.10980",
79
- "text": 'A. Krull, T.-O. Buchholz and F. Jug, "Noise2Void - Learning '
80
- 'Denoising From Single Noisy Images," 2019 IEEE/CVF '
81
- "Conference on Computer Vision and Pattern Recognition "
82
- "(CVPR), 2019, pp. 2124-2132",
83
- }
84
- ],
85
- # "input_axes": ["bcyx"], <- overriden in save_as_bioimage
86
- "preprocessing": [ # for multiple inputs
87
- [ # multiple processes per input
88
- {
89
- "kwargs": {
90
- "axes": "zyx" if is_3D else "yx",
91
- "mean": [mean],
92
- "mode": "fixed",
93
- "std": [std],
94
- },
95
- "name": "zero_mean_unit_variance",
96
- }
97
- ]
98
- ],
99
- # "output_axes": ["bcyx"], <- overriden in save_as_bioimage
100
- "postprocessing": [ # for multiple outputs
101
- [ # multiple processes per input
102
- {
103
- "kwargs": {
104
- "axes": "zyx" if is_3D else "yx",
105
- "gain": [std],
106
- "offset": [mean],
107
- },
108
- "name": "scale_linear",
109
- }
110
- ]
111
- ],
112
- "tags": ["unet", "denoising", "Noise2Void", "tensorflow", "napari"],
113
- }
114
-
115
- rdf["documentation"] = _get_model_doc(name)
116
-
117
- return rdf
118
-
119
-
120
- def build_zip_model(
121
- path: Union[str, Path],
122
- config: Configuration,
123
- model_specs: dict,
124
- ) -> Model:
125
- """
126
- Build bioimage model zip file from model specification data.
127
-
128
- Parameters
129
- ----------
130
- path : Union[str, Path]
131
- Path to the model zip file.
132
- config : Configuration
133
- Configuration object.
134
- model_specs : dict
135
- Model specification data.
136
-
137
- Returns
138
- -------
139
- Model
140
- Bioimage model object.
141
- """
142
- workdir = config.working_directory
143
-
144
- # load best checkpoint
145
- checkpoint_path = workdir.joinpath(f"{config.experiment_name}_best.pth").absolute()
146
- checkpoint = torch.load(checkpoint_path, map_location="cpu")
147
-
148
- # save chekpoint entries in separate files
149
- weight_path = workdir.joinpath("model_weights.pth")
150
- torch.save(checkpoint["model_state_dict"], weight_path)
151
-
152
- optim_path = workdir.joinpath("optim.pth")
153
- torch.save(checkpoint["optimizer_state_dict"], optim_path)
154
-
155
- scheduler_path = workdir.joinpath("scheduler.pth")
156
- torch.save(checkpoint["scheduler_state_dict"], scheduler_path)
157
-
158
- grad_path = workdir.joinpath("grad.pth")
159
- torch.save(checkpoint["grad_scaler_state_dict"], grad_path)
160
-
161
- config_path = workdir.joinpath("config.pth")
162
- torch.save(config.model_dump(), config_path)
163
-
164
- # Create attachments
165
- attachments = [
166
- str(optim_path),
167
- str(scheduler_path),
168
- str(grad_path),
169
- str(config_path),
170
- ]
171
-
172
- model_specs.update(
173
- {
174
- "weight_type": PYTORCH_STATE_DICT,
175
- "weight_uri": str(weight_path),
176
- "attachments": {"files": attachments},
177
- }
178
- )
179
-
180
- if config.algorithm.is_3D:
181
- model_specs["tags"].append("3D")
182
- else:
183
- model_specs["tags"].append("2D")
184
-
185
- # build model zip
186
- raw_model = build_model(
187
- output_path=Path(path).absolute(),
188
- **model_specs,
189
- )
190
-
191
- # remove the temporary files
192
- weight_path.unlink()
193
- optim_path.unlink()
194
- scheduler_path.unlink()
195
- grad_path.unlink()
196
- config_path.unlink()
197
-
198
- return raw_model
199
-
200
-
201
- def import_bioimage_model(model_path: Union[str, Path]) -> Path:
202
- """
203
- Load configuration and weights from a bioimage zip model.
204
-
205
- Parameters
206
- ----------
207
- model_path : Union[str, Path]
208
- Path to the bioimage.io archive.
209
-
210
- Returns
211
- -------
212
- Path
213
- Path to the checkpoint.
214
-
215
- Raises
216
- ------
217
- ValueError
218
- If the model format is invalid.
219
- FileNotFoundError
220
- If the checkpoint file was not found.
221
- """
222
- if isinstance(model_path, str):
223
- model_path = Path(model_path)
224
- # check the model extension (should be a zip file).
225
- if model_path.suffix != ".zip":
226
- raise ValueError("Invalid model format. Expected bioimage model zip file.")
227
- # load the model
228
- rdf = load_resource_description(model_path)
229
-
230
- # create a valid checkpoint file from weights and attached files
231
- basedir = model_path.parent.joinpath("rdf_model")
232
- basedir.mkdir(exist_ok=True)
233
- optim_path = None
234
- scheduler_path = None
235
- grad_path = None
236
- config_path = None
237
- weight_path = None
238
-
239
- if rdf.weights.get(PYTORCH_STATE_DICT) is not None:
240
- weight_path = rdf.weights.get(PYTORCH_STATE_DICT).source
241
-
242
- for file in rdf.attachments.files:
243
- if file.name.endswith("optim.pth"):
244
- optim_path = file
245
- elif file.name.endswith("scheduler.pth"):
246
- scheduler_path = file
247
- elif file.name.endswith("grad.pth"):
248
- grad_path = file
249
- elif file.name.endswith("config.pth"):
250
- config_path = file
251
-
252
- if (
253
- weight_path is None
254
- or optim_path is None
255
- or scheduler_path is None
256
- or grad_path is None
257
- or config_path is None
258
- ):
259
- raise FileNotFoundError(f"No valid checkpoint file was found in {model_path}.")
260
-
261
- checkpoint = {
262
- "model_state_dict": torch.load(weight_path, map_location="cpu"),
263
- "optimizer_state_dict": torch.load(optim_path, map_location="cpu"),
264
- "scheduler_state_dict": torch.load(scheduler_path, map_location="cpu"),
265
- "grad_scaler_state_dict": torch.load(grad_path, map_location="cpu"),
266
- "config": torch.load(config_path, map_location="cpu"),
267
- }
268
- checkpoint_path = basedir.joinpath("checkpoint.pth")
269
- torch.save(checkpoint, checkpoint_path)
270
-
271
- return checkpoint_path
@@ -1,231 +0,0 @@
1
- """Algorithm configuration."""
2
- from enum import Enum
3
- from typing import Dict, List
4
-
5
- from pydantic import BaseModel, ConfigDict, Field, field_validator
6
-
7
- from .config_filter import remove_default_optionals
8
-
9
-
10
- # python 3.11: https://docs.python.org/3/library/enum.html
11
- class Loss(str, Enum):
12
- """
13
- Available loss functions.
14
-
15
- Currently supported losses:
16
-
17
- - n2v: Noise2Void loss.
18
- """
19
-
20
- N2V = "n2v"
21
-
22
-
23
- class Models(str, Enum):
24
- """
25
- Available models.
26
-
27
- Currently supported models:
28
- - UNet: U-Net model.
29
- """
30
-
31
- UNET = "UNet"
32
-
33
-
34
- class MaskingStrategy(str, Enum):
35
- """
36
- Available masking strategy.
37
-
38
- Currently supported strategies:
39
-
40
- - default: default masking strategy of Noise2Void (uniform sampling of neighbors).
41
- - median: median masking strategy of N2V2.
42
- """
43
-
44
- DEFAULT = "default"
45
- MEDIAN = "median"
46
-
47
-
48
- class ModelParameters(BaseModel):
49
- """
50
- Deep-learning model parameters.
51
-
52
- The number of filters (base) must be even and minimum 8.
53
-
54
- Attributes
55
- ----------
56
- depth : int
57
- Depth of the model, between 1 and 10 (default 2).
58
- num_channels_init : int
59
- Number of filters of the first level of the network, should be even
60
- and minimum 8 (default 96).
61
- """
62
-
63
- model_config = ConfigDict(validate_assignment=True)
64
-
65
- depth: int = Field(default=2, ge=1, le=10)
66
- num_channels_init: int = Field(default=32, ge=8)
67
-
68
- # TODO revisit the constraints on num_channels_init
69
- @field_validator("num_channels_init")
70
- def even(cls, num_channels: int) -> int:
71
- """
72
- Validate that num_channels_init is even.
73
-
74
- Parameters
75
- ----------
76
- num_channels : int
77
- Number of channels.
78
-
79
- Returns
80
- -------
81
- int
82
- Validated number of channels.
83
-
84
- Raises
85
- ------
86
- ValueError
87
- If the number of channels is odd.
88
- """
89
- # if odd
90
- if num_channels % 2 != 0:
91
- raise ValueError(
92
- f"Number of channels (init) must be even (got {num_channels})."
93
- )
94
-
95
- return num_channels
96
-
97
-
98
- class Algorithm(BaseModel):
99
- """
100
- Algorithm configuration.
101
-
102
- The minimum algorithm configuration is composed of the following fields:
103
- - loss:
104
- Loss to use, currently only supports n2v.
105
- - model:
106
- Model to use, currently only supports UNet.
107
- - is_3D:
108
- Whether to use a 3D model or not, this should be coherent with the
109
- data configuration (axes).
110
-
111
- Other optional fields are:
112
- - masking_strategy:
113
- Masking strategy to use, currently only supports default masking.
114
- - masked_pixel_percentage:
115
- Percentage of pixels to be masked in each patch.
116
- - roi_size:
117
- Size of the region of interest to use in the masking algorithm.
118
- - model_parameters:
119
- Model parameters, see ModelParameters for more details.
120
-
121
- Attributes
122
- ----------
123
- loss : List[Losses]
124
- List of losses to use, currently only supports n2v.
125
- model : Models
126
- Model to use, currently only supports UNet.
127
- is_3D : bool
128
- Whether to use a 3D model or not.
129
- masking_strategy : MaskingStrategies
130
- Masking strategy to use, currently only supports default masking.
131
- masked_pixel_percentage : float
132
- Percentage of pixels to be masked in each patch.
133
- roi_size : int
134
- Size of the region of interest used in the masking scheme.
135
- model_parameters : ModelParameters
136
- Model parameters, see ModelParameters for more details.
137
- """
138
-
139
- # Pydantic class configuration
140
- model_config = ConfigDict(
141
- use_enum_values=True,
142
- protected_namespaces=(), # allows to use model_* as a field name
143
- validate_assignment=True,
144
- )
145
-
146
- # Mandatory fields
147
- loss: Loss
148
- model: Models
149
- is_3D: bool
150
-
151
- # Optional fields, define a default value
152
- masking_strategy: MaskingStrategy = MaskingStrategy.DEFAULT
153
- masked_pixel_percentage: float = Field(default=0.2, ge=0.1, le=20)
154
- roi_size: int = Field(default=11, ge=3, le=21)
155
- model_parameters: ModelParameters = ModelParameters()
156
-
157
- def get_conv_dim(self) -> int:
158
- """
159
- Get the convolution layers dimension (2D or 3D).
160
-
161
- Returns
162
- -------
163
- int
164
- Dimension (2 or 3).
165
- """
166
- return 3 if self.is_3D else 2
167
-
168
- @field_validator("roi_size")
169
- def even(cls, roi_size: int) -> int:
170
- """
171
- Validate that roi_size is odd.
172
-
173
- Parameters
174
- ----------
175
- roi_size : int
176
- Size of the region of interest in the masking scheme.
177
-
178
- Returns
179
- -------
180
- int
181
- Validated size of the region of interest.
182
-
183
- Raises
184
- ------
185
- ValueError
186
- If the size of the region of interest is even.
187
- """
188
- # if even
189
- if roi_size % 2 == 0:
190
- raise ValueError(f"ROI size must be odd (got {roi_size}).")
191
-
192
- return roi_size
193
-
194
- def model_dump(
195
- self, exclude_optionals: bool = True, *args: List, **kwargs: Dict
196
- ) -> Dict:
197
- """
198
- Override model_dump method.
199
-
200
- The purpose is to ensure export smooth import to yaml. It includes:
201
- - remove entries with None value.
202
- - remove optional values if they have the default value.
203
-
204
- Parameters
205
- ----------
206
- exclude_optionals : bool, optional
207
- Whether to exclude optional arguments if they are default, by default True.
208
- *args : List
209
- Positional arguments, unused.
210
- **kwargs : Dict
211
- Keyword arguments, unused.
212
-
213
- Returns
214
- -------
215
- Dict
216
- Dictionary representation of the model.
217
- """
218
- dictionary = super().model_dump(exclude_none=True)
219
-
220
- if exclude_optionals is True:
221
- # remove optional arguments if they are default
222
- defaults = {
223
- "masking_strategy": MaskingStrategy.DEFAULT.value,
224
- "masked_pixel_percentage": 0.2,
225
- "roi_size": 11,
226
- "model_parameters": ModelParameters().model_dump(exclude_none=True),
227
- }
228
-
229
- remove_default_optionals(dictionary, defaults)
230
-
231
- return dictionary