careamics 0.0.1__py3-none-any.whl → 0.0.3__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 (155) hide show
  1. careamics/__init__.py +6 -1
  2. careamics/careamist.py +729 -0
  3. careamics/config/__init__.py +39 -0
  4. careamics/config/architectures/__init__.py +17 -0
  5. careamics/config/architectures/architecture_model.py +37 -0
  6. careamics/config/architectures/custom_model.py +162 -0
  7. careamics/config/architectures/lvae_model.py +174 -0
  8. careamics/config/architectures/register_model.py +103 -0
  9. careamics/config/architectures/unet_model.py +118 -0
  10. careamics/config/callback_model.py +123 -0
  11. careamics/config/configuration_factory.py +583 -0
  12. careamics/config/configuration_model.py +604 -0
  13. careamics/config/data_model.py +527 -0
  14. careamics/config/fcn_algorithm_model.py +147 -0
  15. careamics/config/inference_model.py +239 -0
  16. careamics/config/likelihood_model.py +43 -0
  17. careamics/config/nm_model.py +101 -0
  18. careamics/config/optimizer_models.py +187 -0
  19. careamics/config/references/__init__.py +45 -0
  20. careamics/config/references/algorithm_descriptions.py +132 -0
  21. careamics/config/references/references.py +39 -0
  22. careamics/config/support/__init__.py +31 -0
  23. careamics/config/support/supported_activations.py +27 -0
  24. careamics/config/support/supported_algorithms.py +33 -0
  25. careamics/config/support/supported_architectures.py +17 -0
  26. careamics/config/support/supported_data.py +109 -0
  27. careamics/config/support/supported_loggers.py +10 -0
  28. careamics/config/support/supported_losses.py +29 -0
  29. careamics/config/support/supported_optimizers.py +57 -0
  30. careamics/config/support/supported_pixel_manipulations.py +15 -0
  31. careamics/config/support/supported_struct_axis.py +21 -0
  32. careamics/config/support/supported_transforms.py +11 -0
  33. careamics/config/tile_information.py +65 -0
  34. careamics/config/training_model.py +72 -0
  35. careamics/config/transformations/__init__.py +15 -0
  36. careamics/config/transformations/n2v_manipulate_model.py +64 -0
  37. careamics/config/transformations/normalize_model.py +60 -0
  38. careamics/config/transformations/transform_model.py +45 -0
  39. careamics/config/transformations/xy_flip_model.py +43 -0
  40. careamics/config/transformations/xy_random_rotate90_model.py +35 -0
  41. careamics/config/vae_algorithm_model.py +171 -0
  42. careamics/config/validators/__init__.py +5 -0
  43. careamics/config/validators/validator_utils.py +101 -0
  44. careamics/conftest.py +39 -0
  45. careamics/dataset/__init__.py +17 -0
  46. careamics/dataset/dataset_utils/__init__.py +19 -0
  47. careamics/dataset/dataset_utils/dataset_utils.py +101 -0
  48. careamics/dataset/dataset_utils/file_utils.py +141 -0
  49. careamics/dataset/dataset_utils/iterate_over_files.py +83 -0
  50. careamics/dataset/dataset_utils/running_stats.py +186 -0
  51. careamics/dataset/in_memory_dataset.py +310 -0
  52. careamics/dataset/in_memory_pred_dataset.py +88 -0
  53. careamics/dataset/in_memory_tiled_pred_dataset.py +129 -0
  54. careamics/dataset/iterable_dataset.py +295 -0
  55. careamics/dataset/iterable_pred_dataset.py +122 -0
  56. careamics/dataset/iterable_tiled_pred_dataset.py +140 -0
  57. careamics/dataset/patching/__init__.py +1 -0
  58. careamics/dataset/patching/patching.py +299 -0
  59. careamics/dataset/patching/random_patching.py +201 -0
  60. careamics/dataset/patching/sequential_patching.py +212 -0
  61. careamics/dataset/patching/validate_patch_dimension.py +64 -0
  62. careamics/dataset/tiling/__init__.py +10 -0
  63. careamics/dataset/tiling/collate_tiles.py +33 -0
  64. careamics/dataset/tiling/lvae_tiled_patching.py +282 -0
  65. careamics/dataset/tiling/tiled_patching.py +164 -0
  66. careamics/dataset/zarr_dataset.py +151 -0
  67. careamics/file_io/__init__.py +15 -0
  68. careamics/file_io/read/__init__.py +12 -0
  69. careamics/file_io/read/get_func.py +56 -0
  70. careamics/file_io/read/tiff.py +58 -0
  71. careamics/file_io/read/zarr.py +60 -0
  72. careamics/file_io/write/__init__.py +15 -0
  73. careamics/file_io/write/get_func.py +63 -0
  74. careamics/file_io/write/tiff.py +40 -0
  75. careamics/lightning/__init__.py +18 -0
  76. careamics/lightning/callbacks/__init__.py +11 -0
  77. careamics/lightning/callbacks/hyperparameters_callback.py +49 -0
  78. careamics/lightning/callbacks/prediction_writer_callback/__init__.py +20 -0
  79. careamics/lightning/callbacks/prediction_writer_callback/file_path_utils.py +56 -0
  80. careamics/lightning/callbacks/prediction_writer_callback/prediction_writer_callback.py +233 -0
  81. careamics/lightning/callbacks/prediction_writer_callback/write_strategy.py +398 -0
  82. careamics/lightning/callbacks/prediction_writer_callback/write_strategy_factory.py +215 -0
  83. careamics/lightning/callbacks/progress_bar_callback.py +90 -0
  84. careamics/lightning/lightning_module.py +632 -0
  85. careamics/lightning/predict_data_module.py +333 -0
  86. careamics/lightning/train_data_module.py +680 -0
  87. careamics/losses/__init__.py +15 -0
  88. careamics/losses/fcn/__init__.py +1 -0
  89. careamics/losses/fcn/losses.py +98 -0
  90. careamics/losses/loss_factory.py +155 -0
  91. careamics/losses/lvae/__init__.py +1 -0
  92. careamics/losses/lvae/loss_utils.py +83 -0
  93. careamics/losses/lvae/losses.py +445 -0
  94. careamics/lvae_training/__init__.py +0 -0
  95. careamics/lvae_training/dataset/__init__.py +0 -0
  96. careamics/lvae_training/dataset/data_utils.py +701 -0
  97. careamics/lvae_training/dataset/lc_dataset.py +259 -0
  98. careamics/lvae_training/dataset/lc_dataset_config.py +13 -0
  99. careamics/lvae_training/dataset/vae_data_config.py +179 -0
  100. careamics/lvae_training/dataset/vae_dataset.py +1054 -0
  101. careamics/lvae_training/eval_utils.py +905 -0
  102. careamics/lvae_training/get_config.py +84 -0
  103. careamics/lvae_training/lightning_module.py +701 -0
  104. careamics/lvae_training/metrics.py +214 -0
  105. careamics/lvae_training/train_lvae.py +342 -0
  106. careamics/lvae_training/train_utils.py +121 -0
  107. careamics/model_io/__init__.py +7 -0
  108. careamics/model_io/bioimage/__init__.py +11 -0
  109. careamics/model_io/bioimage/_readme_factory.py +121 -0
  110. careamics/model_io/bioimage/bioimage_utils.py +52 -0
  111. careamics/model_io/bioimage/model_description.py +327 -0
  112. careamics/model_io/bmz_io.py +246 -0
  113. careamics/model_io/model_io_utils.py +95 -0
  114. careamics/models/__init__.py +5 -0
  115. careamics/models/activation.py +39 -0
  116. careamics/models/layers.py +493 -0
  117. careamics/models/lvae/__init__.py +3 -0
  118. careamics/models/lvae/layers.py +1998 -0
  119. careamics/models/lvae/likelihoods.py +364 -0
  120. careamics/models/lvae/lvae.py +901 -0
  121. careamics/models/lvae/noise_models.py +541 -0
  122. careamics/models/lvae/utils.py +395 -0
  123. careamics/models/model_factory.py +67 -0
  124. careamics/models/unet.py +443 -0
  125. careamics/prediction_utils/__init__.py +10 -0
  126. careamics/prediction_utils/lvae_prediction.py +158 -0
  127. careamics/prediction_utils/lvae_tiling_manager.py +362 -0
  128. careamics/prediction_utils/prediction_outputs.py +135 -0
  129. careamics/prediction_utils/stitch_prediction.py +112 -0
  130. careamics/transforms/__init__.py +20 -0
  131. careamics/transforms/compose.py +107 -0
  132. careamics/transforms/n2v_manipulate.py +146 -0
  133. careamics/transforms/normalize.py +243 -0
  134. careamics/transforms/pixel_manipulation.py +407 -0
  135. careamics/transforms/struct_mask_parameters.py +20 -0
  136. careamics/transforms/transform.py +24 -0
  137. careamics/transforms/tta.py +88 -0
  138. careamics/transforms/xy_flip.py +123 -0
  139. careamics/transforms/xy_random_rotate90.py +101 -0
  140. careamics/utils/__init__.py +19 -0
  141. careamics/utils/autocorrelation.py +40 -0
  142. careamics/utils/base_enum.py +60 -0
  143. careamics/utils/context.py +66 -0
  144. careamics/utils/logging.py +322 -0
  145. careamics/utils/metrics.py +188 -0
  146. careamics/utils/path_utils.py +26 -0
  147. careamics/utils/ram.py +15 -0
  148. careamics/utils/receptive_field.py +108 -0
  149. careamics/utils/torch_utils.py +127 -0
  150. careamics-0.0.3.dist-info/METADATA +78 -0
  151. careamics-0.0.3.dist-info/RECORD +154 -0
  152. {careamics-0.0.1.dist-info → careamics-0.0.3.dist-info}/WHEEL +1 -1
  153. {careamics-0.0.1.dist-info → careamics-0.0.3.dist-info}/licenses/LICENSE +1 -1
  154. careamics-0.0.1.dist-info/METADATA +0 -46
  155. careamics-0.0.1.dist-info/RECORD +0 -6
