careamics 0.1.0rc6__py3-none-any.whl → 0.1.0rc7__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.
- careamics/careamist.py +163 -266
- careamics/config/algorithm_model.py +0 -15
- careamics/config/architectures/custom_model.py +3 -3
- careamics/config/configuration_example.py +0 -3
- careamics/config/configuration_factory.py +23 -25
- careamics/config/configuration_model.py +11 -11
- careamics/config/data_model.py +80 -50
- careamics/config/inference_model.py +29 -17
- careamics/config/optimizer_models.py +7 -7
- careamics/config/support/supported_transforms.py +0 -1
- careamics/config/tile_information.py +26 -58
- careamics/config/transformations/normalize_model.py +32 -4
- careamics/config/validators/validator_utils.py +1 -1
- careamics/dataset/__init__.py +12 -1
- careamics/dataset/dataset_utils/__init__.py +8 -1
- careamics/dataset/dataset_utils/file_utils.py +1 -1
- careamics/dataset/dataset_utils/iterate_over_files.py +83 -0
- careamics/dataset/dataset_utils/read_tiff.py +0 -9
- careamics/dataset/dataset_utils/running_stats.py +186 -0
- careamics/dataset/in_memory_dataset.py +66 -171
- careamics/dataset/in_memory_pred_dataset.py +88 -0
- careamics/dataset/in_memory_tiled_pred_dataset.py +129 -0
- careamics/dataset/iterable_dataset.py +92 -249
- careamics/dataset/iterable_pred_dataset.py +121 -0
- careamics/dataset/iterable_tiled_pred_dataset.py +139 -0
- careamics/dataset/patching/patching.py +54 -25
- careamics/dataset/patching/random_patching.py +9 -4
- careamics/dataset/patching/validate_patch_dimension.py +5 -3
- careamics/dataset/tiling/__init__.py +10 -0
- careamics/dataset/tiling/collate_tiles.py +33 -0
- careamics/dataset/{patching → tiling}/tiled_patching.py +4 -4
- careamics/lightning_datamodule.py +1 -6
- careamics/lightning_module.py +11 -7
- careamics/lightning_prediction_datamodule.py +52 -72
- careamics/lvae_training/__init__.py +0 -0
- careamics/lvae_training/data_modules.py +1220 -0
- careamics/lvae_training/data_utils.py +618 -0
- careamics/lvae_training/eval_utils.py +905 -0
- careamics/lvae_training/get_config.py +84 -0
- careamics/lvae_training/lightning_module.py +701 -0
- careamics/lvae_training/metrics.py +214 -0
- careamics/lvae_training/train_lvae.py +339 -0
- careamics/lvae_training/train_utils.py +121 -0
- careamics/model_io/bioimage/model_description.py +40 -32
- careamics/model_io/bmz_io.py +1 -1
- careamics/model_io/model_io_utils.py +5 -2
- careamics/models/lvae/__init__.py +0 -0
- careamics/models/lvae/layers.py +1998 -0
- careamics/models/lvae/likelihoods.py +312 -0
- careamics/models/lvae/lvae.py +985 -0
- careamics/models/lvae/noise_models.py +409 -0
- careamics/models/lvae/utils.py +395 -0
- careamics/prediction_utils/__init__.py +12 -0
- careamics/prediction_utils/create_pred_datamodule.py +185 -0
- careamics/prediction_utils/prediction_outputs.py +165 -0
- careamics/prediction_utils/stitch_prediction.py +100 -0
- careamics/transforms/n2v_manipulate.py +3 -1
- careamics/transforms/normalize.py +139 -68
- careamics/transforms/pixel_manipulation.py +33 -9
- careamics/transforms/tta.py +43 -29
- careamics/utils/ram.py +2 -2
- {careamics-0.1.0rc6.dist-info → careamics-0.1.0rc7.dist-info}/METADATA +7 -6
- {careamics-0.1.0rc6.dist-info → careamics-0.1.0rc7.dist-info}/RECORD +65 -42
- {careamics-0.1.0rc6.dist-info → careamics-0.1.0rc7.dist-info}/WHEEL +1 -1
- careamics/lightning_prediction_loop.py +0 -118
- careamics/prediction/__init__.py +0 -7
- careamics/prediction/stitch_prediction.py +0 -70
- careamics/utils/running_stats.py +0 -43
- {careamics-0.1.0rc6.dist-info → careamics-0.1.0rc7.dist-info}/licenses/LICENSE +0 -0
|
@@ -0,0 +1,395 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Script for utility functions needed by the LVAE model.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from typing import Iterable
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
import torch
|
|
9
|
+
import torch.nn as nn
|
|
10
|
+
import torchvision.transforms.functional as F
|
|
11
|
+
from torch.distributions.normal import Normal
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def torch_nanmean(inp):
|
|
15
|
+
return torch.mean(inp[~inp.isnan()])
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def compute_batch_mean(x):
|
|
19
|
+
N = len(x)
|
|
20
|
+
return x.view(N, -1).mean(dim=1)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def power_of_2(self, x):
|
|
24
|
+
assert isinstance(x, int)
|
|
25
|
+
if x == 1:
|
|
26
|
+
return True
|
|
27
|
+
if x == 0:
|
|
28
|
+
# happens with validation
|
|
29
|
+
return False
|
|
30
|
+
if x % 2 == 1:
|
|
31
|
+
return False
|
|
32
|
+
return self.power_of_2(x // 2)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class Enum:
|
|
36
|
+
@classmethod
|
|
37
|
+
def name(cls, enum_type):
|
|
38
|
+
for key, value in cls.__dict__.items():
|
|
39
|
+
if enum_type == value:
|
|
40
|
+
return key
|
|
41
|
+
|
|
42
|
+
@classmethod
|
|
43
|
+
def contains(cls, enum_type):
|
|
44
|
+
for key, value in cls.__dict__.items():
|
|
45
|
+
if enum_type == value:
|
|
46
|
+
return True
|
|
47
|
+
return False
|
|
48
|
+
|
|
49
|
+
@classmethod
|
|
50
|
+
def from_name(cls, enum_type_str):
|
|
51
|
+
for key, value in cls.__dict__.items():
|
|
52
|
+
if key == enum_type_str:
|
|
53
|
+
return value
|
|
54
|
+
assert f"{cls.__name__}:{enum_type_str} doesnot exist."
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class LossType(Enum):
|
|
58
|
+
Elbo = 0
|
|
59
|
+
ElboWithCritic = 1
|
|
60
|
+
ElboMixedReconstruction = 2
|
|
61
|
+
MSE = 3
|
|
62
|
+
ElboWithNbrConsistency = 4
|
|
63
|
+
ElboSemiSupMixedReconstruction = 5
|
|
64
|
+
ElboCL = 6
|
|
65
|
+
ElboRestrictedReconstruction = 7
|
|
66
|
+
DenoiSplitMuSplit = 8
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class ModelType(Enum):
|
|
70
|
+
LadderVae = 3
|
|
71
|
+
LadderVaeTwinDecoder = 4
|
|
72
|
+
LadderVAECritic = 5
|
|
73
|
+
# Separate vampprior: two optimizers
|
|
74
|
+
LadderVaeSepVampprior = 6
|
|
75
|
+
# one encoder for mixed input, two for separate inputs.
|
|
76
|
+
LadderVaeSepEncoder = 7
|
|
77
|
+
LadderVAEMultiTarget = 8
|
|
78
|
+
LadderVaeSepEncoderSingleOptim = 9
|
|
79
|
+
UNet = 10
|
|
80
|
+
BraveNet = 11
|
|
81
|
+
LadderVaeStitch = 12
|
|
82
|
+
LadderVaeSemiSupervised = 13
|
|
83
|
+
LadderVaeStitch2Stage = 14 # Note that previously trained models will have issue.
|
|
84
|
+
# since earlier, LadderVaeStitch2Stage = 13, LadderVaeSemiSupervised = 14
|
|
85
|
+
LadderVaeMixedRecons = 15
|
|
86
|
+
LadderVaeCL = 16
|
|
87
|
+
LadderVaeTwoDataSet = (
|
|
88
|
+
17 # on one subdset, apply disentanglement, on other apply reconstruction
|
|
89
|
+
)
|
|
90
|
+
LadderVaeTwoDatasetMultiBranch = 18
|
|
91
|
+
LadderVaeTwoDatasetMultiOptim = 19
|
|
92
|
+
LVaeDeepEncoderIntensityAug = 20
|
|
93
|
+
AutoRegresiveLadderVAE = 21
|
|
94
|
+
LadderVAEInterleavedOptimization = 22
|
|
95
|
+
Denoiser = 23
|
|
96
|
+
DenoiserSplitter = 24
|
|
97
|
+
SplitterDenoiser = 25
|
|
98
|
+
LadderVAERestrictedReconstruction = 26
|
|
99
|
+
LadderVAETwoDataSetRestRecon = 27
|
|
100
|
+
LadderVAETwoDataSetFinetuning = 28
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _pad_crop_img(x, size, mode) -> torch.Tensor:
|
|
104
|
+
"""Pads or crops a tensor.
|
|
105
|
+
Pads or crops a tensor of shape (batch, channels, h, w) to new height
|
|
106
|
+
and width given by a tuple.
|
|
107
|
+
Args:
|
|
108
|
+
x (torch.Tensor): Input image
|
|
109
|
+
size (list or tuple): Desired size (height, width)
|
|
110
|
+
mode (str): Mode, either 'pad' or 'crop'
|
|
111
|
+
Returns:
|
|
112
|
+
The padded or cropped tensor
|
|
113
|
+
"""
|
|
114
|
+
assert x.dim() == 4 and len(size) == 2
|
|
115
|
+
size = tuple(size)
|
|
116
|
+
x_size = x.size()[2:4]
|
|
117
|
+
if mode == "pad":
|
|
118
|
+
cond = x_size[0] > size[0] or x_size[1] > size[1]
|
|
119
|
+
elif mode == "crop":
|
|
120
|
+
cond = x_size[0] < size[0] or x_size[1] < size[1]
|
|
121
|
+
else:
|
|
122
|
+
raise ValueError(f"invalid mode '{mode}'")
|
|
123
|
+
if cond:
|
|
124
|
+
raise ValueError(f"trying to {mode} from size {x_size} to size {size}")
|
|
125
|
+
dr, dc = (abs(x_size[0] - size[0]), abs(x_size[1] - size[1]))
|
|
126
|
+
dr1, dr2 = dr // 2, dr - (dr // 2)
|
|
127
|
+
dc1, dc2 = dc // 2, dc - (dc // 2)
|
|
128
|
+
if mode == "pad":
|
|
129
|
+
return nn.functional.pad(x, [dc1, dc2, dr1, dr2, 0, 0, 0, 0])
|
|
130
|
+
elif mode == "crop":
|
|
131
|
+
return x[:, :, dr1 : x_size[0] - dr2, dc1 : x_size[1] - dc2]
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def pad_img_tensor(x, size) -> torch.Tensor:
|
|
135
|
+
"""Pads a tensor.
|
|
136
|
+
Pads a tensor of shape (batch, channels, h, w) to a desired height and width.
|
|
137
|
+
Args:
|
|
138
|
+
x (torch.Tensor): Input image
|
|
139
|
+
size (list or tuple): Desired size (height, width)
|
|
140
|
+
|
|
141
|
+
Returns
|
|
142
|
+
-------
|
|
143
|
+
The padded tensor
|
|
144
|
+
"""
|
|
145
|
+
return _pad_crop_img(x, size, "pad")
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def crop_img_tensor(x, size) -> torch.Tensor:
|
|
149
|
+
"""Crops a tensor.
|
|
150
|
+
Crops a tensor of shape (batch, channels, h, w) to a desired height and width
|
|
151
|
+
given by a tuple.
|
|
152
|
+
Args:
|
|
153
|
+
x (torch.Tensor): Input image
|
|
154
|
+
size (list or tuple): Desired size (height, width)
|
|
155
|
+
|
|
156
|
+
Returns
|
|
157
|
+
-------
|
|
158
|
+
The cropped tensor
|
|
159
|
+
"""
|
|
160
|
+
return _pad_crop_img(x, size, "crop")
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
class StableExponential:
|
|
164
|
+
"""
|
|
165
|
+
Class that redefines the definition of exp() to increase numerical stability.
|
|
166
|
+
Naturally, also the definition of log() must change accordingly.
|
|
167
|
+
However, it is worth noting that the two operations remain one the inverse of the other,
|
|
168
|
+
meaning that x = log(exp(x)) and x = exp(log(x)) are always true.
|
|
169
|
+
|
|
170
|
+
Definition:
|
|
171
|
+
exp(x) = {
|
|
172
|
+
exp(x) if x<=0
|
|
173
|
+
x+1 if x>0
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
log(x) = {
|
|
177
|
+
x if x<=0
|
|
178
|
+
log(1+x) if x>0
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
NOTE 1:
|
|
182
|
+
Within the class everything is done on the tensor given as input to the constructor.
|
|
183
|
+
Therefore, when exp() is called, self._tensor.exp() is computed.
|
|
184
|
+
When log() is called, torch.log(self._tensor.exp()) is computed instead.
|
|
185
|
+
|
|
186
|
+
NOTE 2:
|
|
187
|
+
Given the output from exp(), torch.log() or the log() method of the class give identical results.
|
|
188
|
+
"""
|
|
189
|
+
|
|
190
|
+
def __init__(self, tensor):
|
|
191
|
+
self._raw_tensor = tensor
|
|
192
|
+
posneg_dic = self.posneg_separation(self._raw_tensor)
|
|
193
|
+
self.pos_f, self.neg_f = posneg_dic["filter"]
|
|
194
|
+
self.pos_data, self.neg_data = posneg_dic["value"]
|
|
195
|
+
|
|
196
|
+
def posneg_separation(self, tensor):
|
|
197
|
+
pos = tensor > 0
|
|
198
|
+
pos_tensor = torch.clip(tensor, min=0)
|
|
199
|
+
|
|
200
|
+
neg = tensor <= 0
|
|
201
|
+
neg_tensor = torch.clip(tensor, max=0)
|
|
202
|
+
|
|
203
|
+
return {"filter": [pos, neg], "value": [pos_tensor, neg_tensor]}
|
|
204
|
+
|
|
205
|
+
def exp(self):
|
|
206
|
+
return torch.exp(self.neg_data) * self.neg_f + (1 + self.pos_data) * self.pos_f
|
|
207
|
+
|
|
208
|
+
def log(self):
|
|
209
|
+
return self.neg_data * self.neg_f + torch.log(1 + self.pos_data) * self.pos_f
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
class StableLogVar:
|
|
213
|
+
"""
|
|
214
|
+
Class that provides a numerically stable implementation of Log-Variance.
|
|
215
|
+
Specifically, it uses the exp() and log() formulas defined in `StableExponential` class.
|
|
216
|
+
"""
|
|
217
|
+
|
|
218
|
+
def __init__(
|
|
219
|
+
self, logvar: torch.Tensor, enable_stable: bool = True, var_eps: float = 1e-6
|
|
220
|
+
):
|
|
221
|
+
"""
|
|
222
|
+
Contructor.
|
|
223
|
+
|
|
224
|
+
Parameters
|
|
225
|
+
----------
|
|
226
|
+
logvar: torch.Tensor
|
|
227
|
+
The input (true) logvar vector, to be converted in the Stable version.
|
|
228
|
+
enable_stable: bool, optional
|
|
229
|
+
Whether to compute the stable version of log-variance. Default is `True`.
|
|
230
|
+
var_eps: float, optional
|
|
231
|
+
The minimum value attainable by the variance. Default is `1e-6`.
|
|
232
|
+
"""
|
|
233
|
+
self._lv = logvar
|
|
234
|
+
self._enable_stable = enable_stable
|
|
235
|
+
self._eps = var_eps
|
|
236
|
+
|
|
237
|
+
def get(self) -> torch.Tensor:
|
|
238
|
+
if self._enable_stable is False:
|
|
239
|
+
return self._lv
|
|
240
|
+
|
|
241
|
+
return torch.log(self.get_var())
|
|
242
|
+
|
|
243
|
+
def get_var(self) -> torch.Tensor:
|
|
244
|
+
"""
|
|
245
|
+
Get Variance from Log-Variance.
|
|
246
|
+
"""
|
|
247
|
+
if self._enable_stable is False:
|
|
248
|
+
return torch.exp(self._lv)
|
|
249
|
+
return StableExponential(self._lv).exp() + self._eps
|
|
250
|
+
|
|
251
|
+
def get_std(self) -> torch.Tensor:
|
|
252
|
+
return torch.sqrt(self.get_var())
|
|
253
|
+
|
|
254
|
+
def centercrop_to_size(self, size: Iterable[int]) -> None:
|
|
255
|
+
"""
|
|
256
|
+
Centercrop the log-variance tensor to the desired size.
|
|
257
|
+
|
|
258
|
+
Parameters
|
|
259
|
+
----------
|
|
260
|
+
size: torch.Tensor
|
|
261
|
+
The desired size of the log-variance tensor.
|
|
262
|
+
"""
|
|
263
|
+
if self._lv.shape[-1] == size:
|
|
264
|
+
return
|
|
265
|
+
|
|
266
|
+
diff = self._lv.shape[-1] - size
|
|
267
|
+
assert diff > 0 and diff % 2 == 0
|
|
268
|
+
self._lv = F.center_crop(self._lv, (size, size))
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
class StableMean:
|
|
272
|
+
|
|
273
|
+
def __init__(self, mean):
|
|
274
|
+
self._mean = mean
|
|
275
|
+
|
|
276
|
+
def get(self) -> torch.Tensor:
|
|
277
|
+
return self._mean
|
|
278
|
+
|
|
279
|
+
def centercrop_to_size(self, size: Iterable[int]) -> None:
|
|
280
|
+
"""
|
|
281
|
+
Centercrop the mean tensor to the desired size.
|
|
282
|
+
|
|
283
|
+
Parameters
|
|
284
|
+
----------
|
|
285
|
+
size: torch.Tensor
|
|
286
|
+
The desired size of the log-variance tensor.
|
|
287
|
+
"""
|
|
288
|
+
if self._mean.shape[-1] == size:
|
|
289
|
+
return
|
|
290
|
+
|
|
291
|
+
diff = self._mean.shape[-1] - size
|
|
292
|
+
assert diff > 0 and diff % 2 == 0
|
|
293
|
+
self._mean = F.center_crop(self._mean, (size, size))
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def allow_numpy(func):
|
|
297
|
+
"""
|
|
298
|
+
All optional arguements are passed as is. positional arguments are checked. if they are numpy array,
|
|
299
|
+
they are converted to torch Tensor.
|
|
300
|
+
"""
|
|
301
|
+
|
|
302
|
+
def numpy_wrapper(*args, **kwargs):
|
|
303
|
+
new_args = []
|
|
304
|
+
for arg in args:
|
|
305
|
+
if isinstance(arg, np.ndarray):
|
|
306
|
+
arg = torch.Tensor(arg)
|
|
307
|
+
new_args.append(arg)
|
|
308
|
+
new_args = tuple(new_args)
|
|
309
|
+
|
|
310
|
+
output = func(*new_args, **kwargs)
|
|
311
|
+
return output
|
|
312
|
+
|
|
313
|
+
return numpy_wrapper
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
class Interpolate(nn.Module):
|
|
317
|
+
"""Wrapper for torch.nn.functional.interpolate."""
|
|
318
|
+
|
|
319
|
+
def __init__(self, size=None, scale=None, mode="bilinear", align_corners=False):
|
|
320
|
+
super().__init__()
|
|
321
|
+
assert (size is None) == (scale is not None)
|
|
322
|
+
self.size = size
|
|
323
|
+
self.scale = scale
|
|
324
|
+
self.mode = mode
|
|
325
|
+
self.align_corners = align_corners
|
|
326
|
+
|
|
327
|
+
def forward(self, x):
|
|
328
|
+
out = F.interpolate(
|
|
329
|
+
x,
|
|
330
|
+
size=self.size,
|
|
331
|
+
scale_factor=self.scale,
|
|
332
|
+
mode=self.mode,
|
|
333
|
+
align_corners=self.align_corners,
|
|
334
|
+
)
|
|
335
|
+
return out
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def kl_normal_mc(z, p_mulv, q_mulv):
|
|
339
|
+
"""
|
|
340
|
+
One-sample estimation of element-wise KL between two diagonal
|
|
341
|
+
multivariate normal distributions. Any number of dimensions,
|
|
342
|
+
broadcasting supported (be careful).
|
|
343
|
+
:param z:
|
|
344
|
+
:param p_mulv:
|
|
345
|
+
:param q_mulv:
|
|
346
|
+
:return:
|
|
347
|
+
"""
|
|
348
|
+
assert isinstance(p_mulv, tuple)
|
|
349
|
+
assert isinstance(q_mulv, tuple)
|
|
350
|
+
p_mu, p_lv = p_mulv
|
|
351
|
+
q_mu, q_lv = q_mulv
|
|
352
|
+
|
|
353
|
+
p_std = p_lv.get_std()
|
|
354
|
+
q_std = q_lv.get_std()
|
|
355
|
+
|
|
356
|
+
p_distrib = Normal(p_mu.get(), p_std)
|
|
357
|
+
q_distrib = Normal(q_mu.get(), q_std)
|
|
358
|
+
return q_distrib.log_prob(z) - p_distrib.log_prob(z)
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
def free_bits_kl(
|
|
362
|
+
kl: torch.Tensor, free_bits: float, batch_average: bool = False, eps: float = 1e-6
|
|
363
|
+
) -> torch.Tensor:
|
|
364
|
+
"""
|
|
365
|
+
Computes free-bits version of KL divergence.
|
|
366
|
+
Ensures that the KL doesn't go to zero for any latent dimension.
|
|
367
|
+
Hence, it contributes to use latent variables more efficiently,
|
|
368
|
+
leading to better representation learning.
|
|
369
|
+
|
|
370
|
+
NOTE:
|
|
371
|
+
Takes in the KL with shape (batch size, layers), returns the KL with
|
|
372
|
+
free bits (for optimization) with shape (layers,), which is the average
|
|
373
|
+
free-bits KL per layer in the current batch.
|
|
374
|
+
If batch_average is False (default), the free bits are per layer and
|
|
375
|
+
per batch element. Otherwise, the free bits are still per layer, but
|
|
376
|
+
are assigned on average to the whole batch. In both cases, the batch
|
|
377
|
+
average is returned, so it's simply a matter of doing mean(clamp(KL))
|
|
378
|
+
or clamp(mean(KL)).
|
|
379
|
+
|
|
380
|
+
Args:
|
|
381
|
+
kl (torch.Tensor)
|
|
382
|
+
free_bits (float)
|
|
383
|
+
batch_average (bool, optional))
|
|
384
|
+
eps (float, optional)
|
|
385
|
+
|
|
386
|
+
Returns
|
|
387
|
+
-------
|
|
388
|
+
The KL with free bits
|
|
389
|
+
"""
|
|
390
|
+
assert kl.dim() == 2
|
|
391
|
+
if free_bits < eps:
|
|
392
|
+
return kl.mean(0)
|
|
393
|
+
if batch_average:
|
|
394
|
+
return kl.mean(0).clamp(min=free_bits)
|
|
395
|
+
return kl.clamp(min=free_bits).mean(0)
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""Package to house various prediction utilies."""
|
|
2
|
+
|
|
3
|
+
__all__ = [
|
|
4
|
+
"create_pred_datamodule",
|
|
5
|
+
"stitch_prediction",
|
|
6
|
+
"stitch_prediction_single",
|
|
7
|
+
"convert_outputs",
|
|
8
|
+
]
|
|
9
|
+
|
|
10
|
+
from .create_pred_datamodule import create_pred_datamodule
|
|
11
|
+
from .prediction_outputs import convert_outputs
|
|
12
|
+
from .stitch_prediction import stitch_prediction, stitch_prediction_single
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
"""Module containing functions to create `CAREamicsPredictData`."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import Callable, Dict, Literal, Optional, Tuple, Union
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
from numpy.typing import NDArray
|
|
8
|
+
|
|
9
|
+
from careamics.config import Configuration, create_inference_configuration
|
|
10
|
+
from careamics.utils import check_path_exists
|
|
11
|
+
|
|
12
|
+
from ..lightning_prediction_datamodule import CAREamicsPredictData
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def create_pred_datamodule(
|
|
16
|
+
source: Union[CAREamicsPredictData, Path, str, NDArray],
|
|
17
|
+
config: Configuration,
|
|
18
|
+
batch_size: Optional[int] = None,
|
|
19
|
+
tile_size: Optional[Tuple[int, ...]] = None,
|
|
20
|
+
tile_overlap: Tuple[int, ...] = (48, 48),
|
|
21
|
+
axes: Optional[str] = None,
|
|
22
|
+
data_type: Optional[Literal["array", "tiff", "custom"]] = None,
|
|
23
|
+
tta_transforms: bool = True,
|
|
24
|
+
dataloader_params: Optional[Dict] = None,
|
|
25
|
+
read_source_func: Optional[Callable] = None,
|
|
26
|
+
extension_filter: str = "",
|
|
27
|
+
) -> CAREamicsPredictData:
|
|
28
|
+
"""
|
|
29
|
+
Create a `CAREamicsPredictData` module.
|
|
30
|
+
|
|
31
|
+
Parameters
|
|
32
|
+
----------
|
|
33
|
+
source : CAREamicsPredData, pathlib.Path, str or numpy.ndarray
|
|
34
|
+
Data to predict on.
|
|
35
|
+
config : Configuration
|
|
36
|
+
Global configuration.
|
|
37
|
+
batch_size : int, default=1
|
|
38
|
+
Batch size for prediction.
|
|
39
|
+
tile_size : tuple of int, optional
|
|
40
|
+
Size of the tiles to use for prediction.
|
|
41
|
+
tile_overlap : tuple of int, default=(48, 48)
|
|
42
|
+
Overlap between tiles.
|
|
43
|
+
axes : str, optional
|
|
44
|
+
Axes of the input data, by default None.
|
|
45
|
+
data_type : {"array", "tiff", "custom"}, optional
|
|
46
|
+
Type of the input data.
|
|
47
|
+
tta_transforms : bool, default=True
|
|
48
|
+
Whether to apply test-time augmentation.
|
|
49
|
+
dataloader_params : dict, optional
|
|
50
|
+
Parameters to pass to the dataloader.
|
|
51
|
+
read_source_func : Callable, optional
|
|
52
|
+
Function to read the source data.
|
|
53
|
+
extension_filter : str, default=""
|
|
54
|
+
Filter for the file extension.
|
|
55
|
+
|
|
56
|
+
Returns
|
|
57
|
+
-------
|
|
58
|
+
prediction datamodule: CAREamicsPredictData
|
|
59
|
+
Subclass of `pytorch_lightning.LightningDataModule` for creating predictions.
|
|
60
|
+
|
|
61
|
+
Raises
|
|
62
|
+
------
|
|
63
|
+
ValueError
|
|
64
|
+
If the input is not a CAREamicsPredData instance, a path or a numpy array.
|
|
65
|
+
"""
|
|
66
|
+
# Reuse batch size if not provided explicitly
|
|
67
|
+
if batch_size is None:
|
|
68
|
+
batch_size = config.data_config.batch_size
|
|
69
|
+
|
|
70
|
+
# create predict config, reuse training config if parameters missing
|
|
71
|
+
prediction_config = create_inference_configuration(
|
|
72
|
+
configuration=config,
|
|
73
|
+
tile_size=tile_size,
|
|
74
|
+
tile_overlap=tile_overlap,
|
|
75
|
+
data_type=data_type,
|
|
76
|
+
axes=axes,
|
|
77
|
+
tta_transforms=tta_transforms,
|
|
78
|
+
batch_size=batch_size,
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
# remove batch from dataloader parameters (priority given to config)
|
|
82
|
+
if dataloader_params is None:
|
|
83
|
+
dataloader_params = {}
|
|
84
|
+
if "batch_size" in dataloader_params:
|
|
85
|
+
del dataloader_params["batch_size"]
|
|
86
|
+
|
|
87
|
+
if isinstance(source, CAREamicsPredictData):
|
|
88
|
+
pred_datamodule = source
|
|
89
|
+
elif isinstance(source, Path) or isinstance(source, str):
|
|
90
|
+
pred_datamodule = _create_from_path(
|
|
91
|
+
source=source,
|
|
92
|
+
pred_config=prediction_config,
|
|
93
|
+
read_source_func=read_source_func,
|
|
94
|
+
extension_filter=extension_filter,
|
|
95
|
+
dataloader_params=dataloader_params,
|
|
96
|
+
)
|
|
97
|
+
elif isinstance(source, np.ndarray):
|
|
98
|
+
pred_datamodule = _create_from_array(
|
|
99
|
+
source=source,
|
|
100
|
+
pred_config=prediction_config,
|
|
101
|
+
dataloader_params=dataloader_params,
|
|
102
|
+
)
|
|
103
|
+
else:
|
|
104
|
+
raise ValueError(
|
|
105
|
+
f"Invalid input. Expected a CAREamicsPredData instance, paths or "
|
|
106
|
+
f"NDArray (got {type(source)})."
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
return pred_datamodule
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _create_from_path(
|
|
113
|
+
source: Union[Path, str],
|
|
114
|
+
pred_config: Configuration,
|
|
115
|
+
read_source_func: Optional[Callable] = None,
|
|
116
|
+
extension_filter: str = "",
|
|
117
|
+
dataloader_params: Optional[Dict] = None,
|
|
118
|
+
**kwargs,
|
|
119
|
+
) -> CAREamicsPredictData:
|
|
120
|
+
"""
|
|
121
|
+
Create `CAREamicsPredictData` from path.
|
|
122
|
+
|
|
123
|
+
Parameters
|
|
124
|
+
----------
|
|
125
|
+
source : Path or str
|
|
126
|
+
_Data to predict on.
|
|
127
|
+
pred_config : Configuration
|
|
128
|
+
Prediction configuration.
|
|
129
|
+
read_source_func : Callable, optional
|
|
130
|
+
Function to read the source data.
|
|
131
|
+
extension_filter : str, default=""
|
|
132
|
+
Function to read the source data.
|
|
133
|
+
dataloader_params : Optional[Dict], optional
|
|
134
|
+
Parameters to pass to the dataloader.
|
|
135
|
+
**kwargs
|
|
136
|
+
Unused.
|
|
137
|
+
|
|
138
|
+
Returns
|
|
139
|
+
-------
|
|
140
|
+
prediction datamodule: CAREamicsPredictData
|
|
141
|
+
Subclass of `pytorch_lightning.LightningDataModule` for creating predictions.
|
|
142
|
+
"""
|
|
143
|
+
source_path = check_path_exists(source)
|
|
144
|
+
|
|
145
|
+
datamodule = CAREamicsPredictData(
|
|
146
|
+
pred_config=pred_config,
|
|
147
|
+
pred_data=source_path,
|
|
148
|
+
read_source_func=read_source_func,
|
|
149
|
+
extension_filter=extension_filter,
|
|
150
|
+
dataloader_params=dataloader_params,
|
|
151
|
+
)
|
|
152
|
+
return datamodule
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _create_from_array(
|
|
156
|
+
source: NDArray,
|
|
157
|
+
pred_config: Configuration,
|
|
158
|
+
dataloader_params: Optional[Dict] = None,
|
|
159
|
+
**kwargs,
|
|
160
|
+
) -> CAREamicsPredictData:
|
|
161
|
+
"""
|
|
162
|
+
Create `CAREamicsPredictData` from array.
|
|
163
|
+
|
|
164
|
+
Parameters
|
|
165
|
+
----------
|
|
166
|
+
source : Path or str
|
|
167
|
+
_Data to predict on.
|
|
168
|
+
pred_config : Configuration
|
|
169
|
+
Prediction configuration.
|
|
170
|
+
dataloader_params : Optional[Dict], optional
|
|
171
|
+
Parameters to pass to the dataloader.
|
|
172
|
+
**kwargs
|
|
173
|
+
Unused. Added for compatible function signature with `_create_from_path`.
|
|
174
|
+
|
|
175
|
+
Returns
|
|
176
|
+
-------
|
|
177
|
+
prediction datamodule: CAREamicsPredictData
|
|
178
|
+
Subclass of `pytorch_lightning.LightningDataModule` for creating predictions.
|
|
179
|
+
"""
|
|
180
|
+
datamodule = CAREamicsPredictData(
|
|
181
|
+
pred_config=pred_config,
|
|
182
|
+
pred_data=source,
|
|
183
|
+
dataloader_params=dataloader_params,
|
|
184
|
+
)
|
|
185
|
+
return datamodule
|