senoquant 1.0.0b1__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.
Files changed (148) hide show
  1. senoquant/__init__.py +6 -0
  2. senoquant/_reader.py +7 -0
  3. senoquant/_widget.py +33 -0
  4. senoquant/napari.yaml +83 -0
  5. senoquant/reader/__init__.py +5 -0
  6. senoquant/reader/core.py +369 -0
  7. senoquant/tabs/__init__.py +15 -0
  8. senoquant/tabs/batch/__init__.py +10 -0
  9. senoquant/tabs/batch/backend.py +641 -0
  10. senoquant/tabs/batch/config.py +270 -0
  11. senoquant/tabs/batch/frontend.py +1283 -0
  12. senoquant/tabs/batch/io.py +326 -0
  13. senoquant/tabs/batch/layers.py +86 -0
  14. senoquant/tabs/quantification/__init__.py +1 -0
  15. senoquant/tabs/quantification/backend.py +228 -0
  16. senoquant/tabs/quantification/features/__init__.py +80 -0
  17. senoquant/tabs/quantification/features/base.py +142 -0
  18. senoquant/tabs/quantification/features/marker/__init__.py +5 -0
  19. senoquant/tabs/quantification/features/marker/config.py +69 -0
  20. senoquant/tabs/quantification/features/marker/dialog.py +437 -0
  21. senoquant/tabs/quantification/features/marker/export.py +879 -0
  22. senoquant/tabs/quantification/features/marker/feature.py +119 -0
  23. senoquant/tabs/quantification/features/marker/morphology.py +285 -0
  24. senoquant/tabs/quantification/features/marker/rows.py +654 -0
  25. senoquant/tabs/quantification/features/marker/thresholding.py +46 -0
  26. senoquant/tabs/quantification/features/roi.py +346 -0
  27. senoquant/tabs/quantification/features/spots/__init__.py +5 -0
  28. senoquant/tabs/quantification/features/spots/config.py +62 -0
  29. senoquant/tabs/quantification/features/spots/dialog.py +477 -0
  30. senoquant/tabs/quantification/features/spots/export.py +1292 -0
  31. senoquant/tabs/quantification/features/spots/feature.py +112 -0
  32. senoquant/tabs/quantification/features/spots/morphology.py +279 -0
  33. senoquant/tabs/quantification/features/spots/rows.py +241 -0
  34. senoquant/tabs/quantification/frontend.py +815 -0
  35. senoquant/tabs/segmentation/__init__.py +1 -0
  36. senoquant/tabs/segmentation/backend.py +131 -0
  37. senoquant/tabs/segmentation/frontend.py +1009 -0
  38. senoquant/tabs/segmentation/models/__init__.py +5 -0
  39. senoquant/tabs/segmentation/models/base.py +146 -0
  40. senoquant/tabs/segmentation/models/cpsam/details.json +65 -0
  41. senoquant/tabs/segmentation/models/cpsam/model.py +150 -0
  42. senoquant/tabs/segmentation/models/default_2d/details.json +69 -0
  43. senoquant/tabs/segmentation/models/default_2d/model.py +664 -0
  44. senoquant/tabs/segmentation/models/default_3d/details.json +69 -0
  45. senoquant/tabs/segmentation/models/default_3d/model.py +682 -0
  46. senoquant/tabs/segmentation/models/hf.py +71 -0
  47. senoquant/tabs/segmentation/models/nuclear_dilation/__init__.py +1 -0
  48. senoquant/tabs/segmentation/models/nuclear_dilation/details.json +26 -0
  49. senoquant/tabs/segmentation/models/nuclear_dilation/model.py +96 -0
  50. senoquant/tabs/segmentation/models/perinuclear_rings/__init__.py +1 -0
  51. senoquant/tabs/segmentation/models/perinuclear_rings/details.json +34 -0
  52. senoquant/tabs/segmentation/models/perinuclear_rings/model.py +132 -0
  53. senoquant/tabs/segmentation/stardist_onnx_utils/__init__.py +2 -0
  54. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/__init__.py +3 -0
  55. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/data/__init__.py +6 -0
  56. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/data/generate.py +470 -0
  57. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/data/prepare.py +273 -0
  58. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/data/rawdata.py +112 -0
  59. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/data/transform.py +384 -0
  60. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/internals/__init__.py +0 -0
  61. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/internals/blocks.py +184 -0
  62. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/internals/losses.py +79 -0
  63. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/internals/nets.py +165 -0
  64. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/internals/predict.py +467 -0
  65. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/internals/probability.py +67 -0
  66. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/internals/train.py +148 -0
  67. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/io/__init__.py +163 -0
  68. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/models/__init__.py +52 -0
  69. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/models/base_model.py +329 -0
  70. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/models/care_isotropic.py +160 -0
  71. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/models/care_projection.py +178 -0
  72. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/models/care_standard.py +446 -0
  73. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/models/care_upsampling.py +54 -0
  74. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/models/config.py +254 -0
  75. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/models/pretrained.py +119 -0
  76. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/scripts/__init__.py +0 -0
  77. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/scripts/care_predict.py +180 -0
  78. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/utils/__init__.py +5 -0
  79. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/utils/plot_utils.py +159 -0
  80. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/utils/six.py +18 -0
  81. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/utils/tf.py +644 -0
  82. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/utils/utils.py +272 -0
  83. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/csbdeep/version.py +1 -0
  84. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/docs/source/conf.py +368 -0
  85. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/setup.py +68 -0
  86. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/tests/test_datagen.py +169 -0
  87. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/tests/test_models.py +462 -0
  88. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/tests/test_utils.py +166 -0
  89. senoquant/tabs/segmentation/stardist_onnx_utils/_csbdeep/tools/create_zip_contents.py +34 -0
  90. senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/__init__.py +30 -0
  91. senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/big.py +624 -0
  92. senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/bioimageio_utils.py +494 -0
  93. senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/data/__init__.py +39 -0
  94. senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/geometry/__init__.py +10 -0
  95. senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/geometry/geom2d.py +215 -0
  96. senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/geometry/geom3d.py +349 -0
  97. senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/matching.py +483 -0
  98. senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/models/__init__.py +28 -0
  99. senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/models/base.py +1217 -0
  100. senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/models/model2d.py +594 -0
  101. senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/models/model3d.py +696 -0
  102. senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/nms.py +384 -0
  103. senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/plot/__init__.py +2 -0
  104. senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/plot/plot.py +74 -0
  105. senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/plot/render.py +298 -0
  106. senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/rays3d.py +373 -0
  107. senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/sample_patches.py +65 -0
  108. senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/scripts/__init__.py +0 -0
  109. senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/scripts/predict2d.py +90 -0
  110. senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/scripts/predict3d.py +93 -0
  111. senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/utils.py +408 -0
  112. senoquant/tabs/segmentation/stardist_onnx_utils/_stardist/version.py +1 -0
  113. senoquant/tabs/segmentation/stardist_onnx_utils/onnx_framework/__init__.py +45 -0
  114. senoquant/tabs/segmentation/stardist_onnx_utils/onnx_framework/convert/__init__.py +17 -0
  115. senoquant/tabs/segmentation/stardist_onnx_utils/onnx_framework/convert/cli.py +55 -0
  116. senoquant/tabs/segmentation/stardist_onnx_utils/onnx_framework/convert/core.py +285 -0
  117. senoquant/tabs/segmentation/stardist_onnx_utils/onnx_framework/inspect/__init__.py +15 -0
  118. senoquant/tabs/segmentation/stardist_onnx_utils/onnx_framework/inspect/cli.py +36 -0
  119. senoquant/tabs/segmentation/stardist_onnx_utils/onnx_framework/inspect/divisibility.py +193 -0
  120. senoquant/tabs/segmentation/stardist_onnx_utils/onnx_framework/inspect/probe.py +100 -0
  121. senoquant/tabs/segmentation/stardist_onnx_utils/onnx_framework/inspect/receptive_field.py +182 -0
  122. senoquant/tabs/segmentation/stardist_onnx_utils/onnx_framework/inspect/rf_cli.py +48 -0
  123. senoquant/tabs/segmentation/stardist_onnx_utils/onnx_framework/inspect/valid_sizes.py +278 -0
  124. senoquant/tabs/segmentation/stardist_onnx_utils/onnx_framework/post/__init__.py +8 -0
  125. senoquant/tabs/segmentation/stardist_onnx_utils/onnx_framework/post/core.py +157 -0
  126. senoquant/tabs/segmentation/stardist_onnx_utils/onnx_framework/pre/__init__.py +17 -0
  127. senoquant/tabs/segmentation/stardist_onnx_utils/onnx_framework/pre/core.py +226 -0
  128. senoquant/tabs/segmentation/stardist_onnx_utils/onnx_framework/predict/__init__.py +5 -0
  129. senoquant/tabs/segmentation/stardist_onnx_utils/onnx_framework/predict/core.py +401 -0
  130. senoquant/tabs/settings/__init__.py +1 -0
  131. senoquant/tabs/settings/backend.py +29 -0
  132. senoquant/tabs/settings/frontend.py +19 -0
  133. senoquant/tabs/spots/__init__.py +1 -0
  134. senoquant/tabs/spots/backend.py +139 -0
  135. senoquant/tabs/spots/frontend.py +800 -0
  136. senoquant/tabs/spots/models/__init__.py +5 -0
  137. senoquant/tabs/spots/models/base.py +94 -0
  138. senoquant/tabs/spots/models/rmp/details.json +61 -0
  139. senoquant/tabs/spots/models/rmp/model.py +499 -0
  140. senoquant/tabs/spots/models/udwt/details.json +103 -0
  141. senoquant/tabs/spots/models/udwt/model.py +482 -0
  142. senoquant/utils.py +25 -0
  143. senoquant-1.0.0b1.dist-info/METADATA +193 -0
  144. senoquant-1.0.0b1.dist-info/RECORD +148 -0
  145. senoquant-1.0.0b1.dist-info/WHEEL +5 -0
  146. senoquant-1.0.0b1.dist-info/entry_points.txt +2 -0
  147. senoquant-1.0.0b1.dist-info/licenses/LICENSE +28 -0
  148. senoquant-1.0.0b1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,594 @@