@@ -0,0 +1,233 @@
1
+ """Module containing `PredictionWriterCallback` class."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+ from typing import Any, Optional, Sequence, Union
7
+
8
+ from pytorch_lightning import LightningModule, Trainer
9
+ from pytorch_lightning.callbacks import BasePredictionWriter
10
+ from torch.utils.data import DataLoader
11
+
12
+ from careamics.dataset import (
13
+ IterablePredDataset,
14
+ IterableTiledPredDataset,
15
+ )
16
+ from careamics.file_io import SupportedWriteType, WriteFunc
17
+ from careamics.utils import get_logger
18
+
19
+ from .write_strategy import WriteStrategy
20
+ from .write_strategy_factory import create_write_strategy
21
+
22
+ logger = get_logger(__name__)
23
+
24
+ ValidPredDatasets = Union[IterablePredDataset, IterableTiledPredDataset]
25
+
26
+
27
+ class PredictionWriterCallback(BasePredictionWriter):
28
+ """
29
+ A PyTorch Lightning callback to save predictions.
30
+
31
+ Parameters
32
+ ----------
33
+ write_strategy : WriteStrategy
34
+ A strategy for writing predictions.
35
+ dirpath : Path or str, default="predictions"
36
+ The path to the directory where prediction outputs will be saved. If
37
+ `dirpath` is not absolute it is assumed to be relative to current working
38
+ directory.
39
+
40
+ Attributes
41
+ ----------
42
+ write_strategy : WriteStrategy
43
+ A strategy for writing predictions.
44
+ dirpath : pathlib.Path, default="predictions"
45
+ The path to the directory where prediction outputs will be saved. If
46
+ `dirpath` is not absolute it is assumed to be relative to current working
47
+ directory.
48
+ writing_predictions : bool
49
+ If writing predictions is turned on or off.
50
+ """
51
+
52
+ def __init__(
53
+ self,
54
+ write_strategy: WriteStrategy,
55
+ dirpath: Union[Path, str] = "predictions",
56
+ ):
57
+ """
58
+ A PyTorch Lightning callback to save predictions.
59
+
60
+ Parameters
61
+ ----------
62
+ write_strategy : WriteStrategy
63
+ A strategy for writing predictions.
64
+ dirpath : pathlib.Path or str, default="predictions"
65
+ The path to the directory where prediction outputs will be saved. If
66
+ `dirpath` is not absolute it is assumed to be relative to current working
67
+ directory.
68
+ """
69
+ super().__init__(write_interval="batch")
70
+
71
+ # Toggle for CAREamist to switch off saving if desired
72
+ self.writing_predictions: bool = True
73
+
74
+ self.write_strategy: WriteStrategy = write_strategy
75
+
76
+ # forward declaration
77
+ self.dirpath: Path
78
+ # attribute initialisation
79
+ self._init_dirpath(dirpath)
80
+
81
+ @classmethod
82
+ def from_write_func_params(
83
+ cls,
84
+ write_type: SupportedWriteType,
85
+ tiled: bool,
86
+ write_func: Optional[WriteFunc] = None,
87
+ write_extension: Optional[str] = None,
88
+ write_func_kwargs: Optional[dict[str, Any]] = None,
89
+ dirpath: Union[Path, str] = "predictions",
90
+ ) -> PredictionWriterCallback: # TODO: change type hint to self (find out how)
91
+ """
92
+ Initialize a `PredictionWriterCallback` from write function parameters.
93
+
94
+ This will automatically create a `WriteStrategy` to be passed to the
95
+ initialization of `PredictionWriterCallback`.
96
+
97
+ Parameters
98
+ ----------
99
+ write_type : {"tiff", "custom"}
100
+ The data type to save as, includes custom.
101
+ tiled : bool
102
+ Whether the prediction will be tiled or not.
103
+ write_func : WriteFunc, optional
104
+ If a known `write_type` is selected this argument is ignored. For a custom
105
+ `write_type` a function to save the data must be passed. See notes below.
106
+ write_extension : str, optional
107
+ If a known `write_type` is selected this argument is ignored. For a custom
108
+ `write_type` an extension to save the data with must be passed.
109
+ write_func_kwargs : dict of {{str: any}}, optional
110
+ Additional keyword arguments to be passed to the save function.
111
+ dirpath : pathlib.Path or str, default="predictions"
112
+ The path to the directory where prediction outputs will be saved. If
113
+ `dirpath` is not absolute it is assumed to be relative to current working
114
+ directory.
115
+
116
+ Returns
117
+ -------
118
+ PredictionWriterCallback
119
+ Callback for writing predictions.
120
+ """
121
+ write_strategy = create_write_strategy(
122
+ write_type=write_type,
123
+ tiled=tiled,
124
+ write_func=write_func,
125
+ write_extension=write_extension,
126
+ write_func_kwargs=write_func_kwargs,
127
+ )
128
+ return cls(write_strategy=write_strategy, dirpath=dirpath)
129
+
130
+ def _init_dirpath(self, dirpath):
131
+ """
132
+ Initialize directory path. Should only be called from `__init__`.
133
+
134
+ Parameters
135
+ ----------
136
+ dirpath : pathlib.Path
137
+ See `__init__` description.
138
+ """
139
+ dirpath = Path(dirpath)
140
+ if not dirpath.is_absolute():
141
+ dirpath = Path.cwd() / dirpath
142
+ logger.warning(
143
+ "Prediction output directory is not absolute, absolute path assumed to"
144
+ f"be '{dirpath}'"
145
+ )
146
+ self.dirpath = dirpath
147
+
148
+ def setup(self, trainer: Trainer, pl_module: LightningModule, stage: str) -> None:
149
+ """
150
+ Create the prediction output directory when predict begins.
151
+
152
+ Called when fit, validate, test, predict, or tune begins.
153
+
154
+ Parameters
155
+ ----------
156
+ trainer : Trainer
157
+ PyTorch Lightning trainer.
158
+ pl_module : LightningModule
159
+ PyTorch Lightning module.
160
+ stage : str
161
+ Stage of training e.g. 'predict', 'fit', 'validate'.
162
+ """
163
+ super().setup(trainer, pl_module, stage)
164
+ if stage == "predict":
165
+ # make prediction output directory
166
+ logger.info("Making prediction output directory.")
167
+ self.dirpath.mkdir(parents=True, exist_ok=True)
168
+
169
+ def write_on_batch_end(
170
+ self,
171
+ trainer: Trainer,
172
+ pl_module: LightningModule,
173
+ prediction: Any, # TODO: change to expected type
174
+ batch_indices: Optional[Sequence[int]],
175
+ batch: Any, # TODO: change to expected type
176
+ batch_idx: int,
177
+ dataloader_idx: int,
178
+ ) -> None:
179
+ """
180
+ Write predictions at the end of a batch.
181
+
182
+ The method of prediction is determined by the attribute `write_strategy`.
183
+
184
+ Parameters
185
+ ----------
186
+ trainer : Trainer
187
+ PyTorch Lightning trainer.
188
+ pl_module : LightningModule
189
+ PyTorch Lightning module.
190
+ prediction : Any
191
+ Prediction outputs of `batch`.
192
+ batch_indices : sequence of Any, optional
193
+ Batch indices.
194
+ batch : Any
195
+ Input batch.
196
+ batch_idx : int
197
+ Batch index.
198
+ dataloader_idx : int
199
+ Dataloader index.
200
+ """
201
+ # if writing prediction is turned off
202
+ if not self.writing_predictions:
203
+ return
204
+
205
+ dataloaders: Union[DataLoader, list[DataLoader]] = trainer.predict_dataloaders
206
+ dataloader: DataLoader = (
207
+ dataloaders[dataloader_idx]
208
+ if isinstance(dataloaders, list)
209
+ else dataloaders
210
+ )
211
+ dataset: ValidPredDatasets = dataloader.dataset
212
+ if not (
213
+ isinstance(dataset, IterablePredDataset)
214
+ or isinstance(dataset, IterableTiledPredDataset)
215
+ ):
216
+ # Note: Error will be raised before here from the source type
217
+ # This is for extra redundancy of errors.
218
+ raise TypeError(
219
+ "Prediction dataset has to be `IterableTiledPredDataset` or "
220
+ "`IterablePredDataset`. Cannot be `InMemoryPredDataset` because "
221
+ "filenames are taken from the original file."
222
+ )
223
+
224
+ self.write_strategy.write_batch(
225
+ trainer=trainer,
226
+ pl_module=pl_module,
227
+ prediction=prediction,
228
+ batch_indices=batch_indices,
229
+ batch=batch,
230
+ batch_idx=batch_idx,
231
+ dataloader_idx=dataloader_idx,
232
+ dirpath=self.dirpath,
233
+ )
@@ -0,0 +1,398 @@
1
+ """Module containing different strategies for writing predictions."""
2
+
3
+ from pathlib import Path
4
+ from typing import Any, Optional, Protocol, Sequence, Union
5
+
6
+ import numpy as np
7
+ from numpy.typing import NDArray
8
+ from pytorch_lightning import LightningModule, Trainer
9
+ from torch.utils.data import DataLoader
10
+
11
+ from careamics.config.tile_information import TileInformation
12
+ from careamics.dataset import IterablePredDataset, IterableTiledPredDataset
13
+ from careamics.file_io import WriteFunc
14
+ from careamics.prediction_utils import stitch_prediction_single
15
+
16
+ from .file_path_utils import create_write_file_path, get_sample_file_path
17
+
18
+
19
+ class WriteStrategy(Protocol):
20
+ """Protocol for write strategy classes."""
21
+
22
+ def write_batch(
23
+ self,
24
+ trainer: Trainer,
25
+ pl_module: LightningModule,
26
+ prediction: Any, # TODO: change to expected type
27
+ batch_indices: Optional[Sequence[int]],
28
+ batch: Any, # TODO: change to expected type
29
+ batch_idx: int,
30
+ dataloader_idx: int,
31
+ dirpath: Path,
32
+ ) -> None:
33
+ """
34
+ WriteStrategy subclasses must contain this function to write a batch.
35
+
36
+ Parameters
37
+ ----------
38
+ trainer : Trainer
39
+ PyTorch Lightning Trainer.
40
+ pl_module : LightningModule
41
+ PyTorch Lightning LightningModule.
42
+ prediction : Any
43
+ Predictions on `batch`.
44
+ batch_indices : sequence of int
45
+ Indices identifying the samples in the batch.
46
+ batch : Any
47
+ Input batch.
48
+ batch_idx : int
49
+ Batch index.
50
+ dataloader_idx : int
51
+ Dataloader index.
52
+ dirpath : Path
53
+ Path to directory to save predictions to.
54
+ """
55
+
56
+
57
+ class CacheTiles(WriteStrategy):
58
+ """
59
+ A write strategy that will cache tiles.
60
+
61
+ Tiles are cached until a whole image is predicted on. Then the stitched
62
+ prediction is saved.
63
+
64
+ Parameters
65
+ ----------
66
+ write_func : WriteFunc
67
+ Function used to save predictions.
68
+ write_extension : str
69
+ Extension added to prediction file paths.
70
+ write_func_kwargs : dict of {str: Any}
71
+ Extra kwargs to pass to `write_func`.
72
+
73
+ Attributes
74
+ ----------
75
+ write_func : WriteFunc
76
+ Function used to save predictions.
77
+ write_extension : str
78
+ Extension added to prediction file paths.
79
+ write_func_kwargs : dict of {str: Any}
80
+ Extra kwargs to pass to `write_func`.
81
+ tile_cache : list of numpy.ndarray
82
+ Tiles cached for stitching prediction.
83
+ tile_info_cache : list of TileInformation
84
+ Cached tile information for stitching prediction.
85
+ """
86
+
87
+ def __init__(
88
+ self,
89
+ write_func: WriteFunc,
90
+ write_extension: str,
91
+ write_func_kwargs: dict[str, Any],
92
+ ) -> None:
93
+ """
94
+ A write strategy that will cache tiles.
95
+
96
+ Tiles are cached until a whole image is predicted on. Then the stitched
97
+ prediction is saved.
98
+
99
+ Parameters
100
+ ----------
101
+ write_func : WriteFunc
102
+ Function used to save predictions.
103
+ write_extension : str
104
+ Extension added to prediction file paths.
105
+ write_func_kwargs : dict of {str: Any}
106
+ Extra kwargs to pass to `write_func`.
107
+ """
108
+ super().__init__()
109
+
110
+ self.write_func: WriteFunc = write_func
111
+ self.write_extension: str = write_extension
112
+ self.write_func_kwargs: dict[str, Any] = write_func_kwargs
113
+
114
+ # where tiles will be cached until a whole image has been predicted
115
+ self.tile_cache: list[NDArray] = []
116
+ self.tile_info_cache: list[TileInformation] = []
117
+
118
+ @property
119
+ def last_tiles(self) -> list[bool]:
120
+ """
121
+ List of bool to determine whether each tile in the cache is the last tile.
122
+
123
+ Returns
124
+ -------
125
+ list of bool
126
+ Whether each tile in the tile cache is the last tile.
127
+ """
128
+ return [tile_info.last_tile for tile_info in self.tile_info_cache]
129
+
130
+ def write_batch(
131
+ self,
132
+ trainer: Trainer,
133
+ pl_module: LightningModule,
134
+ prediction: tuple[NDArray, list[TileInformation]],
135
+ batch_indices: Optional[Sequence[int]],
136
+ batch: tuple[NDArray, list[TileInformation]],
137
+ batch_idx: int,
138
+ dataloader_idx: int,
139
+ dirpath: Path,
140
+ ) -> None:
141
+ """
142
+ Cache tiles until the last tile is predicted; save the stitched prediction.
143
+
144
+ Parameters
145
+ ----------
146
+ trainer : Trainer
147
+ PyTorch Lightning Trainer.
148
+ pl_module : LightningModule
149
+ PyTorch Lightning LightningModule.
150
+ prediction : Any
151
+ Predictions on `batch`.
152
+ batch_indices : sequence of int
153
+ Indices identifying the samples in the batch.
154
+ batch : Any
155
+ Input batch.
156
+ batch_idx : int
157
+ Batch index.
158
+ dataloader_idx : int
159
+ Dataloader index.
160
+ dirpath : Path
161
+ Path to directory to save predictions to.
162
+ """
163
+ dataloaders: Union[DataLoader, list[DataLoader]] = trainer.predict_dataloaders
164
+ dataloader: DataLoader = (
165
+ dataloaders[dataloader_idx]
166
+ if isinstance(dataloaders, list)
167
+ else dataloaders
168
+ )
169
+ dataset: IterableTiledPredDataset = dataloader.dataset
170
+ if not isinstance(dataset, IterableTiledPredDataset):
171
+ raise TypeError("Prediction dataset is not `IterableTiledPredDataset`.")
172
+
173
+ # cache tiles (batches are split into single samples)
174
+ self.tile_cache.extend(np.split(prediction[0], prediction[0].shape[0]))
175
+ self.tile_info_cache.extend(prediction[1])
176
+
177
+ # save stitched prediction
178
+ if self._has_last_tile():
179
+
180
+ # get image tiles and remove them from the cache
181
+ tiles, tile_infos = self._get_image_tiles()
182
+ self._clear_cache()
183
+
184
+ # stitch prediction
185
+ prediction_image = stitch_prediction_single(
186
+ tiles=tiles, tile_infos=tile_infos
187
+ )
188
+
189
+ # write prediction
190
+ sample_id = tile_infos[0].sample_id # need this to select correct file name
191
+ input_file_path = get_sample_file_path(dataset=dataset, sample_id=sample_id)
192
+ file_path = create_write_file_path(
193
+ dirpath=dirpath,
194
+ file_path=input_file_path,
195
+ write_extension=self.write_extension,
196
+ )
197
+ self.write_func(
198
+ file_path=file_path, img=prediction_image[0], **self.write_func_kwargs
199
+ )
200
+
201
+ def _has_last_tile(self) -> bool:
202
+ """
203
+ Whether a last tile is contained in the cached tiles.
204
+
205
+ Returns
206
+ -------
207
+ bool
208
+ Whether a last tile is contained in the cached tiles.
209
+ """
210
+ return any(self.last_tiles)
211
+
212
+ def _clear_cache(self) -> None:
213
+ """Remove the tiles in the cache up to the first last tile."""
214
+ index = self._last_tile_index()
215
+ self.tile_cache = self.tile_cache[index + 1 :]
216
+ self.tile_info_cache = self.tile_info_cache[index + 1 :]
217
+
218
+ def _last_tile_index(self) -> int:
219
+ """
220
+ Find the index of the last tile in the tile cache.
221
+
222
+ Returns
223
+ -------
224
+ int
225
+ Index of last tile.
226
+
227
+ Raises
228
+ ------
229
+ ValueError
230
+ If there is no last tile in the tile cache.
231
+ """
232
+ last_tiles = self.last_tiles
233
+ if not any(last_tiles):
234
+ raise ValueError("No last tile in the tile cache.")
235
+ index = np.where(last_tiles)[0][0]
236
+ return index
237
+
238
+ def _get_image_tiles(self) -> tuple[list[NDArray], list[TileInformation]]:
239
+ """
240
+ Get the tiles corresponding to a single image.
241
+
242
+ Returns
243
+ -------
244
+ tuple of (list of numpy.ndarray, list of TileInformation)
245
+ Tiles and tile information to stitch together a full image.
246
+ """
247
+ index = self._last_tile_index()
248
+ tiles = self.tile_cache[: index + 1]
249
+ tile_infos = self.tile_info_cache[: index + 1]
250
+ return tiles, tile_infos
251
+
252
+
253
+ class WriteTilesZarr(WriteStrategy):
254
+ """Strategy to write tiles to Zarr file."""
255
+
256
+ def write_batch(
257
+ self,
258
+ trainer: Trainer,
259
+ pl_module: LightningModule,
260
+ prediction: Any,
261
+ batch_indices: Optional[Sequence[int]],
262
+ batch: Any,
263
+ batch_idx: int,
264
+ dataloader_idx: int,
265
+ dirpath: Path,
266
+ ) -> None:
267
+ """
268
+ Write tiles to zarr file.
269
+
270
+ Parameters
271
+ ----------
272
+ trainer : Trainer
273
+ PyTorch Lightning Trainer.
274
+ pl_module : LightningModule
275
+ PyTorch Lightning LightningModule.
276
+ prediction : Any
277
+ Predictions on `batch`.
278
+ batch_indices : sequence of int
279
+ Indices identifying the samples in the batch.
280
+ batch : Any
281
+ Input batch.
282
+ batch_idx : int
283
+ Batch index.
284
+ dataloader_idx : int
285
+ Dataloader index.
286
+ dirpath : Path
287
+ Path to directory to save predictions to.
288
+
289
+ Raises
290
+ ------
291
+ NotImplementedError
292
+ """
293
+ raise NotImplementedError
294
+
295
+
296
+ class WriteImage(WriteStrategy):
297
+ """
298
+ A strategy for writing image predictions (i.e. un-tiled predictions).
299
+
300
+ Parameters
301
+ ----------
302
+ write_func : WriteFunc
303
+ Function used to save predictions.
304
+ write_extension : str
305
+ Extension added to prediction file paths.
306
+ write_func_kwargs : dict of {str: Any}
307
+ Extra kwargs to pass to `write_func`.
308
+
309
+ Attributes
310
+ ----------
311
+ write_func : WriteFunc
312
+ Function used to save predictions.
313
+ write_extension : str
314
+ Extension added to prediction file paths.
315
+ write_func_kwargs : dict of {str: Any}
316
+ Extra kwargs to pass to `write_func`.
317
+ """
318
+
319
+ def __init__(
320
+ self,
321
+ write_func: WriteFunc,
322
+ write_extension: str,
323
+ write_func_kwargs: dict[str, Any],
324
+ ) -> None:
325
+ """
326
+ A strategy for writing image predictions (i.e. un-tiled predictions).
327
+
328
+ Parameters
329
+ ----------
330
+ write_func : WriteFunc
331
+ Function used to save predictions.
332
+ write_extension : str
333
+ Extension added to prediction file paths.
334
+ write_func_kwargs : dict of {str: Any}
335
+ Extra kwargs to pass to `write_func`.
336
+ """
337
+ super().__init__()
338
+
339
+ self.write_func: WriteFunc = write_func
340
+ self.write_extension: str = write_extension
341
+ self.write_func_kwargs: dict[str, Any] = write_func_kwargs
342
+
343
+ def write_batch(
344
+ self,
345
+ trainer: Trainer,
346
+ pl_module: LightningModule,
347
+ prediction: NDArray,
348
+ batch_indices: Optional[Sequence[int]],
349
+ batch: NDArray,
350
+ batch_idx: int,
351
+ dataloader_idx: int,
352
+ dirpath: Path,
353
+ ) -> None:
354
+ """
355
+ Save full images.
356
+
357
+ Parameters
358
+ ----------
359
+ trainer : Trainer
360
+ PyTorch Lightning Trainer.
361
+ pl_module : LightningModule
362
+ PyTorch Lightning LightningModule.
363
+ prediction : Any
364
+ Predictions on `batch`.
365
+ batch_indices : sequence of int
366
+ Indices identifying the samples in the batch.
367
+ batch : Any
368
+ Input batch.
369
+ batch_idx : int
370
+ Batch index.
371
+ dataloader_idx : int
372
+ Dataloader index.
373
+ dirpath : Path
374
+ Path to directory to save predictions to.
375
+
376
+ Raises
377
+ ------
378
+ TypeError
379
+ If trainer prediction dataset is not `IterablePredDataset`.
380
+ """
381
+ dls: Union[DataLoader, list[DataLoader]] = trainer.predict_dataloaders
382
+ dl: DataLoader = dls[dataloader_idx] if isinstance(dls, list) else dls
383
+ ds: IterablePredDataset = dl.dataset
384
+ if not isinstance(ds, IterablePredDataset):
385
+ raise TypeError("Prediction dataset is not `IterablePredDataset`.")
386
+
387
+ for i in range(prediction.shape[0]):
388
+ prediction_image = prediction[0]
389
+ sample_id = batch_idx * dl.batch_size + i
390
+ input_file_path = get_sample_file_path(dataset=ds, sample_id=sample_id)
391
+ file_path = create_write_file_path(
392
+ dirpath=dirpath,
393
+ file_path=input_file_path,
394
+ write_extension=self.write_extension,
395
+ )
396
+ self.write_func(
397
+ file_path=file_path, img=prediction_image, **self.write_func_kwargs
398
+ )