wsi-patching 0.5.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.
Files changed (50) hide show
  1. wsi_patching/__init__.py +38 -0
  2. wsi_patching/annotations/__init__.py +3 -0
  3. wsi_patching/annotations/add_cell_annotation_from_csv.py +152 -0
  4. wsi_patching/assets/models/cellvit_tissue_detector.pt +0 -0
  5. wsi_patching/backends/__init__.py +0 -0
  6. wsi_patching/backends/cupy_numpy.py +80 -0
  7. wsi_patching/backends/fastslide.py +243 -0
  8. wsi_patching/backends/torch_device.py +45 -0
  9. wsi_patching/core/__init__.py +4 -0
  10. wsi_patching/core/chunking_and_batching.py +519 -0
  11. wsi_patching/core/pipeline.py +566 -0
  12. wsi_patching/core/types/__init__.py +0 -0
  13. wsi_patching/core/types/types.py +145 -0
  14. wsi_patching/core/types/util_types.py +93 -0
  15. wsi_patching/core/wsi_grid.py +119 -0
  16. wsi_patching/custom_component/__init__.py +18 -0
  17. wsi_patching/encoders/__init__.py +3 -0
  18. wsi_patching/encoders/pngencoder.py +72 -0
  19. wsi_patching/filtering/__init__.py +15 -0
  20. wsi_patching/filtering/cellvit_tissue_classifier_filter.py +124 -0
  21. wsi_patching/filtering/low_contrast_background_filter.py +125 -0
  22. wsi_patching/filtering/otsu_filter.py +217 -0
  23. wsi_patching/filtering/pen_artifact_filter.py +216 -0
  24. wsi_patching/py.typed +0 -0
  25. wsi_patching/regions_of_interest/__init__.py +4 -0
  26. wsi_patching/regions_of_interest/attach_rois.py +59 -0
  27. wsi_patching/regions_of_interest/roi_providers.py +94 -0
  28. wsi_patching/regions_of_interest/rois.py +78 -0
  29. wsi_patching/transforms/__init__.py +4 -0
  30. wsi_patching/transforms/macenko_normalizer.py +175 -0
  31. wsi_patching/transforms/reinhard_normalizer.py +271 -0
  32. wsi_patching/utils/__init__.py +3 -0
  33. wsi_patching/utils/logging_config.py +13 -0
  34. wsi_patching/utils/meta_typing.py +94 -0
  35. wsi_patching/utils/profiling.py +115 -0
  36. wsi_patching/utils/wsi_thumbnail_visualization.py +208 -0
  37. wsi_patching/writers/__init__.py +10 -0
  38. wsi_patching/writers/materialize_writers/__init__.py +0 -0
  39. wsi_patching/writers/materialize_writers/materialize_writer_base.py +92 -0
  40. wsi_patching/writers/materialize_writers/webdataset/__init__.py +0 -0
  41. wsi_patching/writers/materialize_writers/webdataset/webdataset_loader.py +165 -0
  42. wsi_patching/writers/materialize_writers/webdataset/webdataset_writer.py +69 -0
  43. wsi_patching/writers/stream_writers/__init__.py +0 -0
  44. wsi_patching/writers/stream_writers/numpy_stream_writer.py +36 -0
  45. wsi_patching/writers/stream_writers/stream_writer_base.py +71 -0
  46. wsi_patching/writers/stream_writers/torch_stream_writer.py +67 -0
  47. wsi_patching-0.5.0.dist-info/METADATA +249 -0
  48. wsi_patching-0.5.0.dist-info/RECORD +50 -0
  49. wsi_patching-0.5.0.dist-info/WHEEL +4 -0
  50. wsi_patching-0.5.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,125 @@
