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,302 @@
|
|
|
1
|
+
from stainnormprogram.slide import SlideImage
|
|
2
|
+
|
|
3
|
+
from stainnormprogram.norm.subset import Subset
|
|
4
|
+
from stainnormprogram.norm.adjustments import Adjustment
|
|
5
|
+
from stainnormprogram.norm.pipeline.pipeline import Pipeline
|
|
6
|
+
from stainnormprogram.norm.background import HSVBackgroundEstimation, hsv_threshold_foreground
|
|
7
|
+
from stainnormprogram.norm.style_estimation.macenko import MacenkoStyleEstimation
|
|
8
|
+
from stainnormprogram.norm.translation.macenko import MacenkoTranslation
|
|
9
|
+
|
|
10
|
+
from stainnormprogram.io.write_slide import TiledWriter
|
|
11
|
+
|
|
12
|
+
import os
|
|
13
|
+
import json
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
import numpy as np
|
|
17
|
+
|
|
18
|
+
class MacenkoPipeline(Pipeline):
|
|
19
|
+
|
|
20
|
+
def __init__(
|
|
21
|
+
self,
|
|
22
|
+
stain: str = "HE",
|
|
23
|
+
bkgd_method: str = "tiled",
|
|
24
|
+
bkgd_options: dict[str, Any] = {},
|
|
25
|
+
style_est_mode: str = "tiled_parallel",
|
|
26
|
+
style_est_options: dict[str, Any] = {"detect_fg": True},
|
|
27
|
+
alpha: float = 1.0,
|
|
28
|
+
beta: float = 0.15,
|
|
29
|
+
use_nnls: bool = True,
|
|
30
|
+
maxworkers: int | None = None,
|
|
31
|
+
compression: str | None = "zlib",
|
|
32
|
+
):
|
|
33
|
+
"""Create a Macenko pipeline.
|
|
34
|
+
|
|
35
|
+
Args:
|
|
36
|
+
stain: Stain type (either "HE" or "DAB").
|
|
37
|
+
bkgd_method: Background estimation method ("thumbnail", "tiled", or "pyvips").
|
|
38
|
+
bkgd_options: Kwargs for background estimation.
|
|
39
|
+
style_est_mode: Style estimation mode ("tiled_parallel", "thumbnail", or "tiled").
|
|
40
|
+
style_est_options: Kwargs for style estimation.
|
|
41
|
+
alpha: Macenko's alpha.
|
|
42
|
+
beta: Macenko's beta.
|
|
43
|
+
use_nnls: Use non-negative least squares for concentration estimations.
|
|
44
|
+
maxworkers: Max workers for style estimation and file saving (None calculates this for you).
|
|
45
|
+
compression: Compression method for file saving (None, "zlib", or "jpeg").
|
|
46
|
+
"""
|
|
47
|
+
super().__init__()
|
|
48
|
+
|
|
49
|
+
self.stain = stain
|
|
50
|
+
|
|
51
|
+
self.bkgd_method = bkgd_method
|
|
52
|
+
self.bkgd_options = bkgd_options
|
|
53
|
+
|
|
54
|
+
self.style_est_mode = style_est_mode
|
|
55
|
+
self.style_est_options = style_est_options
|
|
56
|
+
self.alpha = alpha
|
|
57
|
+
self.beta = beta
|
|
58
|
+
self.use_nnls = use_nnls
|
|
59
|
+
|
|
60
|
+
self.maxworkers = maxworkers
|
|
61
|
+
self.compression = compression
|
|
62
|
+
|
|
63
|
+
self.target_style = None
|
|
64
|
+
|
|
65
|
+
if not (self.stain == "HE" or self.stain == "DAB"):
|
|
66
|
+
raise Exception(f"{self.stain} is not a valid stain.")
|
|
67
|
+
|
|
68
|
+
def __repr__(self):
|
|
69
|
+
return "MacenkoPipeline"
|
|
70
|
+
|
|
71
|
+
def calculate_style(self, slide: SlideImage, pre_adjustment: Adjustment | None = None) -> dict[str, str | np.ndarray]:
|
|
72
|
+
"""Calculate the stain style of an image.
|
|
73
|
+
|
|
74
|
+
Args:
|
|
75
|
+
slide: Slide image to calculate the style of.
|
|
76
|
+
pre_adjustment: Adjustment to be performed on the slide image before calculating the style.
|
|
77
|
+
|
|
78
|
+
Returns:
|
|
79
|
+
A dictionary containing the calculated style.
|
|
80
|
+
"""
|
|
81
|
+
|
|
82
|
+
slide.set_adjustment(pre_adjustment)
|
|
83
|
+
|
|
84
|
+
bgd_est = HSVBackgroundEstimation(slide)
|
|
85
|
+
background_result = bgd_est.compute(method=self.bkgd_method, options=self.bkgd_options)
|
|
86
|
+
I0 = background_result["median"]
|
|
87
|
+
print(f"Estimated I0: {I0}")
|
|
88
|
+
|
|
89
|
+
mse = MacenkoStyleEstimation(slide,
|
|
90
|
+
I0,
|
|
91
|
+
mode=self.style_est_mode,
|
|
92
|
+
stain_balancing=True if self.stain == "DAB" else False,
|
|
93
|
+
alpha=self.alpha,
|
|
94
|
+
beta=self.beta,
|
|
95
|
+
use_nnls=self.use_nnls,
|
|
96
|
+
maxworkers=self.maxworkers,
|
|
97
|
+
options=self.style_est_options,
|
|
98
|
+
)
|
|
99
|
+
mse.compute_matrix()
|
|
100
|
+
mse.compute_maxC()
|
|
101
|
+
|
|
102
|
+
style = {
|
|
103
|
+
"id": slide.identifier,
|
|
104
|
+
"matrix": mse.matrix_avg,
|
|
105
|
+
"maxC": mse.maxC_avg,
|
|
106
|
+
"I0": I0
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
return style
|
|
110
|
+
|
|
111
|
+
def calculate_style_average(self, slides: dict[str, SlideImage], pre_adjustments: Adjustment | dict[str, Adjustment] | None = None) -> dict[str, str | np.ndarray]:
|
|
112
|
+
"""Calculate the stain style of one image or the average stain style of multiple images.
|
|
113
|
+
|
|
114
|
+
Args:
|
|
115
|
+
slides: One or more slide images to calculate the stain styles of. Key is the image ID (filename without extension) and value is the SlideImage.
|
|
116
|
+
pre_adjustments: Adjustments to be performed to the images before calculating the stain style. If dict, key is the image ID (filename without extension) and value is the Adjustment.
|
|
117
|
+
|
|
118
|
+
Returns:
|
|
119
|
+
A dictionary containing the average stain style.
|
|
120
|
+
"""
|
|
121
|
+
|
|
122
|
+
styles = []
|
|
123
|
+
|
|
124
|
+
# Calculate the style of each image
|
|
125
|
+
for slide_id, slide in slides.items():
|
|
126
|
+
|
|
127
|
+
pre_adjustment = None
|
|
128
|
+
if pre_adjustments is not None:
|
|
129
|
+
if isinstance(pre_adjustments, Adjustment):
|
|
130
|
+
pre_adjustment = pre_adjustments
|
|
131
|
+
else:
|
|
132
|
+
pre_adjustment = pre_adjustments.get(slide_id, None)
|
|
133
|
+
|
|
134
|
+
style = self.calculate_style(slide, pre_adjustment=pre_adjustment)
|
|
135
|
+
styles.append(style)
|
|
136
|
+
|
|
137
|
+
# Average
|
|
138
|
+
matrices = []
|
|
139
|
+
maxCs = []
|
|
140
|
+
I0s = []
|
|
141
|
+
for style in styles:
|
|
142
|
+
matrices.append(style["matrix"])
|
|
143
|
+
maxCs.append(style["maxC"])
|
|
144
|
+
I0s.append(style["I0"])
|
|
145
|
+
avg_style = {}
|
|
146
|
+
avg_style["matrix"] = np.mean(matrices, axis=0)
|
|
147
|
+
avg_style["maxC"] = np.mean(maxCs, axis=0)
|
|
148
|
+
avg_style["I0"] = np.mean(I0s, axis=0)
|
|
149
|
+
|
|
150
|
+
return avg_style
|
|
151
|
+
|
|
152
|
+
def save_style(self, style: dict[str, str | np.ndarray], filename: str, subfolder: str = ""):
|
|
153
|
+
"""Save the staining style to a JSON file.
|
|
154
|
+
|
|
155
|
+
Staining styles are saved to the folder from using ``set_output_dir``.
|
|
156
|
+
|
|
157
|
+
Args:
|
|
158
|
+
style: Staining style to save.
|
|
159
|
+
filename: Base name of the output file with .json.
|
|
160
|
+
subfolder: Subfolder paths to insert between the output_dir and filename (leave as an empty string if no subfolders are desired).
|
|
161
|
+
"""
|
|
162
|
+
output_path = os.path.join(self.output_dir, subfolder, filename)
|
|
163
|
+
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
|
164
|
+
if os.path.exists(output_path):
|
|
165
|
+
raise Exception(f"Output style path {output_path} already exists.")
|
|
166
|
+
|
|
167
|
+
output_dict = {}
|
|
168
|
+
for key, value in style.items():
|
|
169
|
+
if isinstance(value, np.ndarray):
|
|
170
|
+
output_dict[key] = value.tolist()
|
|
171
|
+
else:
|
|
172
|
+
output_dict[key] = value
|
|
173
|
+
|
|
174
|
+
with open(output_path, "w") as file:
|
|
175
|
+
json.dump(output_dict, file, indent=4)
|
|
176
|
+
|
|
177
|
+
print(f"Saved stain style to {output_path}")
|
|
178
|
+
|
|
179
|
+
def load_style(self, path: str, separate: bool = False) -> dict[str, str | np.ndarray] | tuple[str | np.ndarray]:
|
|
180
|
+
"""Load stain style.
|
|
181
|
+
|
|
182
|
+
Args:
|
|
183
|
+
path: JSON file path of the staining style to open.
|
|
184
|
+
separate: If True, return as matrix, maxC, I0 tuple. If False, return as a dictionary.
|
|
185
|
+
|
|
186
|
+
Returns:
|
|
187
|
+
Either a dictionary or tuple constaining of the matrix, maxC, and I0.
|
|
188
|
+
"""
|
|
189
|
+
with open(path, "r") as file:
|
|
190
|
+
style = json.load(file)
|
|
191
|
+
style["matrix"] = np.array(style["matrix"])
|
|
192
|
+
style["maxC"] = np.array(style["maxC"])
|
|
193
|
+
style["I0"] = np.array(style["I0"])
|
|
194
|
+
if not separate:
|
|
195
|
+
return style
|
|
196
|
+
return style["matrix"], style["maxC"], style["I0"]
|
|
197
|
+
|
|
198
|
+
def set_target_from_json(self, target: str):
|
|
199
|
+
"""Set target style from a stain style JSON file.
|
|
200
|
+
|
|
201
|
+
Args:
|
|
202
|
+
target: JSON file path of the target stain style.
|
|
203
|
+
"""
|
|
204
|
+
self.target_style = self.load_style(target)
|
|
205
|
+
|
|
206
|
+
def transform_source(self, slide: SlideImage, source_style: dict[str, str | np.ndarray], pre_adjustment: Adjustment | None = None, post_adjustment: Adjustment | None = None, subfolder: str = ""):
|
|
207
|
+
"""Transform the source image (i.e., perform the color transformation).
|
|
208
|
+
|
|
209
|
+
Args:
|
|
210
|
+
slide: SlideImage to transform.
|
|
211
|
+
source_style: Dictionary containing the source stain style.
|
|
212
|
+
pre_adjustment: Adjustment to apply before transforming the source image.
|
|
213
|
+
post_adjustment: Adjustment to apply after transforming the source image.
|
|
214
|
+
subfolder: Subfolder paths to insert between the output_dir and filename (leave as an empty string if no subfolders are desired).
|
|
215
|
+
"""
|
|
216
|
+
|
|
217
|
+
mt = MacenkoTranslation(slide,
|
|
218
|
+
self.target_style["matrix"],
|
|
219
|
+
self.target_style["maxC"],
|
|
220
|
+
self.target_style["I0"],
|
|
221
|
+
source_style["matrix"],
|
|
222
|
+
source_style["maxC"],
|
|
223
|
+
source_style["I0"],
|
|
224
|
+
pre_adjustment=pre_adjustment,
|
|
225
|
+
post_adjustment=post_adjustment,
|
|
226
|
+
use_nnls=self.use_nnls,
|
|
227
|
+
)
|
|
228
|
+
|
|
229
|
+
output_path = os.path.join(self.output_dir, subfolder, slide.identifier + ".tif")
|
|
230
|
+
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
|
231
|
+
tw = TiledWriter(output_path, slide.shape, slide.tile_size, slide.resolution[0], slide.resolution[1], maxworkers=self.maxworkers, compression=self.compression)
|
|
232
|
+
tw.write(mt.translate)
|
|
233
|
+
|
|
234
|
+
def run(self):
|
|
235
|
+
"""Run the pipeline.
|
|
236
|
+
"""
|
|
237
|
+
|
|
238
|
+
# Calculate target style if needed
|
|
239
|
+
if self.target_style is None:
|
|
240
|
+
print("Calculating target style...")
|
|
241
|
+
self.target_style = self.calculate_style_average(self.target)
|
|
242
|
+
self.save_style(self.target_style, "target.json")
|
|
243
|
+
|
|
244
|
+
# Process each source item
|
|
245
|
+
for key, value in self.source.items():
|
|
246
|
+
# value could be a SlideImage or a Subset
|
|
247
|
+
|
|
248
|
+
if isinstance(value, Subset):
|
|
249
|
+
|
|
250
|
+
print(f"Processing {value.identifier}...")
|
|
251
|
+
|
|
252
|
+
# Get reference
|
|
253
|
+
reference_style = None
|
|
254
|
+
if value.reference_json is not None:
|
|
255
|
+
reference_style = self.load_style(value.reference_json)
|
|
256
|
+
elif len(value.reference) > 0:
|
|
257
|
+
print("Calculating reference style...")
|
|
258
|
+
pre_adjustments = None
|
|
259
|
+
if value.global_pre_adjustment is not None and value.global_pre_adjustment_includes_reference:
|
|
260
|
+
pre_adjustments = value.global_pre_adjustment
|
|
261
|
+
else:
|
|
262
|
+
pre_adjustments = value.reference_pre_adjustments
|
|
263
|
+
reference_style = self.calculate_style_average(value.reference, pre_adjustments=pre_adjustments)
|
|
264
|
+
self.save_style(reference_style, value.identifier + "_reference.json", subfolder=key if self.save_by_subset else "")
|
|
265
|
+
|
|
266
|
+
# Norm
|
|
267
|
+
for subset_k, subset_v in value.images.items():
|
|
268
|
+
# Get pre-adjustment
|
|
269
|
+
pre_adjustment = None
|
|
270
|
+
if subset_k in value.pre_adjustments:
|
|
271
|
+
pre_adjustment = value.pre_adjustments[subset_k]
|
|
272
|
+
elif value.global_pre_adjustment is not None:
|
|
273
|
+
pre_adjustment = value.global_pre_adjustment
|
|
274
|
+
|
|
275
|
+
# Calculate source style
|
|
276
|
+
source_style = None
|
|
277
|
+
if reference_style is None:
|
|
278
|
+
print(f"Calculating source style of {subset_k}...")
|
|
279
|
+
source_style = self.calculate_style(subset_v, pre_adjustment=pre_adjustment)
|
|
280
|
+
self.save_style(source_style, subset_k + ".json", subfolder=key if self.save_by_subset else "")
|
|
281
|
+
else:
|
|
282
|
+
source_style = reference_style
|
|
283
|
+
|
|
284
|
+
# Get post-adjustment
|
|
285
|
+
post_adjustment = None
|
|
286
|
+
if subset_k in value.post_adjustments:
|
|
287
|
+
post_adjustment = value.post_adjustments[subset_k]
|
|
288
|
+
elif value.global_post_adjustment is not None:
|
|
289
|
+
post_adjustment = value.global_post_adjustment
|
|
290
|
+
|
|
291
|
+
# Transform image
|
|
292
|
+
print(f"Transforming {subset_k}...")
|
|
293
|
+
self.transform_source(subset_v, source_style, pre_adjustment=pre_adjustment, post_adjustment=post_adjustment, subfolder=key if self.save_by_subset else "")
|
|
294
|
+
|
|
295
|
+
elif isinstance(value, SlideImage):
|
|
296
|
+
|
|
297
|
+
print(f"Processing {value.identifier}...")
|
|
298
|
+
|
|
299
|
+
source_style = self.calculate_style(value)
|
|
300
|
+
self.save_style(source_style, key + ".json")
|
|
301
|
+
self.transform_source(value, source_style)
|
|
302
|
+
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Abstract class for stain normalization pipelines.
|
|
3
|
+
|
|
4
|
+
General pipeline steps for normalization:
|
|
5
|
+
1. Calculate a target style
|
|
6
|
+
2. Calculate a source style
|
|
7
|
+
3. Transform the source
|
|
8
|
+
"""
|
|
9
|
+
from stainnormprogram.slide import SlideImage
|
|
10
|
+
from stainnormprogram.norm.subset import Subset
|
|
11
|
+
|
|
12
|
+
from abc import ABC, abstractmethod
|
|
13
|
+
|
|
14
|
+
class Pipeline(ABC):
|
|
15
|
+
|
|
16
|
+
def __init__(self):
|
|
17
|
+
|
|
18
|
+
self.target = None
|
|
19
|
+
self.source = None
|
|
20
|
+
|
|
21
|
+
self.output_dir = None
|
|
22
|
+
self.save_by_subset = True
|
|
23
|
+
|
|
24
|
+
def set_target(self, target: dict[str, SlideImage]):
|
|
25
|
+
"""
|
|
26
|
+
Args:
|
|
27
|
+
target: Key is the image ID (filename without extension) and value is the SlideImage.
|
|
28
|
+
"""
|
|
29
|
+
self.target = target
|
|
30
|
+
|
|
31
|
+
@abstractmethod
|
|
32
|
+
def set_target_from_json(self, target: str):
|
|
33
|
+
"""Set the target style from a JSON.
|
|
34
|
+
|
|
35
|
+
Args:
|
|
36
|
+
target: Path to a JSON file containing the target style.
|
|
37
|
+
"""
|
|
38
|
+
pass
|
|
39
|
+
|
|
40
|
+
def set_source(self, source: dict[str, SlideImage | Subset]):
|
|
41
|
+
"""
|
|
42
|
+
Args:
|
|
43
|
+
source: Key is the image ID (filename without extension) or subset ID. Value is the SlideImage or Subset.
|
|
44
|
+
"""
|
|
45
|
+
self.source = source
|
|
46
|
+
|
|
47
|
+
@abstractmethod
|
|
48
|
+
def run(self):
|
|
49
|
+
"""Run the pipeline.
|
|
50
|
+
"""
|
|
51
|
+
pass
|
|
52
|
+
|
|
53
|
+
def set_output_dir(self, output_dir: str, save_by_subset: bool = True):
|
|
54
|
+
"""
|
|
55
|
+
Args:
|
|
56
|
+
output_dir: Output directory.
|
|
57
|
+
save_by_subset: Within the output_dir, save each Subset into its own subfolder.
|
|
58
|
+
"""
|
|
59
|
+
self.output_dir = output_dir
|
|
60
|
+
self.save_by_subset = save_by_subset
|
|
61
|
+
|
|
File without changes
|