1
+ from __future__ import print_function, unicode_literals, absolute_import, division
2
+
3
+ import numpy as np
4
+ import warnings
5
+ import math
6
+ from tqdm import tqdm
7
+
8
+ from csbdeep.models import BaseConfig
9
+ from csbdeep.internals.blocks import unet_block
10
+ from csbdeep.utils import _raise, backend_channels_last, axes_check_and_normalize, axes_dict
11
+ from csbdeep.utils.tf import keras_import, IS_TF_1, CARETensorBoard, CARETensorBoardImage, IS_KERAS_3_PLUS, BACKEND as K
12
+ from skimage.segmentation import clear_border
13
+ from skimage.measure import regionprops
14
+ from scipy.ndimage import zoom
15
+ from packaging.version import Version
16
+
17
+ keras = keras_import()
18
+ Input, Conv2D, MaxPooling2D = keras_import('layers', 'Input', 'Conv2D', 'MaxPooling2D')
19
+ Model = keras_import('models', 'Model')
20
+
21
+ from .base import StarDistBase, StarDistDataBase, _tf_version_at_least
22
+ from ..sample_patches import sample_patches
23
+ from ..utils import edt_prob, _normalize_grid, mask_to_categorical
24
+ from ..geometry import star_dist, dist_to_coord, polygons_to_label
25
+ from ..nms import non_maximum_suppression, non_maximum_suppression_sparse
26
+
27
+ _gen_rtype = list if IS_TF_1 else tuple
28
+
29
+ class StarDistData2D(StarDistDataBase):
30
+
31
+ def __init__(self, X, Y, batch_size, n_rays, length,
32
+ n_classes=None, classes=None,
33
+ patch_size=(256,256), b=32, grid=(1,1), shape_completion=False, augmenter=None, foreground_prob=0, **kwargs):
34
+
35
+ super().__init__(X=X, Y=Y, n_rays=n_rays, grid=grid,
36
+ n_classes=n_classes, classes=classes,
37
+ batch_size=batch_size, patch_size=patch_size, length=length,
38
+ augmenter=augmenter, foreground_prob=foreground_prob, **kwargs)
39
+
40
+ self.shape_completion = bool(shape_completion)
41
+ if self.shape_completion and b > 0:
42
+ if not all(b % g == 0 for g in self.grid):
43
+ raise ValueError(f"'shape_completion' requires that crop size {b} ('train_completion_crop' in config) is evenly divisible by all grid values {self.grid}")
44
+ self.b = slice(b,-b),slice(b,-b)
45
+ else:
46
+ self.b = slice(None),slice(None)
47
+
48
+ self.sd_mode = 'opencl' if self.use_gpu else 'cpp'
49
+
50
+
51
+ def __getitem__(self, i):
52
+ idx = self.batch(i)
53
+ arrays = [sample_patches((self.Y[k],) + self.channels_as_tuple(self.X[k]),
54
+ patch_size=self.patch_size, n_samples=1,
55
+ valid_inds=self.get_valid_inds(k)) for k in idx]
56
+
57
+ if self.n_channel is None:
58
+ X, Y = list(zip(*[(x[0][self.b],y[0]) for y,x in arrays]))
59
+ else:
60
+ X, Y = list(zip(*[(np.stack([_x[0] for _x in x],axis=-1)[self.b], y[0]) for y,*x in arrays]))
61
+
62
+ X, Y = tuple(zip(*tuple(self.augmenter(_x, _y) for _x, _y in zip(X,Y))))
63
+
64
+ mask_neg_labels = tuple(y[self.b][self.ss_grid[1:3]] < 0 for y in Y)
65
+ has_neg_labels = any(m.any() for m in mask_neg_labels)
66
+ if has_neg_labels:
67
+ mask_neg_labels = np.stack(mask_neg_labels)
68
+ # set negative label pixels to 0 (background)
69
+ Y = tuple(np.maximum(y, 0) for y in Y)
70
+
71
+ prob = np.stack([edt_prob(lbl[self.b][self.ss_grid[1:3]]) for lbl in Y])
72
+ # prob = np.stack([edt_prob(lbl[self.b]) for lbl in Y])
73
+ # prob = prob[self.ss_grid]
74
+
75
+ if self.shape_completion:
76
+ Y_cleared = [clear_border(lbl) for lbl in Y]
77
+ _dist = np.stack([star_dist(lbl,self.n_rays,mode=self.sd_mode)[self.b+(slice(None),)] for lbl in Y_cleared])
78
+ dist = _dist[self.ss_grid]
79
+ dist_mask = np.stack([edt_prob(lbl[self.b][self.ss_grid[1:3]]) for lbl in Y_cleared])
80
+ else:
81
+ # directly subsample with grid
82
+ dist = np.stack([star_dist(lbl,self.n_rays,mode=self.sd_mode, grid=self.grid) for lbl in Y])
83
+ dist_mask = prob
84
+
85
+ X = np.stack(X)
86
+ if X.ndim == 3: # input image has no channel axis
87
+ X = np.expand_dims(X,-1)
88
+ prob = np.expand_dims(prob,-1)
89
+ dist_mask = np.expand_dims(dist_mask,-1)
90
+
91
+ # subsample wth given grid
92
+ # dist_mask = dist_mask[self.ss_grid]
93
+ # prob = prob[self.ss_grid]
94
+
95
+ # append dist_mask to dist as additional channel
96
+ # dist_and_mask = np.concatenate([dist,dist_mask],axis=-1)
97
+ # faster than concatenate
98
+ dist_and_mask = np.empty(dist.shape[:-1]+(self.n_rays+1,), np.float32)
99
+ dist_and_mask[...,:-1] = dist
100
+ dist_and_mask[...,-1:] = dist_mask
101
+
102
+ if has_neg_labels:
103
+ prob[mask_neg_labels] = -1 # set to -1 to disable loss
104
+
105
+ # note: must return tuples in keras 3 (cf. https://stackoverflow.com/a/78158487)
106
+ if self.n_classes is None:
107
+ return _gen_rtype((X,)), _gen_rtype((prob,dist_and_mask))
108
+ else:
109
+ prob_class = np.stack(tuple((mask_to_categorical(y[self.b], self.n_classes, self.classes[k]) for y,k in zip(Y, idx))))
110
+
111
+ # TODO: investigate downsampling via simple indexing vs. using 'zoom'
112
+ # prob_class = prob_class[self.ss_grid]
113
+ # 'zoom' might lead to better registered maps (especially if upscaled later)
114
+ prob_class = zoom(prob_class, (1,)+tuple(1/g for g in self.grid)+(1,), order=0)
115
+
116
+ if has_neg_labels:
117
+ prob_class[mask_neg_labels] = -1 # set to -1 to disable loss
118
+
119
+ return _gen_rtype((X,)), _gen_rtype((prob,dist_and_mask, prob_class))
120
+
121
+
122
+
123
+ class Config2D(BaseConfig):
124
+ """Configuration for a :class:`StarDist2D` model.
125
+
126
+ Parameters
127
+ ----------
128
+ axes : str or None
129
+ Axes of the input images.
130
+ n_rays : int
131
+ Number of radial directions for the star-convex polygon.
132
+ Recommended to use a power of 2 (default: 32).
133
+ n_channel_in : int
134
+ Number of channels of given input image (default: 1).
135
+ grid : (int,int)
136
+ Subsampling factors (must be powers of 2) for each of the axes.
137
+ Model will predict on a subsampled grid for increased efficiency and larger field of view.
138
+ n_classes : None or int
139
+ Number of object classes to use for multi-class prediction (use None to disable)
140
+ backbone : str
141
+ Name of the neural network architecture to be used as backbone.
142
+ kwargs : dict
143
+ Overwrite (or add) configuration attributes (see below).
144
+
145
+
146
+ Attributes
147
+ ----------
148
+ unet_n_depth : int
149
+ Number of U-Net resolution levels (down/up-sampling layers).
150
+ unet_kernel_size : (int,int)
151
+ Convolution kernel size for all (U-Net) convolution layers.
152
+ unet_n_filter_base : int
153
+ Number of convolution kernels (feature channels) for first U-Net layer.
154
+ Doubled after each down-sampling layer.
155
+ unet_pool : (int,int)
156
+ Maxpooling size for all (U-Net) convolution layers.
157
+ net_conv_after_unet : int
158
+ Number of filters of the extra convolution layer after U-Net (0 to disable).
159
+ unet_* : *
160
+ Additional parameters for U-net backbone.
161
+ train_shape_completion : bool
162
+ Train model to predict complete shapes for partially visible objects at image boundary.
163
+ train_completion_crop : int
164
+ If 'train_shape_completion' is set to True, specify number of pixels to crop at boundary of training patches.
165
+ Should be chosen based on (largest) object sizes.
166
+ train_patch_size : (int,int)
167
+ Size of patches to be cropped from provided training images.
168
+ train_background_reg : float
169
+ Regularizer to encourage distance predictions on background regions to be 0.
170
+ train_foreground_only : float
171
+ Fraction (0..1) of patches that will only be sampled from regions that contain foreground pixels.
172
+ train_sample_cache : bool
173
+ Activate caching of valid patch regions for all training images (disable to save memory for large datasets)
174
+ train_dist_loss : str
175
+ Training loss for star-convex polygon distances ('mse' or 'mae').
176
+ train_loss_weights : tuple of float
177
+ Weights for losses relating to (probability, distance)
178
+ train_epochs : int
179
+ Number of training epochs.
180
+ train_steps_per_epoch : int
181
+ Number of parameter update steps per epoch.
182
+ train_learning_rate : float
183
+ Learning rate for training.
184
+ train_batch_size : int
185
+ Batch size for training.
186
+ train_n_val_patches : int
187
+ Number of patches to be extracted from validation images (``None`` = one patch per image).
188
+ train_tensorboard : bool
189
+ Enable TensorBoard for monitoring training progress.
190
+ train_reduce_lr : dict
191
+ Parameter :class:`dict` of ReduceLROnPlateau_ callback; set to ``None`` to disable.
192
+ use_gpu : bool
193
+ Indicate that the data generator should use OpenCL to do computations on the GPU.
194
+
195
+ .. _ReduceLROnPlateau: https://keras.io/api/callbacks/reduce_lr_on_plateau/
196
+ """
197
+
198
+ def __init__(self, axes='YX', n_rays=32, n_channel_in=1, grid=(1,1), n_classes=None, backbone='unet', **kwargs):
199
+ """See class docstring."""
200
+
201
+ super().__init__(axes=axes, n_channel_in=n_channel_in, n_channel_out=1+n_rays)
202
+
203
+ # directly set by parameters
204
+ self.n_rays = int(n_rays)
205
+ self.grid = _normalize_grid(grid,2)
206
+ self.backbone = str(backbone).lower()
207
+ self.n_classes = None if n_classes is None else int(n_classes)
208
+
209
+ # default config (can be overwritten by kwargs below)
210
+ if self.backbone == 'unet':
211
+ self.unet_n_depth = 3
212
+ self.unet_kernel_size = 3,3
213
+ self.unet_n_filter_base = 32
214
+ self.unet_n_conv_per_depth = 2
215
+ self.unet_pool = 2,2
216
+ self.unet_activation = 'relu'
217
+ self.unet_last_activation = 'relu'
218
+ self.unet_batch_norm = False
219
+ self.unet_dropout = 0.0
220
+ self.unet_expansion = 2
221
+ self.unet_prefix = ''
222
+ self.net_conv_after_unet = 128
223
+ else:
224
+ # TODO: resnet backbone for 2D model?
225
+ raise ValueError("backbone '%s' not supported." % self.backbone)
226
+
227
+ # net_mask_shape not needed but kept for legacy reasons
228
+ if backend_channels_last():
229
+ self.net_input_shape = None,None,self.n_channel_in
230
+ self.net_mask_shape = None,None,1
231
+ else:
232
+ self.net_input_shape = self.n_channel_in,None,None
233
+ self.net_mask_shape = 1,None,None
234
+
235
+ self.train_shape_completion = False
236
+ self.train_completion_crop = 32
237
+ self.train_patch_size = 256,256
238
+ self.train_background_reg = 1e-4
239
+ self.train_foreground_only = 0.9
240
+ self.train_sample_cache = True
241
+
242
+ self.train_dist_loss = 'mae'
243
+ self.train_loss_weights = (1,0.2) if self.n_classes is None else (1,0.2,1)
244
+ self.train_class_weights = (1,1) if self.n_classes is None else (1,)*(self.n_classes+1)
245
+ self.train_epochs = 400
246
+ self.train_steps_per_epoch = 100
247
+ self.train_learning_rate = 0.0003
248
+ self.train_batch_size = 4
249
+ self.train_n_val_patches = None
250
+ self.train_tensorboard = True
251
+ # the parameter 'min_delta' was called 'epsilon' for keras<=2.1.5
252
+ # keras.__version__ was removed in tensorflow 2.13.0
253
+ min_delta_key = 'epsilon' if Version(getattr(keras, '__version__', '9.9.9'))<=Version('2.1.5') else 'min_delta'
254
+ self.train_reduce_lr = {'factor': 0.5, 'patience': 40, min_delta_key: 0}
255
+
256
+ self.use_gpu = False
257
+
258
+ # remove derived attributes that shouldn't be overwritten
259
+ for k in ('n_dim', 'n_channel_out'):
260
+ try: del kwargs[k]
261
+ except KeyError: pass
262
+
263
+ self.update_parameters(False, **kwargs)
264
+
265
+ # FIXME: put into is_valid()
266
+ if not len(self.train_loss_weights) == (2 if self.n_classes is None else 3):
267
+ raise ValueError(f"train_loss_weights {self.train_loss_weights} not compatible with n_classes ({self.n_classes}): must be 3 weights if n_classes is not None, otherwise 2")
268
+
269
+ if not len(self.train_class_weights) == (2 if self.n_classes is None else self.n_classes+1):
270
+ raise ValueError(f"train_class_weights {self.train_class_weights} not compatible with n_classes ({self.n_classes}): must be 'n_classes + 1' weights if n_classes is not None, otherwise 2")
271
+
272
+
273
+
274
+ class StarDist2D(StarDistBase):
275
+ """StarDist2D model.
276
+
277
+ Parameters
278
+ ----------
279
+ config : :class:`Config` or None
280
+ Will be saved to disk as JSON (``config.json``).
281
+ If set to ``None``, will be loaded from disk (must exist).
282
+ name : str or None
283
+ Model name. Uses a timestamp if set to ``None`` (default).
284
+ basedir : str
285
+ Directory that contains (or will contain) a folder with the given model name.
286
+
287
+ Raises
288
+ ------
289
+ FileNotFoundError
290
+ If ``config=None`` and config cannot be loaded from disk.
291
+ ValueError
292
+ Illegal arguments, including invalid configuration.
293
+
294
+ Attributes
295
+ ----------
296
+ config : :class:`Config`
297
+ Configuration, as provided during instantiation.
298
+ keras_model : `Keras model <https://keras.io/getting-started/functional-api-guide/>`_
299
+ Keras neural network model.
300
+ name : str
301
+ Model name.
302
+ logdir : :class:`pathlib.Path`
303
+ Path to model folder (which stores configuration, weights, etc.)
304
+ """
305
+
306
+ def __init__(self, config=Config2D(), name=None, basedir='.'):
307
+ """See class docstring."""
308
+ super().__init__(config, name=name, basedir=basedir)
309
+
310
+
311
+ def _build(self):
312
+ self.config.backbone == 'unet' or _raise(NotImplementedError())
313
+ unet_kwargs = {k[len('unet_'):]:v for (k,v) in vars(self.config).items() if k.startswith('unet_')}
314
+
315
+ input_img = Input(self.config.net_input_shape, name='input')
316
+
317
+ # maxpool input image to grid size
318
+ pooled = np.array([1,1])
319
+ pooled_img = input_img
320
+ while tuple(pooled) != tuple(self.config.grid):
321
+ pool = 1 + (np.asarray(self.config.grid) > pooled)
322
+ pooled *= pool
323
+ for _ in range(self.config.unet_n_conv_per_depth):
324
+ pooled_img = Conv2D(self.config.unet_n_filter_base, self.config.unet_kernel_size,
325
+ padding='same', activation=self.config.unet_activation)(pooled_img)
326
+ pooled_img = MaxPooling2D(pool)(pooled_img)
327
+
328
+ unet_base = unet_block(**unet_kwargs)(pooled_img)
329
+
330
+ if self.config.net_conv_after_unet > 0:
331
+ unet = Conv2D(self.config.net_conv_after_unet, self.config.unet_kernel_size,
332
+ name='features', padding='same', activation=self.config.unet_activation)(unet_base)
333
+ else:
334
+ unet = unet_base
335
+
336
+ output_prob = Conv2D( 1, (1,1), name='prob', padding='same', activation='sigmoid')(unet)
337
+ output_dist = Conv2D(self.config.n_rays, (1,1), name='dist', padding='same', activation='linear')(unet)
338
+
339
+ # attach extra classification head when self.n_classes is given
340
+ if self._is_multiclass():
341
+ if self.config.net_conv_after_unet > 0:
342
+ unet_class = Conv2D(self.config.net_conv_after_unet, self.config.unet_kernel_size,
343
+ name='features_class', padding='same', activation=self.config.unet_activation)(unet_base)
344
+ else:
345
+ unet_class = unet_base
346
+
347
+ output_prob_class = Conv2D(self.config.n_classes+1, (1,1), name='prob_class', padding='same', activation='softmax')(unet_class)
348
+ return Model([input_img], [output_prob,output_dist,output_prob_class])
349
+ else:
350
+ return Model([input_img], [output_prob,output_dist])
351
+
352
+
353
+ def train(self, X, Y, validation_data, classes='auto', augmenter=None, seed=None, epochs=None, steps_per_epoch=None, workers=1):
354
+ """Train the neural network with the given data.
355
+
356
+ Parameters
357
+ ----------
358
+ X : tuple, list, `numpy.ndarray`, `keras.utils.Sequence`
359
+ Input images
360
+ Y : tuple, list, `numpy.ndarray`, `keras.utils.Sequence`
361
+ Label masks
362
+ Positive pixel values denote object instance ids (0 for background).
363
+ Negative values can be used to turn off all losses for the corresponding pixels (e.g. for regions that haven't been labeled).
364
+ classes (optional): 'auto' or iterable of same length as X
365
+ label id -> class id mapping for each label mask of Y if multiclass prediction is activated (n_classes > 0)
366
+ list of dicts with label id -> class id (1,...,n_classes)
367
+ 'auto' -> all objects will be assigned to the first non-background class,
368
+ or will be ignored if config.n_classes is None
369
+ validation_data : tuple(:class:`numpy.ndarray`, :class:`numpy.ndarray`) or triple (if multiclass)
370
+ Tuple (triple if multiclass) of X,Y,[classes] validation data.
371
+ augmenter : None or callable
372
+ Function with expected signature ``xt, yt = augmenter(x, y)``
373
+ that takes in a single pair of input/label image (x,y) and returns
374
+ the transformed images (xt, yt) for the purpose of data augmentation
375
+ during training. Not applied to validation images.
376
+ Example:
377
+ def simple_augmenter(x,y):
378
+ x = x + 0.05*np.random.normal(0,1,x.shape)
379
+ return x,y
380
+ seed : int
381
+ Convenience to set ``np.random.seed(seed)``. (To obtain reproducible validation patches, etc.)
382
+ epochs : int
383
+ Optional argument to use instead of the value from ``config``.
384
+ steps_per_epoch : int
385
+ Optional argument to use instead of the value from ``config``.
386
+
387
+ Returns
388
+ -------
389
+ ``History`` object
390
+ See `Keras training history <https://keras.io/models/model/#fit>`_.
391
+
392
+ """
393
+ if seed is not None:
394
+ # https://keras.io/getting-started/faq/#how-can-i-obtain-reproducible-results-using-keras-during-development
395
+ np.random.seed(seed)
396
+ if epochs is None:
397
+ epochs = self.config.train_epochs
398
+ if steps_per_epoch is None:
399
+ steps_per_epoch = self.config.train_steps_per_epoch
400
+
401
+ classes = self._parse_classes_arg(classes, len(X))
402
+
403
+ if not self._is_multiclass() and classes is not None:
404
+ warnings.warn("Ignoring given classes as n_classes is set to None")
405
+
406
+ isinstance(validation_data,(list,tuple)) or _raise(ValueError())
407
+ if self._is_multiclass() and len(validation_data) == 2:
408
+ validation_data = tuple(validation_data) + ('auto',)
409
+ ((len(validation_data) == (3 if self._is_multiclass() else 2))
410
+ or _raise(ValueError(f'len(validation_data) = {len(validation_data)}, but should be {3 if self._is_multiclass() else 2}')))
411
+
412
+ patch_size = self.config.train_patch_size
413
+ axes = self.config.axes.replace('C','')
414
+ b = self.config.train_completion_crop if self.config.train_shape_completion else 0
415
+ div_by = self._axes_div_by(axes)
416
+ [(p-2*b) % d == 0 or _raise(ValueError(
417
+ "'train_patch_size' - 2*'train_completion_crop' must be divisible by {d} along axis '{a}'".format(a=a,d=d) if self.config.train_shape_completion else
418
+ "'train_patch_size' must be divisible by {d} along axis '{a}'".format(a=a,d=d)
419
+ )) for p,d,a in zip(patch_size,div_by,axes)]
420
+
421
+ if not self._model_prepared:
422
+ self.prepare_for_training()
423
+
424
+ data_kwargs = dict (
425
+ n_rays = self.config.n_rays,
426
+ patch_size = self.config.train_patch_size,
427
+ grid = self.config.grid,
428
+ shape_completion = self.config.train_shape_completion,
429
+ b = self.config.train_completion_crop,
430
+ use_gpu = self.config.use_gpu,
431
+ foreground_prob = self.config.train_foreground_only,
432
+ n_classes = self.config.n_classes,
433
+ sample_ind_cache = self.config.train_sample_cache,
434
+ )
435
+ worker_kwargs = dict(workers=workers, use_multiprocessing=workers>1)
436
+ if IS_KERAS_3_PLUS:
437
+ data_kwargs['keras_kwargs'] = worker_kwargs
438
+ fit_kwargs = {}
439
+ else:
440
+ fit_kwargs = worker_kwargs
441
+
442
+ # generate validation data and store in numpy arrays
443
+ n_data_val = len(validation_data[0])
444
+ classes_val = self._parse_classes_arg(validation_data[2], n_data_val) if self._is_multiclass() else None
445
+ n_take = self.config.train_n_val_patches if self.config.train_n_val_patches is not None else n_data_val
446
+ _data_val = StarDistData2D(validation_data[0],validation_data[1], classes=classes_val, batch_size=n_take, length=1, **data_kwargs)
447
+ data_val = _data_val[0]
448
+
449
+ # expose data generator as member for general diagnostics
450
+ self.data_train = StarDistData2D(X, Y, classes=classes, batch_size=self.config.train_batch_size,
451
+ augmenter=augmenter, length=epochs*steps_per_epoch, **data_kwargs)
452
+
453
+ if self.config.train_tensorboard:
454
+ # show dist for three rays
455
+ _n = min(3, self.config.n_rays)
456
+ channel = axes_dict(self.config.axes)['C']
457
+ output_slices = [[slice(None)]*4,[slice(None)]*4]
458
+ output_slices[1][1+channel] = slice(0,(self.config.n_rays//_n)*_n, self.config.n_rays//_n)
459
+ if self._is_multiclass():
460
+ _n = min(3, self.config.n_classes)
461
+ output_slices += [[slice(None)]*4]
462
+ output_slices[2][1+channel] = slice(1,1+(self.config.n_classes//_n)*_n, self.config.n_classes//_n)
463
+
464
+ if IS_TF_1:
465
+ for cb in self.callbacks:
466
+ if isinstance(cb,CARETensorBoard):
467
+ cb.output_slices = output_slices
468
+ # target image for dist includes dist_mask and thus has more channels than dist output
469
+ cb.output_target_shapes = [None,[None]*4,None]
470
+ cb.output_target_shapes[1][1+channel] = data_val[1][1].shape[1+channel]
471
+ elif self.basedir is not None and not any(isinstance(cb,CARETensorBoardImage) for cb in self.callbacks):
472
+ self.callbacks.append(CARETensorBoardImage(model=self.keras_model, data=data_val, log_dir=str(self.logdir/'logs'/'images'),
473
+ n_images=3, prob_out=False, output_slices=output_slices))
474
+
475
+ fit = self.keras_model.fit_generator if (IS_TF_1 and not IS_KERAS_3_PLUS) else self.keras_model.fit
476
+ history = fit(iter(self.data_train), validation_data=data_val,
477
+ epochs=epochs, steps_per_epoch=steps_per_epoch,
478
+ **fit_kwargs,
479
+ callbacks=self.callbacks, verbose=1,
480
+ # set validation batchsize to training batchsize (only works for tf >= 2.2)
481
+ **(dict(validation_batch_size = self.config.train_batch_size) if _tf_version_at_least("2.2.0") else {}))
482
+ self._training_finished()
483
+
484
+ return history
485
+
486
+
487
+ # def _instances_from_prediction_old(self, img_shape, prob, dist,points = None, prob_class = None, prob_thresh=None, nms_thresh=None, overlap_label = None, **nms_kwargs):
488
+ # from stardist.geometry.geom2d import _polygons_to_label_old, _dist_to_coord_old
489
+ # from stardist.nms import _non_maximum_suppression_old
490
+
491
+ # if prob_thresh is None: prob_thresh = self.thresholds.prob
492
+ # if nms_thresh is None: nms_thresh = self.thresholds.nms
493
+ # if overlap_label is not None: raise NotImplementedError("overlap_label not supported for 2D yet!")
494
+
495
+ # coord = _dist_to_coord_old(dist, grid=self.config.grid)
496
+ # inds = _non_maximum_suppression_old(coord, prob, grid=self.config.grid,
497
+ # prob_thresh=prob_thresh, nms_thresh=nms_thresh, **nms_kwargs)
498
+ # labels = _polygons_to_label_old(coord, prob, inds, shape=img_shape)
499
+ # # sort 'inds' such that ids in 'labels' map to entries in polygon dictionary entries
500
+ # inds = inds[np.argsort(prob[inds[:,0],inds[:,1]])]
501
+ # # adjust for grid
502
+ # points = inds*np.array(self.config.grid)
503
+
504
+ # res_dict = dict(coord=coord[inds[:,0],inds[:,1]], points=points, prob=prob[inds[:,0],inds[:,1]])
505
+
506
+ # if prob_class is not None:
507
+ # prob_class = np.asarray(prob_class)
508
+ # res_dict.update(dict(class_prob = prob_class))
509
+
510
+ # return labels, res_dict
511
+
512
+
513
+ def _instances_from_prediction(self, img_shape, prob, dist, points=None, prob_class=None, prob_thresh=None, nms_thresh=None, overlap_label=None, return_labels=True, scale=None, **nms_kwargs):
514
+ """
515
+ if points is None -> dense prediction
516
+ if points is not None -> sparse prediction
517
+
518
+ if prob_class is None -> single class prediction
519
+ if prob_class is not None -> multi class prediction
520
+ """
521
+ if prob_thresh is None: prob_thresh = self.thresholds.prob
522
+ if nms_thresh is None: nms_thresh = self.thresholds.nms
523
+ if overlap_label is not None: raise NotImplementedError("overlap_label not supported for 2D yet!")
524
+
525
+ # sparse prediction
526
+ if points is not None:
527
+ points, probi, disti, indsi = non_maximum_suppression_sparse(dist, prob, points, nms_thresh=nms_thresh, **nms_kwargs)
528
+ if prob_class is not None:
529
+ prob_class = prob_class[indsi]
530
+
531
+ # dense prediction
532
+ else:
533
+ points, probi, disti = non_maximum_suppression(dist, prob, grid=self.config.grid,
534
+ prob_thresh=prob_thresh, nms_thresh=nms_thresh, **nms_kwargs)
535
+ if prob_class is not None:
536
+ inds = tuple(p//g for p,g in zip(points.T, self.config.grid))
537
+ prob_class = prob_class[inds]
538
+
539
+ if scale is not None:
540
+ # need to undo the scaling given by the scale dict, e.g. scale = dict(X=0.5,Y=0.5):
541
+ # 1. re-scale points (origins of polygons)
542
+ # 2. re-scale coordinates (computed from distances) of (zero-origin) polygons
543
+ if not (isinstance(scale,dict) and 'X' in scale and 'Y' in scale):
544
+ raise ValueError("scale must be a dictionary with entries for 'X' and 'Y'")
545
+ rescale = (1/scale['Y'],1/scale['X'])
546
+ points = points * np.array(rescale).reshape(1,2)
547
+ else:
548
+ rescale = (1,1)
549
+
550
+ if return_labels:
551
+ labels = polygons_to_label(disti, points, prob=probi, shape=img_shape, scale_dist=rescale)
552
+ else:
553
+ labels = None
554
+
555
+ coord = dist_to_coord(disti, points, scale_dist=rescale)
556
+ res_dict = dict(coord=coord, points=points, prob=probi)
557
+
558
+ # multi class prediction
559
+ if prob_class is not None:
560
+ prob_class = np.asarray(prob_class)
561
+ class_id = np.argmax(prob_class, axis=-1)
562
+ res_dict.update(dict(class_prob=prob_class, class_id=class_id))
563
+
564
+ return labels, res_dict
565
+
566
+
567
+ def _axes_div_by(self, query_axes):
568
+ self.config.backbone == 'unet' or _raise(NotImplementedError())
569
+ query_axes = axes_check_and_normalize(query_axes)
570
+ assert len(self.config.unet_pool) == len(self.config.grid)
571
+ div_by = dict(zip(
572
+ self.config.axes.replace('C',''),
573
+ tuple(p**self.config.unet_n_depth * g for p,g in zip(self.config.unet_pool,self.config.grid))
574
+ ))
575
+ return tuple(div_by.get(a,1) for a in query_axes)
576
+
577
+
578
+ # def _axes_tile_overlap(self, query_axes):
579
+ # self.config.backbone == 'unet' or _raise(NotImplementedError())
580
+ # query_axes = axes_check_and_normalize(query_axes)
581
+ # assert len(self.config.unet_pool) == len(self.config.grid) == len(self.config.unet_kernel_size)
582
+ # # TODO: compute this properly when any value of grid > 1
583
+ # # all(g==1 for g in self.config.grid) or warnings.warn('FIXME')
584
+ # overlap = dict(zip(
585
+ # self.config.axes.replace('C',''),
586
+ # tuple(tile_overlap(self.config.unet_n_depth + int(np.log2(g)), k, p)
587
+ # for p,k,g in zip(self.config.unet_pool,self.config.unet_kernel_size,self.config.grid))
588
+ # ))
589
+ # return tuple(overlap.get(a,0) for a in query_axes)
590
+
591
+
592
+ @property
593
+ def _config_class(self):
594
+ return Config2D