1
+ from typing import Iterable
2
+
3
+ from wsi_patching.backends.cupy_numpy import ensure_array_matches_use_gpu, ensure_numpy, get_xp_backend
4
+ from wsi_patching.core.pipeline import Stage
5
+ from wsi_patching.core.types.types import CollatedPatchBatch
6
+
7
+
8
+ class LowContrastBackgroundFilter(Stage):
9
+ """
10
+ Drop patches whose grayscale dynamic range (max - min) is below a threshold.
11
+
12
+ Assumptions:
13
+ - `patches` are uint8, or float32 scaled in [0, 255].
14
+ - If ctx['use_gpu'] is True, `patches` is a CuPy array; otherwise NumPy.
15
+ - All computation stays on the active xp backend; we convert to NumPy only
16
+ at pipeline boundaries (`add_col`, `filter`) via `ensure_numpy`.
17
+
18
+ Method (per batch):
19
+ 1) Convert RGB/RGBA to grayscale in [0,1] (float32/float64).
20
+ 2) Compute per-patch dynamic range: max(gray) - min(gray).
21
+ 3) Keep patch iff range >= `range_threshold`.
22
+ """
23
+
24
+ def __init__(
25
+ self,
26
+ *,
27
+ range_threshold: float = 0.2, # threshold in grayscale [0,1] units
28
+ float_precision: str = "float32", # working precision for grayscale conversion
29
+ ):
30
+ """
31
+ Parameters
32
+ ----------
33
+ range_threshold : float in [0,1], default 0.2 (20%)
34
+ Minimum required grayscale dynamic range (max - min) to keep a patch.
35
+
36
+ float_precision : {"float32","float64"}, default "float32"
37
+ Precision for grayscale math. "float32" is typically sufficient/faster.
38
+ """
39
+ if not (0.0 <= range_threshold <= 1.0):
40
+ raise ValueError("range_threshold must be in [0, 1]")
41
+ if float_precision not in ("float32", "float64"):
42
+ raise ValueError("float_precision must be 'float32' or 'float64'")
43
+
44
+ self.range_threshold = float(range_threshold)
45
+ self.float_precision = float_precision
46
+
47
+ def validate(self):
48
+ """No-op: backend is resolved per call from ctx['use_gpu']."""
49
+ self.ctx.require_key("use_gpu")
50
+
51
+ def __call__(self, it: Iterable[CollatedPatchBatch]) -> Iterable[CollatedPatchBatch]:
52
+ """
53
+ For each batch:
54
+ - Ensure dtype/backend
55
+ - Convert to grayscale in [0,1]
56
+ - Compute per-patch range and filter
57
+ - Attach stats and yield
58
+ """
59
+ use_gpu = bool(self.ctx["use_gpu"])
60
+ xp = get_xp_backend(use_gpu)
61
+
62
+ thr = xp.asarray(self.range_threshold, dtype=xp.float32 if self.float_precision == "float32" else xp.float64)
63
+
64
+ for collated_patch_batch in it:
65
+ patches = ensure_array_matches_use_gpu(collated_patch_batch.patches, use_gpu)
66
+
67
+ # 1) RGB/RGBA -> grayscale in [0,1]
68
+ gray = self._rgb_to_gray_xp(patches, xp)
69
+
70
+ # 2) Per-patch min/max and dynamic range
71
+ B = gray.shape[0]
72
+ gray_flat = gray.reshape(B, -1)
73
+ g_min = gray_flat.min(axis=1) # (B,)
74
+ g_max = gray_flat.max(axis=1) # (B,)
75
+ g_range = (g_max - g_min).astype(gray.dtype) # (B,)
76
+
77
+ # 3) Keep iff range >= threshold
78
+ keep_batch_mask = g_range >= thr
79
+
80
+ # Record stats + filter (convert to NumPy only at the boundary)
81
+ collated_patch_batch.add_meta_column("gray_min", ensure_numpy(g_min))
82
+ collated_patch_batch.add_meta_column("gray_max", ensure_numpy(g_max))
83
+ collated_patch_batch.add_meta_column("gray_range", ensure_numpy(g_range))
84
+ collated_patch_batch.add_meta_column("range_threshold", ensure_numpy(xp.full((B,), thr, dtype=gray.dtype)))
85
+ collated_patch_batch.filter_on_mask(ensure_numpy(keep_batch_mask))
86
+
87
+ self.log.info(
88
+ f"wsi={collated_patch_batch.wsi_id} "
89
+ f"batch_out={len(collated_patch_batch.patches)} (range_threshold={self.range_threshold})"
90
+ )
91
+
92
+ if len(collated_patch_batch.patches) == 0:
93
+ continue
94
+
95
+ yield collated_patch_batch
96
+
97
+ # ---- helpers (xp-native) ----
98
+ def _rgb_to_gray_xp(self, imgs, xp):
99
+ """
100
+ Convert (B,H,W,C) to grayscale (B,H,W) in [0,1] using luminance weights.
101
+ Supports C=1 (already gray), C=3 (RGB), C=4 (RGBA → use first 3).
102
+ Output dtype honors `float_precision`.
103
+ """
104
+ if imgs.ndim != 4:
105
+ raise ValueError(f"Expected 4D (B,H,W,C); got {imgs.shape}")
106
+ C = imgs.shape[-1]
107
+ if C not in (1, 3, 4):
108
+ raise ValueError(f"Expected channels 1,3,4; got {C}")
109
+
110
+ prec = xp.float32 if self.float_precision == "float32" else xp.float64
111
+
112
+ if imgs.dtype == xp.uint8:
113
+ f = imgs.astype(prec, copy=False) / prec(255.0)
114
+ else:
115
+ # Accept float32/float64 (0..255) or other numeric types
116
+ f = imgs.astype(prec, copy=False)
117
+ f = xp.clip(f, prec(0.0), prec(255.0)) / prec(255.0)
118
+
119
+ if C == 1:
120
+ return f[..., 0]
121
+
122
+ rgb = f[..., :3]
123
+ # ITU-R BT.709-ish weights (close to skimage defaults)
124
+ coeffs = xp.asarray([0.2125, 0.7154, 0.0721], dtype=prec)
125
+ return (rgb * coeffs).sum(axis=-1, dtype=prec)
@@ -0,0 +1,217 @@
1
+ from typing import Iterable
2
+
3
+ from wsi_patching.backends.cupy_numpy import ensure_array_matches_use_gpu, ensure_numpy, get_xp_backend
4
+ from wsi_patching.core.pipeline import Stage
5
+ from wsi_patching.core.types.types import CollatedPatchBatch
6
+
7
+
8
+ class OtsuFilter(Stage):
9
+ """
10
+ Pure-xp (NumPy/CuPy) batched Otsu thresholding tissue filter.
11
+
12
+ Assumptions:
13
+ - `patches` are uint8, or float32 scaled in [0, 255].
14
+ - If ctx['use_gpu'] is True, `patches` is a CuPy array; otherwise NumPy.
15
+ - All computation stays on the active xp backend; we convert to NumPy only
16
+ at pipeline boundaries (`add_col`, `filter`) via `ensure_numpy`.
17
+
18
+ Method (per batch):
19
+ 1) Convert RGB/RGBA to grayscale in [0,1]
20
+ 2) Compute one Otsu threshold per patch (batched histograms).
21
+ 3) Build tissue mask by comparing gray to the threshold:
22
+ - if `tissue_is_darker=True`: tissue := gray < thr (common for H&E)
23
+ - if `tissue_is_darker=False`: tissue := gray >= thr
24
+ 4) Optionally drop patches with insufficient tissue coverage.
25
+ """
26
+
27
+ def __init__(
28
+ self,
29
+ *,
30
+ tissue_is_darker: bool = True,
31
+ num_bins: int = 256,
32
+ float_precision: str = "float32",
33
+ min_tissue_fraction: float = 0.0,
34
+ ):
35
+ """
36
+ Parameters
37
+ ----------
38
+ tissue_is_darker : bool, default True
39
+ Defines the tissue polarity relative to the Otsu threshold.
40
+ - True -> classify pixels darker than the threshold as tissue (gray < thr).
41
+ - False -> classify pixels brighter/equal as tissue (gray >= thr).
42
+
43
+ num_bins : int, default 256
44
+ Number of histogram bins for Otsu. Must be >= 2. For 8-bit images,
45
+ 256 is typical. Larger values may add noise; smaller values coarsen thresholds.
46
+
47
+ float_precision : {"float32","float64"}, default "float32"
48
+ Working precision for grayscale + histogram math. "float32" is usually
49
+ sufficient for uint8 inputs and is faster. "float64" will match skimage’s
50
+ historical behavior more closely.
51
+
52
+ min_tissue_fraction : float in [0,1], default 0.0
53
+ Minimum required fraction of tissue pixels per patch. Patches below this
54
+ fraction are dropped. Set to 0.0 to keep all patches.
55
+ """
56
+ if num_bins < 2:
57
+ raise ValueError("num_bins must be >= 2")
58
+ if float_precision not in ("float32", "float64"):
59
+ raise ValueError("float_precision must be 'float32' or 'float64'")
60
+ if not (0.0 <= min_tissue_fraction <= 1.0):
61
+ raise ValueError("min_tissue_fraction must be in [0, 1]")
62
+
63
+ self.tissue_is_darker = bool(tissue_is_darker)
64
+ self.num_bins = int(num_bins)
65
+ self.float_precision = float_precision
66
+ self.min_tissue_fraction = float(min_tissue_fraction)
67
+
68
+ def validate(self):
69
+ """No-op: backend is resolved per call from ctx['use_gpu']."""
70
+ self.ctx.require_key("use_gpu")
71
+
72
+ def __call__(self, it: Iterable[CollatedPatchBatch]) -> Iterable[CollatedPatchBatch]:
73
+ """
74
+ For each batch, compute Otsu mask, attach coverage stats, optionally filter, then yield.
75
+ """
76
+ use_gpu = bool(self.ctx["use_gpu"])
77
+ xp = get_xp_backend(use_gpu)
78
+
79
+ for collated_patch_batch in it:
80
+ in_sz = len(collated_patch_batch.patches)
81
+
82
+ patches = ensure_array_matches_use_gpu(collated_patch_batch.patches, use_gpu)
83
+
84
+ # 1) RGB/RGBA -> grayscale in [0,1]
85
+ gray = self._rgb_to_gray_xp(patches, xp)
86
+
87
+ # 2) Per-patch Otsu thresholds (in [0,1])
88
+ thresholds = self._batched_otsu_thresholds_xp(gray, self.num_bins, xp)
89
+
90
+ # 3) Tissue mask based on desired polarity
91
+ if self.tissue_is_darker:
92
+ tissue_mask = gray < thresholds[:, None, None]
93
+ else:
94
+ tissue_mask = gray >= thresholds[:, None, None]
95
+
96
+ # 4) Coverage stats per patch
97
+ B = tissue_mask.shape[0]
98
+ tissue_pixel_count = tissue_mask.reshape(B, -1).sum(axis=1)
99
+ total_pixels = tissue_mask.shape[1] * tissue_mask.shape[2]
100
+ tissue_fraction = tissue_pixel_count.astype(xp.float32) / float(total_pixels)
101
+
102
+ # Optional filtering
103
+ if self.min_tissue_fraction > 0.0:
104
+ keep_batch_mask = tissue_fraction >= self.min_tissue_fraction
105
+ else:
106
+ keep_batch_mask = xp.ones((B,), dtype=bool)
107
+
108
+ # Record stats + filter (convert to NumPy only at the boundary)
109
+ collated_patch_batch.add_meta_column("otsu_threshold", ensure_numpy(thresholds))
110
+ collated_patch_batch.add_meta_column("tissue_fraction", ensure_numpy(tissue_fraction))
111
+ collated_patch_batch.add_meta_column("tissue_pixel_count", ensure_numpy(tissue_pixel_count))
112
+ collated_patch_batch.filter_on_mask(ensure_numpy(keep_batch_mask))
113
+
114
+ self.log.info(
115
+ f"batch_in={in_sz} -> "
116
+ f"batch_out={len(collated_patch_batch.patches)} "
117
+ f"(tissue_is_darker={self.tissue_is_darker}, num_bins={self.num_bins}, "
118
+ f"float_precision={self.float_precision}, min_tissue_fraction={self.min_tissue_fraction})"
119
+ )
120
+ yield collated_patch_batch
121
+
122
+ # ---- helpers (xp-native) ----
123
+ def _rgb_to_gray_xp(self, imgs, xp):
124
+ """
125
+ Convert (B,H,W,C) to grayscale (B,H,W) in [0,1] using luminance weights.
126
+ Supports C=1 (already gray), C=3 (RGB), C=4 (RGBA → use first 3).
127
+ Output dtype honors `float_precision`.
128
+ """
129
+ if imgs.ndim != 4:
130
+ raise ValueError(f"Expected 4D (B,H,W,C); got {imgs.shape}")
131
+ C = imgs.shape[-1]
132
+ if C not in (1, 3, 4):
133
+ raise ValueError(f"Expected channels 1,3,4; got {C}")
134
+
135
+ prec = xp.float32 if self.float_precision == "float32" else xp.float64
136
+
137
+ if imgs.dtype == xp.uint8:
138
+ f = imgs.astype(prec, copy=False) / prec(255.0)
139
+ else:
140
+ # Accept float32/float64 (0..255) or other numeric types
141
+ f = imgs.astype(prec, copy=False)
142
+ f = xp.clip(f, prec(0.0), prec(255.0)) / prec(255.0)
143
+
144
+ if C == 1:
145
+ return f[..., 0]
146
+
147
+ rgb = f[..., :3]
148
+ # ITU-R BT.709-ish weights (close to skimage defaults)
149
+ coeffs = xp.asarray([0.2125, 0.7154, 0.0721], dtype=prec)
150
+ return (rgb * coeffs).sum(axis=-1, dtype=prec)
151
+
152
+ def _batched_otsu_thresholds_xp(self, gray, num_bins: int, xp):
153
+ """
154
+ Batched Otsu thresholds on grayscale images in [0,1].
155
+
156
+ Parameters
157
+ ----------
158
+ gray : (B,H,W) float32/float64
159
+ num_bins : int
160
+
161
+ Returns
162
+ -------
163
+ thresholds : (B,) same dtype as `gray`, each in [0,1] (gray domain)
164
+ """
165
+ B, _, _ = gray.shape
166
+ gray_flat = gray.reshape(B, -1)
167
+
168
+ # Per-image normalization to [0,1] (robust to constants)
169
+ g_min = gray_flat.min(axis=1)
170
+ g_max = gray_flat.max(axis=1)
171
+ is_constant = g_max <= g_min
172
+
173
+ eps = xp.asarray(1e-12, dtype=gray.dtype)
174
+ span = xp.maximum(g_max - g_min, eps)
175
+ gray_norm = (gray - g_min[:, None, None]) / span[:, None, None]
176
+ xp.clip(gray_norm, 0.0, 1.0, out=gray_norm)
177
+
178
+ # Quantize normalized gray into bins (ensure max maps into last bin)
179
+ tiny = xp.asarray(1e-7, dtype=gray.dtype)
180
+ bin_idx = xp.floor(gray_norm * num_bins - tiny).astype(xp.int32)
181
+ xp.clip(bin_idx, 0, num_bins - 1, out=bin_idx)
182
+
183
+ # Batched histograms via offset bincount
184
+ bin_idx_flat = bin_idx.reshape(B, -1).astype(xp.int64, copy=False)
185
+ offsets = (num_bins * xp.arange(B, dtype=xp.int64))[:, None]
186
+ keys = (bin_idx_flat + offsets).ravel()
187
+ counts_flat = xp.bincount(keys, minlength=B * num_bins)
188
+ hist = counts_flat.reshape(B, num_bins).astype(gray.dtype, copy=False)
189
+
190
+ # Bin centers in normalized space
191
+ centers = (xp.arange(num_bins, dtype=gray.dtype) + 0.5) / float(num_bins)
192
+
193
+ # Cumulative class weights/sums
194
+ w1 = xp.cumsum(hist, axis=1) # (B, num_bins)
195
+ total_w = w1[:, -1:] # (B, 1)
196
+ sum1 = xp.cumsum(hist * centers[None, :], axis=1)
197
+ total_sum = sum1[:, -1:]
198
+
199
+ w2 = total_w - w1
200
+ sum2 = total_sum - sum1
201
+
202
+ # Safe means (0 where class empty)
203
+ zero = xp.asarray(0, dtype=gray.dtype)
204
+ m1 = xp.where(w1 > 0, sum1 / xp.maximum(w1, 1), zero)
205
+ m2 = xp.where(w2 > 0, sum2 / xp.maximum(w2, 1), zero)
206
+
207
+ # Between-class variance for thresholds between bins
208
+ var_between = w1[:, :-1] * w2[:, 1:] * (m1[:, :-1] - m2[:, 1:]) ** 2
209
+
210
+ # Best threshold in normalized space, then map back to original gray domain
211
+ best_idx = xp.argmax(var_between, axis=1)
212
+ thr_norm = ((best_idx.astype(gray.dtype) + 0.5) / float(num_bins)).astype(gray.dtype)
213
+ thresholds = g_min.astype(gray.dtype) + thr_norm * span.astype(gray.dtype)
214
+
215
+ # For constant images, use the (degenerate) gray value
216
+ thresholds = xp.where(is_constant, g_min.astype(gray.dtype), thresholds)
217
+ return thresholds
@@ -0,0 +1,216 @@
1
+ from typing import Iterable, Sequence, Tuple
2
+
3
+ from wsi_patching.backends.cupy_numpy import ensure_numpy, get_xp_backend, validate_xp_backend
4
+ from wsi_patching.core.pipeline import Stage
5
+ from wsi_patching.core.types.types import CollatedPatchBatch
6
+
7
+
8
+ class PenArtifactFilter(Stage):
9
+ """
10
+ Pure-xp (NumPy/CuPy) pen artifact filter using bitset LUTs.
11
+
12
+ Assumptions:
13
+ - Input `patches` are uint8, or float32 scaled in [0, 255].
14
+ - If ctx['use_gpu'] is True, `patches` is a CuPy array; otherwise NumPy.
15
+ - All intermediate/results stay on the active xp backend; host conversion is done
16
+ only where the pipeline explicitly expects NumPy (via ensure_numpy).
17
+
18
+ Method:
19
+ - For each color "mode" (red/green/blue), build 3 LUTs (R/G/B). Each LUT (Lookup Table) cell
20
+ contains a bitmask where each bit represents one (r,g,b) threshold tuple.
21
+ - For a pixel, we OR the three channel lookups; if all bits are set (== full_mask),
22
+ the pixel *passes* that mode. A pixel is kept only if it passes all 3 modes,
23
+ or if it is very dark: (R+G+B) < 3*diff_thresh.
24
+ - A patch is dropped when its fraction of *pen* pixels (i.e., pixels not kept) exceeds
25
+ `max_pen_fraction`.
26
+ """
27
+
28
+ # Hard-coded threshold parameter sets (ported from original histolab logic)
29
+ _BLUE_PARAMS: Sequence[Tuple[int, int, int]] = [
30
+ (60, 120, 190),
31
+ (120, 170, 200),
32
+ (175, 210, 230),
33
+ (145, 180, 210),
34
+ (37, 95, 160),
35
+ (30, 65, 130),
36
+ (130, 155, 180),
37
+ (40, 35, 85),
38
+ (30, 20, 65),
39
+ (90, 90, 140),
40
+ (60, 60, 120),
41
+ (110, 110, 175),
42
+ ]
43
+ _GREEN_PARAMS: Sequence[Tuple[int, int, int]] = [
44
+ (150, 160, 140),
45
+ (70, 110, 110),
46
+ (45, 115, 100),
47
+ (30, 75, 60),
48
+ (195, 220, 210),
49
+ (225, 230, 225),
50
+ (170, 210, 200),
51
+ (20, 30, 20),
52
+ (50, 60, 40),
53
+ (30, 50, 35),
54
+ (65, 70, 60),
55
+ (100, 110, 105),
56
+ (165, 180, 180),
57
+ (140, 140, 150),
58
+ (185, 195, 195),
59
+ ]
60
+ _RED_PARAMS: Sequence[Tuple[int, int, int]] = [
61
+ (150, 80, 90),
62
+ (110, 20, 30),
63
+ (185, 65, 105),
64
+ (195, 85, 125),
65
+ (220, 115, 145),
66
+ (125, 40, 70),
67
+ (100, 50, 65),
68
+ (85, 25, 45),
69
+ ]
70
+
71
+ def __init__(self, diff_thresh: float = 5.0, max_pen_fraction: float = 0.01):
72
+ # Darkness guard and batch-level drop threshold
73
+ self.diff_thresh = float(diff_thresh)
74
+ self.max_pen_fraction = float(max_pen_fraction)
75
+
76
+ # Mode-specific LUTs
77
+ self._luts_red = None
78
+ self._luts_green = None
79
+ self._luts_blue = None
80
+
81
+ def validate(self):
82
+ """Resolve backend (NumPy/CuPy) and build LUTs once on that backend."""
83
+ self.ctx.require_key("use_gpu")
84
+ use_gpu = bool(self.ctx["use_gpu"])
85
+ if use_gpu:
86
+ # Fail fast if GPU path requested but CuPy unavailable
87
+ validate_xp_backend(True)
88
+
89
+ self._build_all_luts_xp(get_xp_backend(self.ctx["use_gpu"]))
90
+
91
+ def __call__(self, it: Iterable[CollatedPatchBatch]) -> Iterable[CollatedPatchBatch]:
92
+ """
93
+ For each batch:
94
+ - Ensure dtype uint8 (accept float32 in [0,255] and cast).
95
+ - Compute per-pixel keep mask from LUTs + darkness guard.
96
+ - Derive per-patch pen_fraction; drop patches exceeding `max_pen_fraction`.
97
+ - Attach stats and yield the filtered batch.
98
+ """
99
+ use_gpu = bool(self.ctx["use_gpu"])
100
+ xp = get_xp_backend(use_gpu)
101
+ thr3 = xp.float32(3.0 * self.diff_thresh)
102
+
103
+ for collated_patch_batch in it:
104
+ in_sz = len(collated_patch_batch.patches)
105
+
106
+ # Normalize dtype: prefer uint8 for LUT indexing
107
+ if collated_patch_batch.patches.dtype != xp.uint8:
108
+ collated_patch_batch.patches = collated_patch_batch.patches.astype(xp.uint8, copy=False)
109
+
110
+ # Split channels; shapes: [B,H,W]
111
+ R = collated_patch_batch.patches[..., 0]
112
+ G = collated_patch_batch.patches[..., 1]
113
+ B = collated_patch_batch.patches[..., 2]
114
+
115
+ # A pixel is kept if it passes all three modes
116
+ keep = (
117
+ self._mode_pass_xp(R, G, B, self._luts_red)
118
+ & self._mode_pass_xp(R, G, B, self._luts_green)
119
+ & self._mode_pass_xp(R, G, B, self._luts_blue)
120
+ )
121
+
122
+ # Darkness guard: keep very dark pixels even if they fail LUTs
123
+ sum_rgb = (R.astype(xp.uint16) + G.astype(xp.uint16) + B.astype(xp.uint16)).astype(xp.float32)
124
+ keep_final = xp.where(keep, True, sum_rgb < thr3)
125
+
126
+ # Pen mask is the inverse of keep_final
127
+ pen = xp.logical_not(keep_final) # [B,H,W] bool
128
+
129
+ # Per-patch stats
130
+ Bsz = pen.shape[0]
131
+ pen_pixel_count = pen.reshape(Bsz, -1).sum(axis=1) # xp integer (per patch)
132
+ total_pixels = pen.shape[1] * pen.shape[2]
133
+ pen_fraction = pen_pixel_count.astype(xp.float32) / float(total_pixels)
134
+
135
+ # Drop patches with too much pen content
136
+ keep_batch_mask = pen_fraction <= self.max_pen_fraction
137
+
138
+ # Pipeline columns expect NumPy; convert explicitly at the boundary.
139
+ collated_patch_batch.add_meta_column("pen_fraction", ensure_numpy(pen_fraction))
140
+ collated_patch_batch.add_meta_column("pen_pixel_count", ensure_numpy(pen_pixel_count))
141
+ collated_patch_batch.filter_on_mask(ensure_numpy(keep_batch_mask))
142
+
143
+ self.log.info(
144
+ f"batch_in={in_sz} batch_out={len(collated_patch_batch.patches)} "
145
+ f"(max_pen_fraction={self.max_pen_fraction})"
146
+ )
147
+ yield collated_patch_batch
148
+
149
+ # -------- helpers (xp-native) --------
150
+ def _build_all_luts_xp(self, xp):
151
+ """Build LUT triplets for each mode directly on the active xp backend."""
152
+ self._luts_red = self._build_mode_luts_xp(self._RED_PARAMS, "red", xp)
153
+ self._luts_green = self._build_mode_luts_xp(self._GREEN_PARAMS, "green", xp)
154
+ self._luts_blue = self._build_mode_luts_xp(self._BLUE_PARAMS, "blue", xp)
155
+
156
+ @staticmethod
157
+ def _build_mode_luts_xp(params: Sequence[Tuple[int, int, int]], mode: str, xp):
158
+ """
159
+ Build per-channel LUTs for a mode as bitsets:
160
+ - Each LUT is length-256 (one entry per 8-bit channel value).
161
+ - Each bit in the uint32 entry corresponds to one (r,g,b) threshold tuple.
162
+ - For a pixel/channel value, set a bit if the tuple’s condition is met.
163
+ """
164
+ P = len(params)
165
+ if P > 32:
166
+ raise ValueError(f"Bitset LUT supports up to 32 params per mode (got {P}).")
167
+
168
+ full_mask = xp.uint32((1 << P) - 1) # mask with all P bits set
169
+ lutR = xp.zeros(256, dtype=xp.uint32)
170
+ lutG = xp.zeros(256, dtype=xp.uint32)
171
+ lutB = xp.zeros(256, dtype=xp.uint32)
172
+
173
+ for i, (r, g, b) in enumerate(params):
174
+ bit = xp.uint32(1 << i)
175
+
176
+ # Set bits for *ranges* that satisfy the tuple condition on each channel.
177
+ # See histolab logic: "red", "green", and "blue" modes differ by which side
178
+ # of the threshold is considered passing for each channel.
179
+ if mode == "red":
180
+ if r > 0:
181
+ lutR[:r] |= bit # R < r => pass this tuple
182
+ if g < 255:
183
+ lutG[g + 1 :] |= bit # G > g => pass
184
+ if b < 255:
185
+ lutB[b + 1 :] |= bit # B > b => pass
186
+ elif mode == "green":
187
+ if r < 255:
188
+ lutR[r + 1 :] |= bit # R > r
189
+ if g > 0:
190
+ lutG[:g] |= bit # G < g
191
+ if b > 0:
192
+ lutB[:b] |= bit # B < b
193
+ elif mode == "blue":
194
+ if r < 255:
195
+ lutR[r + 1 :] |= bit # R > r
196
+ if g < 255:
197
+ lutG[g + 1 :] |= bit # G > g
198
+ if b > 0:
199
+ lutB[:b] |= bit # B < b
200
+ else:
201
+ raise ValueError(mode)
202
+
203
+ return (lutR, lutG, lutB, full_mask)
204
+
205
+ @staticmethod
206
+ def _mode_pass_xp(R, G, B, luts):
207
+ """
208
+ For a given mode, return a boolean mask where each pixel passes that mode.
209
+ Implementation:
210
+ - Gather bitsets from LUTs for the pixel's R/G/B values.
211
+ - OR the three bitsets; a bit is set if any channel satisfies that tuple.
212
+ - Pixel passes the mode if *all* bits are set (i.e., equals full_mask).
213
+ """
214
+ lutR, lutG, lutB, full_mask = luts
215
+ m = lutR[R] | lutG[G] | lutB[B]
216
+ return m == full_mask
wsi_patching/py.typed ADDED
File without changes
@@ -0,0 +1,4 @@
1
+ from .attach_rois import AttachROIs
2
+ from .roi_providers import RectROIfromXMLProvider, RectROIProvider, WholeSlideProvider
3
+
4
+ __all__ = ["AttachROIs", "RectROIProvider", "RectROIfromXMLProvider", "WholeSlideProvider"]
@@ -0,0 +1,59 @@
1
+ from typing import Iterable, List, Literal
2
+
3
+ from wsi_patching.core.pipeline import Stage
4
+ from wsi_patching.core.types.types import Slide, SlideWithROIs
5
+ from wsi_patching.regions_of_interest.roi_providers import ROIProvider, WholeSlideProvider
6
+
7
+
8
+ class AttachROIs(Stage):
9
+ """Add Regions of Interest (ROIs) to each slide using one or more ROI providers."""
10
+
11
+ def __init__(self, providers: List[ROIProvider], on_empty: Literal["error", "whole_slide"] = "error") -> None:
12
+ """
13
+ Args:
14
+ providers: List of ROIProvider instances to use for obtaining ROIs.
15
+ on_empty: Behavior when no ROIs are found for a slide. Default is "error".
16
+ Options:
17
+ - "error": raise an error.
18
+ - "whole_slide": use the whole slide as a single ROI.
19
+ """
20
+ self.providers = list(providers)
21
+ self.on_empty = on_empty
22
+
23
+ if self.on_empty not in ("error", "whole_slide"):
24
+ raise ValueError("on_empty must be 'error' or 'whole_slide'")
25
+
26
+ def __call__(self, it: Iterable[Slide]) -> Iterable[SlideWithROIs]:
27
+ for s in it:
28
+ all_rois = []
29
+ provider_errors: List[Exception] = []
30
+
31
+ for prov in self.providers:
32
+ try:
33
+ slide_rois = prov.for_slide(s)
34
+ all_rois.extend(slide_rois)
35
+ self.log.info(f"{type(prov).__name__} found {len(slide_rois)} ROIs for slide {s.wsi_id}")
36
+ except Exception as e:
37
+ provider_errors.append(e)
38
+ self.log.error(f"{type(prov).__name__} failed: {e}")
39
+
40
+ if not all_rois:
41
+ if self.on_empty == "error":
42
+ # If all providers failed, raise the real underlying exception(s)
43
+ if len(provider_errors) == 1:
44
+ raise provider_errors[0]
45
+ if len(provider_errors) > 1:
46
+ msg = (
47
+ f"No valid ROIs found for slide {s.wsi_id}; "
48
+ f"{len(provider_errors)} provider(s) failed: "
49
+ + "; ".join(f"{type(e).__name__}: {e}" for e in provider_errors)
50
+ )
51
+ raise ValueError(msg) from provider_errors[0]
52
+
53
+ # No providers failed, they just returned empty
54
+ raise ValueError(f"No valid ROIs found for slide {s.wsi_id}")
55
+
56
+ all_rois = WholeSlideProvider().for_slide(s)
57
+ self.log.warning(f"No valid ROIs found for slide {s.wsi_id}; using whole slide.")
58
+
59
+ yield SlideWithROIs(**s.__dict__, rois=all_rois)