stainnormprogram 1.0.0__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.
- stainnormprogram/__about__.py +1 -0
- stainnormprogram/__init__.py +2 -0
- stainnormprogram/assessment/__init__.py +1 -0
- stainnormprogram/assessment/assessment.py +1186 -0
- stainnormprogram/assessment/background.py +211 -0
- stainnormprogram/assessment/color.py +770 -0
- stainnormprogram/assessment/contrast.py +252 -0
- stainnormprogram/assessment/gamut.py +407 -0
- stainnormprogram/assessment/palette.py +648 -0
- stainnormprogram/assessment/plot.py +759 -0
- stainnormprogram/assessment/structure.py +158 -0
- stainnormprogram/correction/__init__.py +1 -0
- stainnormprogram/correction/macenko.py +469 -0
- stainnormprogram/io/__init__.py +0 -0
- stainnormprogram/io/write_slide.py +119 -0
- stainnormprogram/library/TCGA-Manifest.txt +31 -0
- stainnormprogram/library/TCIA-Instructions.md +15 -0
- stainnormprogram/library/library.md +14 -0
- stainnormprogram/norm/__init__.py +1 -0
- stainnormprogram/norm/adjustments.py +88 -0
- stainnormprogram/norm/background.py +273 -0
- stainnormprogram/norm/normalization.py +126 -0
- stainnormprogram/norm/pipeline/__init__.py +0 -0
- stainnormprogram/norm/pipeline/macenko.py +302 -0
- stainnormprogram/norm/pipeline/pipeline.py +61 -0
- stainnormprogram/norm/style_estimation/__init__.py +0 -0
- stainnormprogram/norm/style_estimation/macenko.py +649 -0
- stainnormprogram/norm/subset.py +127 -0
- stainnormprogram/norm/translation/__init__.py +0 -0
- stainnormprogram/norm/translation/macenko.py +92 -0
- stainnormprogram/norm/utils.py +96 -0
- stainnormprogram/slide.py +1085 -0
- stainnormprogram-1.0.0.dist-info/METADATA +75 -0
- stainnormprogram-1.0.0.dist-info/RECORD +36 -0
- stainnormprogram-1.0.0.dist-info/WHEEL +4 -0
- stainnormprogram-1.0.0.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1,649 @@
|
|
|
1
|
+
from stainnormprogram.slide import Tile
|
|
2
|
+
from stainnormprogram.norm.utils import nnls
|
|
3
|
+
from stainnormprogram.norm.background import hsv_threshold_foreground
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
import time
|
|
7
|
+
import multiprocessing as mp
|
|
8
|
+
import queue
|
|
9
|
+
import os
|
|
10
|
+
import random
|
|
11
|
+
|
|
12
|
+
import pyvips
|
|
13
|
+
import numpy as np
|
|
14
|
+
from sklearn.linear_model import LinearRegression
|
|
15
|
+
import colour
|
|
16
|
+
from skimage.color import rgb2hsv
|
|
17
|
+
|
|
18
|
+
DAB_HUE = 30.0 / 360.0 # orange
|
|
19
|
+
HTX_HUE = 240.0 / 360.0 # blue
|
|
20
|
+
|
|
21
|
+
class MacenkoStyleEstimation:
|
|
22
|
+
|
|
23
|
+
def __init__(self,
|
|
24
|
+
slide: SlideImage,
|
|
25
|
+
I0: np.ndarray,
|
|
26
|
+
stain_balancing: bool = False,
|
|
27
|
+
mode: str = "tiled_parallel",
|
|
28
|
+
alpha: float = 1.0,
|
|
29
|
+
beta: float = 0.15,
|
|
30
|
+
use_nnls: bool = True,
|
|
31
|
+
maxworkers: int | None = None,
|
|
32
|
+
options: dict[str, Any] = {}
|
|
33
|
+
):
|
|
34
|
+
"""Estimate the stain style using Macenko's method.
|
|
35
|
+
|
|
36
|
+
Args:
|
|
37
|
+
slide: Slide to perform estimation on.
|
|
38
|
+
I0: Background intensity.
|
|
39
|
+
stain_balancing: Whether to perform stain balancing (True is recommended for DAB).
|
|
40
|
+
mode: Estimation mode ("tiled", "tiled_parallel", or "thumbnail").
|
|
41
|
+
alpha: Macenko's alpha.
|
|
42
|
+
beta: Macenko's beta.
|
|
43
|
+
use_nnls: Use non-negative least squares when calculating concentrations.
|
|
44
|
+
maxworkers: Max workers for style estimation (None calculates this for you).
|
|
45
|
+
options: Additional options to pass to the estimation methods.
|
|
46
|
+
"""
|
|
47
|
+
self.slide = slide
|
|
48
|
+
self.I0 = I0
|
|
49
|
+
self.stain_balancing = stain_balancing
|
|
50
|
+
self.mode = mode
|
|
51
|
+
self.alpha = alpha
|
|
52
|
+
self.beta = beta
|
|
53
|
+
self.use_nnls = use_nnls
|
|
54
|
+
self.maxworkers = maxworkers
|
|
55
|
+
self.options = options
|
|
56
|
+
|
|
57
|
+
if "tiled" in self.mode and "threshold" not in options:
|
|
58
|
+
if not stain_balancing:
|
|
59
|
+
self.options["threshold"] = 200_000
|
|
60
|
+
else:
|
|
61
|
+
self.options["threshold"] = (50_000, 50_000)
|
|
62
|
+
|
|
63
|
+
self.matrix_avg = None
|
|
64
|
+
self.maxC_avg = None
|
|
65
|
+
|
|
66
|
+
def compute_matrix(self):
|
|
67
|
+
"""Compute the stain matrix.
|
|
68
|
+
"""
|
|
69
|
+
if self.mode == "tiled_parallel":
|
|
70
|
+
self.compute_tiled_parallel(quantity="matrix", **self.options)
|
|
71
|
+
elif self.mode == "thumbnail":
|
|
72
|
+
self.compute_matrix_thumbnail(**self.options)
|
|
73
|
+
elif self.mode == "tiled":
|
|
74
|
+
self.compute_tiled(quantity="matrix", **self.options)
|
|
75
|
+
else:
|
|
76
|
+
raise Exception(f"{self.mode} is not a valid mode.")
|
|
77
|
+
|
|
78
|
+
def compute_maxC(self):
|
|
79
|
+
"""Compute maxC.
|
|
80
|
+
"""
|
|
81
|
+
if self.mode == "tiled_parallel":
|
|
82
|
+
self.compute_tiled_parallel(quantity="maxC", **self.options)
|
|
83
|
+
elif self.mode == "thumbnail":
|
|
84
|
+
self.compute_maxC_thumbnail(**self.options)
|
|
85
|
+
elif self.mode == "tiled":
|
|
86
|
+
self.compute_tiled(quantity="maxC", **self.options)
|
|
87
|
+
else:
|
|
88
|
+
raise Exception(f"{self.mode} is not a valid mode.")
|
|
89
|
+
|
|
90
|
+
def set_matrix_avg(self, matrix_avg: np.ndarray):
|
|
91
|
+
"""Set the average stain matrix (useful if you want to just calculate maxC).
|
|
92
|
+
"""
|
|
93
|
+
self.matrix_avg = matrix_avg
|
|
94
|
+
|
|
95
|
+
@staticmethod
|
|
96
|
+
def get_buffer_assignment(pixels: np.ndarray) -> np.ndarray:
|
|
97
|
+
"""Assign pixels to either the hematoxylin (False) or DAB (True) buffers.
|
|
98
|
+
|
|
99
|
+
Args:
|
|
100
|
+
pixels: (N,3) in HSV
|
|
101
|
+
|
|
102
|
+
Returns:
|
|
103
|
+
A np.ndarray (N,) where hematoyxlin pixels are False and DAB pixels are True.
|
|
104
|
+
"""
|
|
105
|
+
hues = pixels[:,0]
|
|
106
|
+
|
|
107
|
+
dab_abs_dists = np.abs(hues - DAB_HUE)
|
|
108
|
+
dab_dists = np.minimum(dab_abs_dists, 1.0 - dab_abs_dists)
|
|
109
|
+
|
|
110
|
+
htx_abs_dists = np.abs(hues - HTX_HUE)
|
|
111
|
+
htx_dists = np.minimum(htx_abs_dists, 1.0 - htx_abs_dists)
|
|
112
|
+
|
|
113
|
+
return dab_dists < htx_dists
|
|
114
|
+
|
|
115
|
+
@staticmethod
|
|
116
|
+
def convert_od_and_filter(tile: Tile, I0: np.ndarray, beta: float, return_mask: bool = False) -> np.ndarray | tuple[np.ndarray, np.ndarray]:
|
|
117
|
+
"""Convert RGB pixels into optical density (OD) pixels, then filter out pixels using the beta threshold.
|
|
118
|
+
|
|
119
|
+
Args:
|
|
120
|
+
tile: Tile image.
|
|
121
|
+
I0: Initial intensity.
|
|
122
|
+
beta: Macenko's beta.
|
|
123
|
+
return_mask: Return the filter mask. True pixels in the mask correspond to pixels that were accepted.
|
|
124
|
+
|
|
125
|
+
Returns:
|
|
126
|
+
A np.ndarray with accepted OD pixels, along with a np.ndarray bool mask if return_mask is True.
|
|
127
|
+
"""
|
|
128
|
+
|
|
129
|
+
tile_od = tile.od(I0).reshape(-1,3)
|
|
130
|
+
|
|
131
|
+
beta_mask = np.any(tile_od > beta, axis=1)
|
|
132
|
+
hsv_mask = hsv_threshold_foreground(tile, flatten=True)
|
|
133
|
+
mask = beta_mask & hsv_mask
|
|
134
|
+
|
|
135
|
+
filtered = tile_od[mask]
|
|
136
|
+
|
|
137
|
+
if return_mask:
|
|
138
|
+
return filtered, mask
|
|
139
|
+
|
|
140
|
+
return filtered
|
|
141
|
+
|
|
142
|
+
@staticmethod
|
|
143
|
+
def svd(ODhat: np.ndarray, alpha: float) -> np.ndarray:
|
|
144
|
+
"""Compute Macenko's singular value decomposition.
|
|
145
|
+
|
|
146
|
+
Code taken from https://github.com/slideflow/slideflow/blob/master/slideflow/norm/macenko.py.
|
|
147
|
+
|
|
148
|
+
Args:
|
|
149
|
+
ODhat: Filtered OD pixel values.
|
|
150
|
+
alpha: Macenko's alpha.
|
|
151
|
+
|
|
152
|
+
Returns:
|
|
153
|
+
A np.ndarray representing the stain matrix.
|
|
154
|
+
"""
|
|
155
|
+
|
|
156
|
+
eigvals, eigvecs = np.linalg.eigh(np.cov(ODhat.T))
|
|
157
|
+
|
|
158
|
+
That = ODhat.dot(eigvecs[:, 1:3])
|
|
159
|
+
|
|
160
|
+
phi = np.arctan2(That[:, 1], That[:, 0])
|
|
161
|
+
|
|
162
|
+
minPhi = np.percentile(phi, alpha)
|
|
163
|
+
maxPhi = np.percentile(phi, 100 - alpha)
|
|
164
|
+
|
|
165
|
+
vMin = eigvecs[:, 1:3].dot(np.array([(np.cos(minPhi), np.sin(minPhi))]).T)
|
|
166
|
+
vMax = eigvecs[:, 1:3].dot(np.array([(np.cos(maxPhi), np.sin(maxPhi))]).T)
|
|
167
|
+
|
|
168
|
+
if vMin[0] > vMax[0]:
|
|
169
|
+
matrix = np.array((vMin[:, 0], vMax[:, 0])).T
|
|
170
|
+
else:
|
|
171
|
+
matrix = np.array((vMax[:, 0], vMin[:, 0])).T
|
|
172
|
+
|
|
173
|
+
return matrix
|
|
174
|
+
|
|
175
|
+
def get_thumbnail_pixels(self, height: int = 4096, smooth: bool = True) -> np.ndarray:
|
|
176
|
+
"""Get filtered OD pixels from the thumbnail image.
|
|
177
|
+
|
|
178
|
+
Args:
|
|
179
|
+
height: Max height of the thumbnail.
|
|
180
|
+
smooth: Allow for interpolation that involves pixel smoothing.
|
|
181
|
+
|
|
182
|
+
Returns:
|
|
183
|
+
A np.ndarray with accepted OD pixels.
|
|
184
|
+
"""
|
|
185
|
+
image = self.slide.get_thumbnail(height=height, smooth=smooth)
|
|
186
|
+
tile = Tile(image)
|
|
187
|
+
filtered = self.convert_od_and_filter(tile, self.I0, self.beta)
|
|
188
|
+
|
|
189
|
+
if filtered.shape[0] == 0:
|
|
190
|
+
raise Exception("All pixels were filtered out during style estimation. Adjust your parameters or check this isn't a blank image.")
|
|
191
|
+
|
|
192
|
+
return filtered
|
|
193
|
+
|
|
194
|
+
def compute_matrix_thumbnail(self, height: int = 4096, smooth: bool = True, **kwargs):
|
|
195
|
+
"""Compute the stain matrix from a thumbnail of the whole slide image.
|
|
196
|
+
|
|
197
|
+
Args:
|
|
198
|
+
height: Max height of the thumbnail.
|
|
199
|
+
smooth: Allow for interpolation that involves pixel smoothing.
|
|
200
|
+
"""
|
|
201
|
+
filtered = self.get_thumbnail_pixels(height=height, smooth=smooth)
|
|
202
|
+
self.matrix_avg = self.svd(filtered, self.alpha)
|
|
203
|
+
|
|
204
|
+
def compute_maxC_thumbnail(self, height: int = 4096, smooth: bool = True, **kwargs):
|
|
205
|
+
"""Compute maxC from a thumbnail of the whole slide image.
|
|
206
|
+
|
|
207
|
+
Args:
|
|
208
|
+
height: Max height of the thumbnail.
|
|
209
|
+
smooth: Allow for interpolation that involves pixel smoothing.
|
|
210
|
+
"""
|
|
211
|
+
|
|
212
|
+
filtered = self.get_thumbnail_pixels(height=height, smooth=smooth)
|
|
213
|
+
|
|
214
|
+
vals = filtered.transpose() # (3,N)
|
|
215
|
+
if self.use_nnls:
|
|
216
|
+
C = nnls(self.matrix_avg, vals) # (2,N)
|
|
217
|
+
else:
|
|
218
|
+
C = np.linalg.lstsq(self.matrix_avg, vals, rcond=None)[0]
|
|
219
|
+
maxC = np.array([np.percentile(C[0, :], 100 - self.alpha), np.percentile(C[1, :], 100 - self.alpha)])
|
|
220
|
+
|
|
221
|
+
self.maxC_avg = maxC
|
|
222
|
+
|
|
223
|
+
@staticmethod
|
|
224
|
+
def compute_task(
|
|
225
|
+
quantity: str,
|
|
226
|
+
slide: SlideImage,
|
|
227
|
+
coord_queue: mp.Queue,
|
|
228
|
+
quantity_queue: mp.Queue,
|
|
229
|
+
I0: np.ndarray,
|
|
230
|
+
alpha: float,
|
|
231
|
+
beta: float,
|
|
232
|
+
threshold: int | tuple[int, int],
|
|
233
|
+
remainder_queue: mp.Queue,
|
|
234
|
+
stop_event: mp.Event,
|
|
235
|
+
use_nnls: bool = True,
|
|
236
|
+
matrix_avg: np.array | None = None,
|
|
237
|
+
):
|
|
238
|
+
"""Perform either stain matrix or maxC computation. This is a task function given to workers for parallel processing.
|
|
239
|
+
|
|
240
|
+
Args:
|
|
241
|
+
quantity: Either "matrix" or "maxC" depending on the quantity of interest to calculate.
|
|
242
|
+
slide: SlideImage to perform the computation on.
|
|
243
|
+
coord_queue: Queue containing tile coordinates (upper left corner) to process.
|
|
244
|
+
quantity_queue: Queue to put output computations into.
|
|
245
|
+
I0: Initial intensity.
|
|
246
|
+
alpha: Macenko's alpha.
|
|
247
|
+
beta: Macenko's beta.
|
|
248
|
+
threshold: Number of pixels to accumulate before executing the computation. Tuple of two ints (HTX, DAB) if stain balancing.
|
|
249
|
+
remainder_queue: Queue to put leftover pixels into if the worker is at the end of life and doesn't have enough pixels to do another computation.
|
|
250
|
+
stop_event: Stop event called when workers should stop.
|
|
251
|
+
use_nnls: Use non-negative least squares for calculating concentrations.
|
|
252
|
+
matrix_avg: Computed stain matrix (if maxC is being computed).
|
|
253
|
+
"""
|
|
254
|
+
|
|
255
|
+
stain_balancing = isinstance(threshold, tuple)
|
|
256
|
+
|
|
257
|
+
if stain_balancing:
|
|
258
|
+
pixels = [0, 0]
|
|
259
|
+
buffer = [[], []]
|
|
260
|
+
else:
|
|
261
|
+
pixels = 0
|
|
262
|
+
buffer = []
|
|
263
|
+
|
|
264
|
+
slide.load_slide()
|
|
265
|
+
|
|
266
|
+
while not stop_event.is_set():
|
|
267
|
+
try:
|
|
268
|
+
y, x, tile_h, tile_w = coord_queue.get_nowait()
|
|
269
|
+
except queue.Empty:
|
|
270
|
+
break
|
|
271
|
+
|
|
272
|
+
tile = slide.get_tile(y, x, tile_h, tile_w)
|
|
273
|
+
|
|
274
|
+
filtered, mask = MacenkoStyleEstimation.convert_od_and_filter(tile, I0, beta, return_mask=True)
|
|
275
|
+
|
|
276
|
+
if filtered.shape[0] > 0:
|
|
277
|
+
|
|
278
|
+
if stain_balancing:
|
|
279
|
+
tile_hsv = tile.hsv().reshape(-1,3)
|
|
280
|
+
filtered_hsv = tile_hsv[mask]
|
|
281
|
+
buffer_assignment = MacenkoStyleEstimation.get_buffer_assignment(filtered_hsv)
|
|
282
|
+
htx = filtered[~buffer_assignment]
|
|
283
|
+
dab = filtered[buffer_assignment]
|
|
284
|
+
if len(htx.shape) != 2:
|
|
285
|
+
htx = htx[np.newaxis, :]
|
|
286
|
+
if len(dab.shape) != 2:
|
|
287
|
+
dab = dab[np.newaxis, :]
|
|
288
|
+
if htx.shape[0] > 0 and pixels[0] <= threshold[0]:
|
|
289
|
+
buffer[0].append(htx)
|
|
290
|
+
pixels[0] += htx.shape[0]
|
|
291
|
+
if dab.shape[0] > 0 and pixels[1] <= threshold[1]:
|
|
292
|
+
buffer[1].append(dab)
|
|
293
|
+
pixels[1] += dab.shape[0]
|
|
294
|
+
else:
|
|
295
|
+
buffer.append(filtered)
|
|
296
|
+
pixels += filtered.shape[0]
|
|
297
|
+
|
|
298
|
+
if not stain_balancing and pixels > threshold:
|
|
299
|
+
|
|
300
|
+
vals = np.concatenate(buffer, axis=0)
|
|
301
|
+
buffer = []
|
|
302
|
+
pixels = 0
|
|
303
|
+
if quantity == "matrix":
|
|
304
|
+
matrix = MacenkoStyleEstimation.svd(vals, alpha)
|
|
305
|
+
quantity_queue.put(matrix)
|
|
306
|
+
else:
|
|
307
|
+
vals = vals.transpose()
|
|
308
|
+
if use_nnls:
|
|
309
|
+
C = nnls(matrix_avg, vals) # (2,N)
|
|
310
|
+
else:
|
|
311
|
+
C = np.linalg.lstsq(matrix_avg, vals, rcond=None)[0]
|
|
312
|
+
maxC = np.array([np.percentile(C[0, :], 100 - alpha), np.percentile(C[1, :], 100 - alpha)])
|
|
313
|
+
quantity_queue.put(maxC)
|
|
314
|
+
|
|
315
|
+
if stain_balancing and pixels[0] > threshold[0] and pixels[1] > threshold[1]:
|
|
316
|
+
|
|
317
|
+
htx_vals = np.concatenate(buffer[0], axis=0) # (N_htx,3)
|
|
318
|
+
dab_vals = np.concatenate(buffer[1], axis=0) # (N_dab,3)
|
|
319
|
+
vals = np.concatenate([htx_vals, dab_vals], axis=0) # (N,3)
|
|
320
|
+
pixels = [0, 0]
|
|
321
|
+
buffer = [[], []]
|
|
322
|
+
if quantity == "matrix":
|
|
323
|
+
matrix = MacenkoStyleEstimation.svd(vals, alpha)
|
|
324
|
+
quantity_queue.put(matrix)
|
|
325
|
+
else:
|
|
326
|
+
vals = vals.transpose()
|
|
327
|
+
if use_nnls:
|
|
328
|
+
C = nnls(matrix_avg, vals) # (2,N)
|
|
329
|
+
else:
|
|
330
|
+
C = np.linalg.lstsq(matrix_avg, vals, rcond=None)[0]
|
|
331
|
+
maxC = np.array([np.percentile(C[0, :], 100 - alpha), np.percentile(C[1, :], 100 - alpha)])
|
|
332
|
+
quantity_queue.put(maxC)
|
|
333
|
+
|
|
334
|
+
remainder_queue.put(buffer)
|
|
335
|
+
quantity_queue.put(None)
|
|
336
|
+
|
|
337
|
+
def compute_tiled_parallel(self, threshold: int | tuple[int, int], quantity: str, num_tiles: int = 500, tile_size: int = 512, detect_fg: bool = False, maxC_mode: str = "mean", **kwargs):
|
|
338
|
+
"""Compute stain matrix or maxC using tiles, parallelized.
|
|
339
|
+
|
|
340
|
+
Args:
|
|
341
|
+
threshold: Min number of pixels to accumulate before calculating the quantity. If int, there is one threshold. If tuple of two ints, the first is for hematoxylin and second for DAB.
|
|
342
|
+
quantity: Either "matrix" or "maxC" depending on the quantity of interest to calculate.
|
|
343
|
+
num_tiles: Max number of tiles to use for estimation.
|
|
344
|
+
tile_size: Tile size to use.
|
|
345
|
+
detect_fg: Detect where the tissue is using the thumbnail.
|
|
346
|
+
maxC_mode: Type of statistic to calculate over maxC values ("mean" or "percentile" for 100 - alpha percentile of maxC values).
|
|
347
|
+
"""
|
|
348
|
+
|
|
349
|
+
print(f"Computing stain {quantity}...")
|
|
350
|
+
print(f"Min pixels to accumulate before calculating = {threshold}")
|
|
351
|
+
print(f"Max tiles to use = {num_tiles}")
|
|
352
|
+
print(f"Tile size = {tile_size}")
|
|
353
|
+
print(f"Detect foreground from thumbnail first = {detect_fg}")
|
|
354
|
+
if quantity == "maxC":
|
|
355
|
+
print(f"maxC estimates are aggregated via = {maxC_mode}")
|
|
356
|
+
|
|
357
|
+
# Input checks
|
|
358
|
+
if not (isinstance(threshold, int) or (isinstance(threshold, tuple) and len(threshold) == 2)):
|
|
359
|
+
raise Exception("threshold needs to be an int or tuple of two ints")
|
|
360
|
+
if not (quantity == "matrix" or quantity == "maxC"):
|
|
361
|
+
raise Exception("quantity needs to be either matrix or maxC")
|
|
362
|
+
if quantity == "maxC" and self.matrix_avg is None:
|
|
363
|
+
raise Exception("Stain matrix needs to be computed before maxC")
|
|
364
|
+
|
|
365
|
+
# Set tile size
|
|
366
|
+
self.slide.set_tile_size(tile_size)
|
|
367
|
+
|
|
368
|
+
# Set number of workers based on CPU cores
|
|
369
|
+
num_workers = 1
|
|
370
|
+
if self.maxworkers is None:
|
|
371
|
+
num_workers = max(1, (os.process_cpu_count() or 1) - 1)
|
|
372
|
+
else:
|
|
373
|
+
num_workers = self.maxworkers
|
|
374
|
+
print(f"Using {num_workers} workers...")
|
|
375
|
+
|
|
376
|
+
# Get coordinates to visit
|
|
377
|
+
coords = self.slide.compute_random_sequence()
|
|
378
|
+
if detect_fg:
|
|
379
|
+
coords = self.slide.filter_coords_using_thumbnail(hsv_threshold_foreground, coords)
|
|
380
|
+
|
|
381
|
+
# Put coordinates into a queue
|
|
382
|
+
coord_queue = mp.Queue()
|
|
383
|
+
for c in coords:
|
|
384
|
+
coord_queue.put(c)
|
|
385
|
+
|
|
386
|
+
# Make slide pickleable
|
|
387
|
+
self.slide.pickleable()
|
|
388
|
+
|
|
389
|
+
quantity_queue = mp.Queue() # Queue for storing computed stain quantities
|
|
390
|
+
remainder_queue = mp.Queue() # Queue for storing leftover pixels
|
|
391
|
+
stop_event = mp.Event()
|
|
392
|
+
|
|
393
|
+
# Give workers tasks
|
|
394
|
+
workers = []
|
|
395
|
+
for i in range(num_workers):
|
|
396
|
+
p = mp.Process(target=self.compute_task, args=(quantity, self.slide, coord_queue, quantity_queue, self.I0, self.alpha, self.beta, threshold, remainder_queue, stop_event, self.use_nnls, self.matrix_avg))
|
|
397
|
+
p.start()
|
|
398
|
+
workers.append(p)
|
|
399
|
+
|
|
400
|
+
# Accumulate matrices
|
|
401
|
+
quantity_buffer = []
|
|
402
|
+
tiles = 0
|
|
403
|
+
finished_workers = 0
|
|
404
|
+
try:
|
|
405
|
+
while finished_workers < num_workers and len(quantity_buffer) < num_tiles:
|
|
406
|
+
q = quantity_queue.get()
|
|
407
|
+
if q is None:
|
|
408
|
+
finished_workers += 1
|
|
409
|
+
else:
|
|
410
|
+
quantity_buffer.append(q)
|
|
411
|
+
tiles += 1
|
|
412
|
+
if tiles % 100 == 0:
|
|
413
|
+
print(f"Processed {tiles} tiles so far...")
|
|
414
|
+
finally:
|
|
415
|
+
stop_event.set()
|
|
416
|
+
|
|
417
|
+
# Handle any remaining pixels
|
|
418
|
+
stain_balancing = isinstance(threshold, tuple)
|
|
419
|
+
if stain_balancing:
|
|
420
|
+
remainder_buffer = [[], []]
|
|
421
|
+
pixels = [0, 0]
|
|
422
|
+
else:
|
|
423
|
+
remainder_buffer = []
|
|
424
|
+
pixels = 0
|
|
425
|
+
used_remainder = False
|
|
426
|
+
for i in range(num_workers):
|
|
427
|
+
try:
|
|
428
|
+
remainder = remainder_queue.get(timeout=2.0)
|
|
429
|
+
|
|
430
|
+
if stain_balancing:
|
|
431
|
+
|
|
432
|
+
if len(remainder[0]) == 0 and len(remainder[1]) == 0:
|
|
433
|
+
continue
|
|
434
|
+
remainder[0] = np.concatenate(remainder[0], axis=0)
|
|
435
|
+
remainder[1] = np.concatenate(remainder[1], axis=0)
|
|
436
|
+
pixels[0] += remainder[0].shape[0]
|
|
437
|
+
pixels[1] += remainder[1].shape[0]
|
|
438
|
+
remainder_buffer[0].append(remainder[0])
|
|
439
|
+
remainder_buffer[1].append(remainder[1])
|
|
440
|
+
|
|
441
|
+
if (pixels[0] > threshold[0] and pixels[1] > threshold[1]) or (i + 1 == num_workers and len(remainder_buffer[0]) > 0 and len(remainder_buffer[1]) > 0 and not used_remainder):
|
|
442
|
+
htx_vals = np.concatenate(remainder_buffer[0], axis=0) # (N_htx,3)
|
|
443
|
+
dab_vals = np.concatenate(remainder_buffer[1], axis=0) # (N_dab,3)
|
|
444
|
+
vals = np.concatenate([htx_vals, dab_vals], axis=0) # (N,3)
|
|
445
|
+
remainder_buffer = [[], []]
|
|
446
|
+
pixels = [0, 0]
|
|
447
|
+
if quantity == "matrix":
|
|
448
|
+
matrix = MacenkoStyleEstimation.svd(vals, self.alpha)
|
|
449
|
+
quantity_buffer.append(matrix)
|
|
450
|
+
else:
|
|
451
|
+
vals = vals.transpose()
|
|
452
|
+
if self.use_nnls:
|
|
453
|
+
C = nnls(self.matrix_avg, vals) # (2,N)
|
|
454
|
+
else:
|
|
455
|
+
C = np.linalg.lstsq(self.matrix_avg, vals, rcond=None)[0]
|
|
456
|
+
maxC = np.array([np.percentile(C[0, :], 100 - self.alpha), np.percentile(C[1, :], 100 - self.alpha)])
|
|
457
|
+
quantity_buffer.append(maxC)
|
|
458
|
+
used_remainder = True
|
|
459
|
+
|
|
460
|
+
else:
|
|
461
|
+
|
|
462
|
+
if len(remainder) == 0:
|
|
463
|
+
continue
|
|
464
|
+
remainder = np.concatenate(remainder, axis=0)
|
|
465
|
+
pixels += remainder.shape[0]
|
|
466
|
+
remainder_buffer.append(remainder)
|
|
467
|
+
|
|
468
|
+
if pixels > threshold or (i + 1 == num_workers and len(remainder_buffer) > 0 and not used_remainder):
|
|
469
|
+
vals = np.concatenate(remainder_buffer, axis=0)
|
|
470
|
+
remainder_buffer = []
|
|
471
|
+
pixels = 0
|
|
472
|
+
if quantity == "matrix":
|
|
473
|
+
matrix = MacenkoStyleEstimation.svd(vals, self.alpha)
|
|
474
|
+
quantity_buffer.append(matrix)
|
|
475
|
+
else:
|
|
476
|
+
vals = vals.transpose()
|
|
477
|
+
if self.use_nnls:
|
|
478
|
+
C = nnls(self.matrix_avg, vals) # (2,N)
|
|
479
|
+
else:
|
|
480
|
+
C = np.linalg.lstsq(self.matrix_avg, vals, rcond=None)[0]
|
|
481
|
+
maxC = np.array([np.percentile(C[0, :], 100 - self.alpha), np.percentile(C[1, :], 100 - self.alpha)])
|
|
482
|
+
quantity_buffer.append(maxC)
|
|
483
|
+
used_remainder = True
|
|
484
|
+
|
|
485
|
+
except queue.Empty:
|
|
486
|
+
pass
|
|
487
|
+
|
|
488
|
+
for w in workers:
|
|
489
|
+
w.join(timeout=1.0)
|
|
490
|
+
if w.is_alive():
|
|
491
|
+
w.terminate()
|
|
492
|
+
|
|
493
|
+
if quantity == "matrix":
|
|
494
|
+
self.matrix_buffer = quantity_buffer
|
|
495
|
+
self.matrix_avg = np.mean(quantity_buffer, axis=0)
|
|
496
|
+
else:
|
|
497
|
+
self.maxC_buffer = quantity_buffer
|
|
498
|
+
if maxC_mode == "mean":
|
|
499
|
+
self.maxC_avg = np.mean(quantity_buffer, axis=0)
|
|
500
|
+
elif maxC_mode == "percentile":
|
|
501
|
+
self.maxC_avg = np.percentile(quantity_buffer, 100 - self.alpha, axis=0)
|
|
502
|
+
|
|
503
|
+
# Re-load slide
|
|
504
|
+
self.slide.load_slide()
|
|
505
|
+
|
|
506
|
+
# Close queues
|
|
507
|
+
coord_queue.close()
|
|
508
|
+
coord_queue.cancel_join_thread()
|
|
509
|
+
quantity_queue.close()
|
|
510
|
+
quantity_queue.cancel_join_thread()
|
|
511
|
+
remainder_queue.close()
|
|
512
|
+
remainder_queue.cancel_join_thread()
|
|
513
|
+
|
|
514
|
+
|
|
515
|
+
def compute_tiled(self, threshold: int | tuple[int, int], quantity: str, num_tiles: int = 500, tile_size: int = 512, detect_fg: bool = False, maxC_mode: str = "mean", **kwargs):
|
|
516
|
+
"""Compute stain matrix or maxC using tiles (but not in parallel).
|
|
517
|
+
|
|
518
|
+
Args:
|
|
519
|
+
threshold: Min number of pixels to accumulate before calculating the quantity. If int, there is one threshold. If tuple of two ints, the first is for hematoxylin and second for DAB.
|
|
520
|
+
quantity: Either "matrix" or "maxC" depending on the quantity of interest to calculate.
|
|
521
|
+
num_tiles: Max number of tiles to use for estimation.
|
|
522
|
+
tile_size: Tile size to use.
|
|
523
|
+
detect_fg: Detect where the tissue is using the thumbnail.
|
|
524
|
+
maxC_mode: Type of statistic to calculate over maxC values ("mean" or "percentile" for 100 - alpha percentile of maxC values).
|
|
525
|
+
"""
|
|
526
|
+
|
|
527
|
+
print(f"Computing stain {quantity}...")
|
|
528
|
+
print(f"Min pixels to accumulate before calculating = {threshold}")
|
|
529
|
+
print(f"Max tiles to use = {num_tiles}")
|
|
530
|
+
print(f"Tile size = {tile_size}")
|
|
531
|
+
print(f"Detect foreground from thumbnail first = {detect_fg}")
|
|
532
|
+
if quantity == "maxC":
|
|
533
|
+
print(f"maxC estimates are aggregated via = {maxC_mode}")
|
|
534
|
+
|
|
535
|
+
# Input checks
|
|
536
|
+
if not (isinstance(threshold, int) or (isinstance(threshold, tuple) and len(threshold) == 2)):
|
|
537
|
+
raise Exception("threshold needs to be an int or tuple of two ints")
|
|
538
|
+
if not (quantity == "matrix" or quantity == "maxC"):
|
|
539
|
+
raise Exception("quantity needs to be either matrix or maxC")
|
|
540
|
+
if quantity == "maxC" and self.matrix_avg is None:
|
|
541
|
+
raise Exception("Stain matrix needs to be computed before maxC")
|
|
542
|
+
|
|
543
|
+
# Set tile size
|
|
544
|
+
self.slide.set_tile_size(tile_size)
|
|
545
|
+
|
|
546
|
+
# Foreground detection
|
|
547
|
+
if detect_fg:
|
|
548
|
+
coords = self.slide.compute_random_sequence()
|
|
549
|
+
self.slide.filter_coords_using_thumbnail(hsv_threshold_foreground, coords)
|
|
550
|
+
self.slide.set_mode("custom")
|
|
551
|
+
else:
|
|
552
|
+
self.slide.set_mode("random")
|
|
553
|
+
|
|
554
|
+
stain_balancing = isinstance(threshold, tuple)
|
|
555
|
+
|
|
556
|
+
if stain_balancing:
|
|
557
|
+
buffer = [[], []]
|
|
558
|
+
pixels = [0, 0]
|
|
559
|
+
else:
|
|
560
|
+
buffer = []
|
|
561
|
+
pixels = 0
|
|
562
|
+
|
|
563
|
+
tiles = 0
|
|
564
|
+
quantity_buffer = []
|
|
565
|
+
|
|
566
|
+
iter_len = len(self.slide)
|
|
567
|
+
|
|
568
|
+
for i, (tile, _) in enumerate(self.slide):
|
|
569
|
+
|
|
570
|
+
filtered = self.convert_od_and_filter(tile, self.I0, self.beta)
|
|
571
|
+
|
|
572
|
+
if filtered.shape[0] > 0:
|
|
573
|
+
|
|
574
|
+
if stain_balancing:
|
|
575
|
+
tile_hsv = tile.hsv().reshape(-1,3)
|
|
576
|
+
filtered_hsv = tile_hsv[mask]
|
|
577
|
+
buffer_assignment = MacenkoStyleEstimation.get_buffer_assignment(filtered_hsv)
|
|
578
|
+
htx = filtered[~buffer_assignment]
|
|
579
|
+
dab = filtered[buffer_assignment]
|
|
580
|
+
if len(htx.shape) != 2:
|
|
581
|
+
htx = htx[np.newaxis, :]
|
|
582
|
+
if len(dab.shape) != 2:
|
|
583
|
+
dab = dab[np.newaxis, :]
|
|
584
|
+
if htx.shape[0] > 0 and pixels[0] <= threshold[0]:
|
|
585
|
+
buffer[0].append(htx)
|
|
586
|
+
pixels[0] += htx.shape[0]
|
|
587
|
+
if dab.shape[0] > 0 and pixels[1] <= threshold[1]:
|
|
588
|
+
buffer[1].append(dab)
|
|
589
|
+
pixels[1] += dab.shape[0]
|
|
590
|
+
else:
|
|
591
|
+
buffer.append(filtered)
|
|
592
|
+
pixels += filtered.shape[0]
|
|
593
|
+
|
|
594
|
+
if not stain_balancing and (pixels > threshold or (i + 1 == iter_len and len(quantity_buffer) == 0)):
|
|
595
|
+
|
|
596
|
+
vals = np.concatenate(buffer, axis=0)
|
|
597
|
+
buffer = []
|
|
598
|
+
pixels = 0
|
|
599
|
+
if quantity == "matrix":
|
|
600
|
+
matrix = MacenkoStyleEstimation.svd(vals, self.alpha)
|
|
601
|
+
quantity_buffer.append(matrix)
|
|
602
|
+
else:
|
|
603
|
+
vals = vals.transpose()
|
|
604
|
+
if self.use_nnls:
|
|
605
|
+
C = nnls(self.matrix_avg, vals) # (2,N)
|
|
606
|
+
else:
|
|
607
|
+
C = np.linalg.lstsq(self.matrix_avg, vals, rcond=None)[0]
|
|
608
|
+
maxC = np.array([np.percentile(C[0, :], 100 - self.alpha), np.percentile(C[1, :], 100 - self.alpha)])
|
|
609
|
+
quantity_buffer.append(maxC)
|
|
610
|
+
tiles += 1
|
|
611
|
+
|
|
612
|
+
if tiles % 100 == 0:
|
|
613
|
+
print(f"Processed {tiles} tiles so far...")
|
|
614
|
+
|
|
615
|
+
elif stain_balancing and ((pixels[0] > threshold[0] and pixels[1] > threshold[1]) or (i + 1 == iter_len and len(quantity_buffer) == 0)):
|
|
616
|
+
|
|
617
|
+
htx_vals = np.concatenate(buffer[0], axis=0) # (N_htx,3)
|
|
618
|
+
dab_vals = np.concatenate(buffer[1], axis=0) # (N_dab,3)
|
|
619
|
+
vals = np.concatenate([htx_vals, dab_vals], axis=0) # (N,3)
|
|
620
|
+
pixels = [0, 0]
|
|
621
|
+
buffer = [[], []]
|
|
622
|
+
if quantity == "matrix":
|
|
623
|
+
matrix = MacenkoStyleEstimation.svd(vals, self.alpha)
|
|
624
|
+
quantity_buffer.append(matrix)
|
|
625
|
+
else:
|
|
626
|
+
vals = vals.transpose()
|
|
627
|
+
if self.use_nnls:
|
|
628
|
+
C = nnls(self.matrix_avg, vals) # (2,N)
|
|
629
|
+
else:
|
|
630
|
+
C = np.linalg.lstsq(self.matrix_avg, vals, rcond=None)[0]
|
|
631
|
+
maxC = np.array([np.percentile(C[0, :], 100 - self.alpha), np.percentile(C[1, :], 100 - self.alpha)])
|
|
632
|
+
quantity_buffer.append(maxC)
|
|
633
|
+
tiles += 1
|
|
634
|
+
|
|
635
|
+
if tiles % 100 == 0:
|
|
636
|
+
print(f"Processed {tiles} tiles so far...")
|
|
637
|
+
|
|
638
|
+
if tiles > num_tiles:
|
|
639
|
+
break
|
|
640
|
+
|
|
641
|
+
if quantity == "matrix":
|
|
642
|
+
self.matrix_buffer = quantity_buffer
|
|
643
|
+
self.matrix_avg = np.mean(quantity_buffer, axis=0)
|
|
644
|
+
else:
|
|
645
|
+
self.maxC_buffer = quantity_buffer
|
|
646
|
+
if maxC_mode == "mean":
|
|
647
|
+
self.maxC_avg = np.mean(quantity_buffer, axis=0)
|
|
648
|
+
elif _mode == "percentile":
|
|
649
|
+
self.maxC_avg = np.percentile(quantity_buffer, 100 - self.alpha, axis=0)
|