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.
- wsi_patching/__init__.py +38 -0
- wsi_patching/annotations/__init__.py +3 -0
- wsi_patching/annotations/add_cell_annotation_from_csv.py +152 -0
- wsi_patching/assets/models/cellvit_tissue_detector.pt +0 -0
- wsi_patching/backends/__init__.py +0 -0
- wsi_patching/backends/cupy_numpy.py +80 -0
- wsi_patching/backends/fastslide.py +243 -0
- wsi_patching/backends/torch_device.py +45 -0
- wsi_patching/core/__init__.py +4 -0
- wsi_patching/core/chunking_and_batching.py +519 -0
- wsi_patching/core/pipeline.py +566 -0
- wsi_patching/core/types/__init__.py +0 -0
- wsi_patching/core/types/types.py +145 -0
- wsi_patching/core/types/util_types.py +93 -0
- wsi_patching/core/wsi_grid.py +119 -0
- wsi_patching/custom_component/__init__.py +18 -0
- wsi_patching/encoders/__init__.py +3 -0
- wsi_patching/encoders/pngencoder.py +72 -0
- wsi_patching/filtering/__init__.py +15 -0
- wsi_patching/filtering/cellvit_tissue_classifier_filter.py +124 -0
- wsi_patching/filtering/low_contrast_background_filter.py +125 -0
- wsi_patching/filtering/otsu_filter.py +217 -0
- wsi_patching/filtering/pen_artifact_filter.py +216 -0
- wsi_patching/py.typed +0 -0
- wsi_patching/regions_of_interest/__init__.py +4 -0
- wsi_patching/regions_of_interest/attach_rois.py +59 -0
- wsi_patching/regions_of_interest/roi_providers.py +94 -0
- wsi_patching/regions_of_interest/rois.py +78 -0
- wsi_patching/transforms/__init__.py +4 -0
- wsi_patching/transforms/macenko_normalizer.py +175 -0
- wsi_patching/transforms/reinhard_normalizer.py +271 -0
- wsi_patching/utils/__init__.py +3 -0
- wsi_patching/utils/logging_config.py +13 -0
- wsi_patching/utils/meta_typing.py +94 -0
- wsi_patching/utils/profiling.py +115 -0
- wsi_patching/utils/wsi_thumbnail_visualization.py +208 -0
- wsi_patching/writers/__init__.py +10 -0
- wsi_patching/writers/materialize_writers/__init__.py +0 -0
- wsi_patching/writers/materialize_writers/materialize_writer_base.py +92 -0
- wsi_patching/writers/materialize_writers/webdataset/__init__.py +0 -0
- wsi_patching/writers/materialize_writers/webdataset/webdataset_loader.py +165 -0
- wsi_patching/writers/materialize_writers/webdataset/webdataset_writer.py +69 -0
- wsi_patching/writers/stream_writers/__init__.py +0 -0
- wsi_patching/writers/stream_writers/numpy_stream_writer.py +36 -0
- wsi_patching/writers/stream_writers/stream_writer_base.py +71 -0
- wsi_patching/writers/stream_writers/torch_stream_writer.py +67 -0
- wsi_patching-0.5.0.dist-info/METADATA +249 -0
- wsi_patching-0.5.0.dist-info/RECORD +50 -0
- wsi_patching-0.5.0.dist-info/WHEEL +4 -0
- wsi_patching-0.5.0.dist-info/licenses/LICENSE +21 -0
wsi_patching/__init__.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
# src/wsi_patching/__init__.py
|
|
2
|
+
from importlib.metadata import version as _version
|
|
3
|
+
|
|
4
|
+
from .core import PatchExtractor, ReadWindowChunker, RegionReadAndBatch, TilePlanner, WSIGrid
|
|
5
|
+
from .encoders import PNGEncoder
|
|
6
|
+
from .filtering import LowContrastBackgroundFilter, OtsuFilter, PenArtifactFilter
|
|
7
|
+
from .regions_of_interest import AttachROIs, RectROIfromXMLProvider, RectROIProvider, WholeSlideProvider
|
|
8
|
+
from .writers import NumpyStreamWriter, TorchStreamWriter, WebDatasetWriter
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
# Core pipeline
|
|
12
|
+
"WSIGrid",
|
|
13
|
+
"TilePlanner",
|
|
14
|
+
"PatchExtractor",
|
|
15
|
+
"ReadWindowChunker",
|
|
16
|
+
"RegionReadAndBatch",
|
|
17
|
+
# Regions of interest
|
|
18
|
+
"AttachROIs",
|
|
19
|
+
"RectROIProvider",
|
|
20
|
+
"RectROIfromXMLProvider",
|
|
21
|
+
"WholeSlideProvider",
|
|
22
|
+
# Encoders
|
|
23
|
+
"PNGEncoder",
|
|
24
|
+
# Filters
|
|
25
|
+
"LowContrastBackgroundFilter",
|
|
26
|
+
"OtsuFilter",
|
|
27
|
+
"PenArtifactFilter",
|
|
28
|
+
# Writers
|
|
29
|
+
"NumpyStreamWriter",
|
|
30
|
+
"WebDatasetWriter",
|
|
31
|
+
"TorchStreamWriter",
|
|
32
|
+
]
|
|
33
|
+
|
|
34
|
+
# version (from your installed package metadata)
|
|
35
|
+
try:
|
|
36
|
+
__version__ = _version("wsi_patching")
|
|
37
|
+
except Exception: # during editable installs before metadata exists
|
|
38
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import csv
|
|
2
|
+
from itertools import chain
|
|
3
|
+
from typing import Dict, Iterable, List, Optional, Tuple
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
from rtree import index
|
|
7
|
+
|
|
8
|
+
from wsi_patching.core.pipeline import Stage
|
|
9
|
+
from wsi_patching.core.types.types import CollatedPatchBatch
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class AddCellAnnotationFromCSV(Stage):
|
|
13
|
+
"""
|
|
14
|
+
Same behavior as your class, but without pandas.
|
|
15
|
+
CSV is read with csv.DictReader -> NumPy arrays (x, y, label).
|
|
16
|
+
R-tree is bulk-loaded once per WSI. Queries use pure NumPy masks.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
def __init__(
|
|
20
|
+
self,
|
|
21
|
+
wsi_to_csv_mapping: Dict[str, str],
|
|
22
|
+
x_col: str = "x",
|
|
23
|
+
y_col: str = "y",
|
|
24
|
+
label_col: str = "label",
|
|
25
|
+
filter_empty: bool = False,
|
|
26
|
+
):
|
|
27
|
+
self.wsi_to_csv_mapping = wsi_to_csv_mapping
|
|
28
|
+
self.x_col = x_col
|
|
29
|
+
self.y_col = y_col
|
|
30
|
+
self.label_col = label_col
|
|
31
|
+
self.filter_empty = filter_empty
|
|
32
|
+
|
|
33
|
+
# caches for the currently loaded WSI
|
|
34
|
+
self._x: Optional[np.ndarray] = None # shape (N,), float or int
|
|
35
|
+
self._y: Optional[np.ndarray] = None # shape (N,), float or int
|
|
36
|
+
self._label: Optional[np.ndarray] = None # shape (N,), dtype=object or numeric
|
|
37
|
+
self._rtree: Optional[index.Index] = None
|
|
38
|
+
|
|
39
|
+
def validate(self) -> None:
|
|
40
|
+
self.ctx.require_key("tile_size")
|
|
41
|
+
self.ctx.require_key("use_gpu")
|
|
42
|
+
|
|
43
|
+
def __call__(self, it: Iterable[CollatedPatchBatch]) -> Iterable[CollatedPatchBatch]:
|
|
44
|
+
it = iter(it)
|
|
45
|
+
try:
|
|
46
|
+
first: CollatedPatchBatch = next(it)
|
|
47
|
+
except StopIteration:
|
|
48
|
+
return
|
|
49
|
+
|
|
50
|
+
# Ensure the right slide is loaded
|
|
51
|
+
self._ensure_loaded(first.wsi_id)
|
|
52
|
+
it = chain([first], it)
|
|
53
|
+
|
|
54
|
+
x_arr, y_arr, lbl_arr, rtx = self._x, self._y, self._label, self._rtree
|
|
55
|
+
assert x_arr is not None and y_arr is not None and lbl_arr is not None and rtx is not None
|
|
56
|
+
|
|
57
|
+
tile_size: int = int(self.ctx["tile_size"])
|
|
58
|
+
EMPTY = np.empty((0, 3))
|
|
59
|
+
|
|
60
|
+
for batch in it:
|
|
61
|
+
all_annotations: List[np.ndarray] = []
|
|
62
|
+
|
|
63
|
+
# batch.coords is (N, 2) -> (x0,y0) top-left
|
|
64
|
+
for x0, y0 in batch.coords:
|
|
65
|
+
x1 = x0 + tile_size
|
|
66
|
+
y1 = y0 + tile_size
|
|
67
|
+
|
|
68
|
+
# R-tree returns candidate integer ids
|
|
69
|
+
cand_ids = list(rtx.intersection((x0, y0, x1, y1)))
|
|
70
|
+
|
|
71
|
+
if cand_ids:
|
|
72
|
+
# Use NumPy indexing & boolean mask (strict left-inclusive bounds like your code)
|
|
73
|
+
idx = np.fromiter(cand_ids, dtype=np.int64, count=len(cand_ids))
|
|
74
|
+
xs = x_arr[idx]
|
|
75
|
+
ys = y_arr[idx]
|
|
76
|
+
|
|
77
|
+
inside = (xs >= x0) & (xs < x1) & (ys >= y0) & (ys < y1)
|
|
78
|
+
if inside.any():
|
|
79
|
+
sel = idx[inside]
|
|
80
|
+
# Pack (k,3) object as before: (x, y, label)
|
|
81
|
+
k = sel.size
|
|
82
|
+
packed = np.empty((k, 3), dtype=np.int32)
|
|
83
|
+
packed[:, 0] = x_arr[sel] - x0
|
|
84
|
+
packed[:, 1] = y_arr[sel] - y0
|
|
85
|
+
packed[:, 2] = lbl_arr[sel]
|
|
86
|
+
all_annotations.append(packed)
|
|
87
|
+
continue
|
|
88
|
+
|
|
89
|
+
all_annotations.append(EMPTY)
|
|
90
|
+
|
|
91
|
+
batch.add_meta_column("annotations", all_annotations)
|
|
92
|
+
|
|
93
|
+
if self.filter_empty:
|
|
94
|
+
mask = np.array([a.shape[0] != 0 for a in all_annotations], dtype=bool)
|
|
95
|
+
batch.filter_on_mask(mask)
|
|
96
|
+
|
|
97
|
+
if len(batch.patches) > 0:
|
|
98
|
+
yield batch
|
|
99
|
+
|
|
100
|
+
def _ensure_loaded(self, wsi_id: str) -> None:
|
|
101
|
+
if wsi_id not in self.wsi_to_csv_mapping:
|
|
102
|
+
raise KeyError(f"No CSV file provided for WSI '{wsi_id}'")
|
|
103
|
+
csv_path = self.wsi_to_csv_mapping[wsi_id]
|
|
104
|
+
self._x, self._y, self._label = self._read_csv_to_arrays(csv_path, self.x_col, self.y_col, self.label_col)
|
|
105
|
+
self._rtree = self._build_rtree(self._x, self._y)
|
|
106
|
+
|
|
107
|
+
@staticmethod
|
|
108
|
+
def _read_csv_to_arrays(
|
|
109
|
+
csv_path: str, x_col: str, y_col: str, label_col: str
|
|
110
|
+
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
|
|
111
|
+
"""
|
|
112
|
+
Lightweight CSV to NumPy arrays. Works with numeric x/y and arbitrary label types (string/int).
|
|
113
|
+
For ~50k rows this is fast and avoids pandas allocations entirely.
|
|
114
|
+
"""
|
|
115
|
+
xs: List[float] = []
|
|
116
|
+
ys: List[float] = []
|
|
117
|
+
labels: List[object] = []
|
|
118
|
+
|
|
119
|
+
with open(csv_path, "r", newline="") as f:
|
|
120
|
+
reader = csv.DictReader(f)
|
|
121
|
+
# Basic validation
|
|
122
|
+
if reader.fieldnames is None:
|
|
123
|
+
raise ValueError(f"CSV {csv_path} has no header row")
|
|
124
|
+
missing = {c for c in (x_col, y_col, label_col) if c not in reader.fieldnames}
|
|
125
|
+
if missing:
|
|
126
|
+
raise ValueError(f"CSV {csv_path} missing required column(s): {', '.join(sorted(missing))}")
|
|
127
|
+
|
|
128
|
+
for row in reader:
|
|
129
|
+
# Cast x/y as float (or int if you prefer). Keep label as object/string
|
|
130
|
+
xs.append(float(row[x_col]))
|
|
131
|
+
ys.append(float(row[y_col]))
|
|
132
|
+
labels.append(row[label_col])
|
|
133
|
+
|
|
134
|
+
x_arr = np.asarray(xs, dtype=np.uint32)
|
|
135
|
+
y_arr = np.asarray(ys, dtype=np.uint32)
|
|
136
|
+
label_arr = np.asarray(labels, dtype=np.int64)
|
|
137
|
+
|
|
138
|
+
return x_arr, y_arr, label_arr
|
|
139
|
+
|
|
140
|
+
@staticmethod
|
|
141
|
+
def _build_rtree(x_arr: np.ndarray, y_arr: np.ndarray) -> index.Index:
|
|
142
|
+
"""
|
|
143
|
+
Bulk build R-tree: much faster than calling insert() in a loop.
|
|
144
|
+
"""
|
|
145
|
+
props = index.Property()
|
|
146
|
+
props.dimension = 2
|
|
147
|
+
|
|
148
|
+
# items format: (id, (xmin, ymin, xmax, ymax), obj)
|
|
149
|
+
# We store points as zero-area rectangles (x, y, x, y). obj=None to keep it minimal.
|
|
150
|
+
n = x_arr.shape[0]
|
|
151
|
+
items = ((i, (x_arr[i], y_arr[i], x_arr[i], y_arr[i]), None) for i in range(n))
|
|
152
|
+
return index.Index(items, properties=props)
|
|
Binary file
|
|
File without changes
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import TYPE_CHECKING, Union
|
|
4
|
+
|
|
5
|
+
try:
|
|
6
|
+
import cupy as cp
|
|
7
|
+
|
|
8
|
+
_cupy_available = True
|
|
9
|
+
except ImportError:
|
|
10
|
+
_cupy_available = False
|
|
11
|
+
|
|
12
|
+
if TYPE_CHECKING:
|
|
13
|
+
import torch
|
|
14
|
+
|
|
15
|
+
import numpy as np
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def validate_xp_backend(use_gpu: bool) -> None:
|
|
19
|
+
if use_gpu and not _cupy_available:
|
|
20
|
+
raise ImportError("CuPy is not available. Please install CuPy to use GPU backend.")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def ensure_numpy(arr: Union[np.ndarray, "cp.ndarray"]) -> np.ndarray:
|
|
24
|
+
"""Ensure the input array is a NumPy ndarray. If it's a CuPy array, convert it to NumPy."""
|
|
25
|
+
if _cupy_available and isinstance(arr, cp.ndarray):
|
|
26
|
+
return arr.get()
|
|
27
|
+
elif isinstance(arr, np.ndarray):
|
|
28
|
+
return arr
|
|
29
|
+
else:
|
|
30
|
+
raise TypeError(f"Input must be a numpy.ndarray or cupy.ndarray, got {type(arr)}")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def ensure_cupy(arr: Union[np.ndarray, "cp.ndarray"]) -> "cp.ndarray":
|
|
34
|
+
"""Ensure the input array is a CuPy ndarray. If it's a NumPy array, convert it to CuPy."""
|
|
35
|
+
if not _cupy_available:
|
|
36
|
+
raise ImportError("CuPy is not available. Please install CuPy to use this function.")
|
|
37
|
+
if isinstance(arr, np.ndarray):
|
|
38
|
+
return cp.asarray(arr)
|
|
39
|
+
elif isinstance(arr, cp.ndarray):
|
|
40
|
+
return arr
|
|
41
|
+
else:
|
|
42
|
+
raise TypeError(f"Input must be a numpy.ndarray or cupy.ndarray, got {type(arr)}")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def is_cupy(arr: object) -> bool:
|
|
46
|
+
"""Check if the given array is a CuPy ndarray."""
|
|
47
|
+
return _cupy_available and isinstance(arr, cp.ndarray)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def ensure_array_matches_use_gpu(
|
|
51
|
+
arr: Union[np.ndarray, "cp.ndarray"], use_gpu: bool
|
|
52
|
+
) -> Union[np.ndarray, "cp.ndarray"]:
|
|
53
|
+
"""Ensure that the array type matches the use_gpu flag. Convert if necessary."""
|
|
54
|
+
if use_gpu:
|
|
55
|
+
return ensure_cupy(arr)
|
|
56
|
+
else:
|
|
57
|
+
return ensure_numpy(arr)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def get_xp_backend(use_gpu: bool):
|
|
61
|
+
"""Return either numpy or cupy to use as 'xp.asarray', etc."""
|
|
62
|
+
if use_gpu:
|
|
63
|
+
if not _cupy_available:
|
|
64
|
+
raise ImportError("CuPy is not available. Please install CuPy to use GPU backend.")
|
|
65
|
+
return cp
|
|
66
|
+
else:
|
|
67
|
+
return np
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def xp_from_tensor(t: torch.Tensor, use_gpu: bool):
|
|
71
|
+
"""Convert a Torch tensor to either a NumPy or CuPy array, depending on use_gpu."""
|
|
72
|
+
try:
|
|
73
|
+
import torch # noqa: F401
|
|
74
|
+
except ImportError:
|
|
75
|
+
raise ImportError("torch is required to use xp_from_tensor. Install it with: pip install wsi-patching[gpu]")
|
|
76
|
+
detached = t.detach()
|
|
77
|
+
if use_gpu:
|
|
78
|
+
return cp.from_dlpack(detached)
|
|
79
|
+
else:
|
|
80
|
+
return detached.cpu().numpy()
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import threading
|
|
3
|
+
from contextlib import contextmanager
|
|
4
|
+
from typing import List, Literal, Tuple
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
from fastslide import FastSlide
|
|
8
|
+
|
|
9
|
+
logger = logging.getLogger(__name__)
|
|
10
|
+
|
|
11
|
+
_thread_local = threading.local()
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _new_slide(path: str) -> FastSlide:
|
|
15
|
+
return FastSlide.from_file_path(str(path))
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@contextmanager
|
|
19
|
+
def _open_slide(path: str):
|
|
20
|
+
slide = _new_slide(path)
|
|
21
|
+
try:
|
|
22
|
+
yield slide
|
|
23
|
+
finally:
|
|
24
|
+
if hasattr(slide, "close"):
|
|
25
|
+
slide.close()
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _get_cached_slide(path: str):
|
|
29
|
+
"""Return a cached open FastSlide handle for the current thread."""
|
|
30
|
+
cache = getattr(_thread_local, "slide_cache", None)
|
|
31
|
+
if cache is None:
|
|
32
|
+
_thread_local.slide_cache = {}
|
|
33
|
+
cache = _thread_local.slide_cache
|
|
34
|
+
if path not in cache:
|
|
35
|
+
cache[path] = _new_slide(path)
|
|
36
|
+
return cache[path]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def close_cached_slides() -> None:
|
|
40
|
+
"""Close and evict all cached slide handles for the current thread.
|
|
41
|
+
|
|
42
|
+
Must be called by the producer thread after finishing a slide to prevent
|
|
43
|
+
resource leaks. Safe to call even if no slides are cached.
|
|
44
|
+
"""
|
|
45
|
+
cache = getattr(_thread_local, "slide_cache", {})
|
|
46
|
+
for path, slide in list(cache.items()):
|
|
47
|
+
try:
|
|
48
|
+
if hasattr(slide, "close"):
|
|
49
|
+
slide.close()
|
|
50
|
+
except Exception:
|
|
51
|
+
logger.warning("Failed to close cached slide for path %s", path)
|
|
52
|
+
_thread_local.slide_cache = {}
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _get_mpp0(slide) -> float:
|
|
56
|
+
mpp = getattr(slide, "mpp", None)
|
|
57
|
+
if mpp is not None and mpp[0] is not None:
|
|
58
|
+
return float(mpp[0])
|
|
59
|
+
|
|
60
|
+
properties = getattr(slide, "properties", None)
|
|
61
|
+
if properties is not None:
|
|
62
|
+
mpp_x = properties.get("openslide.mpp-x")
|
|
63
|
+
if mpp_x is not None:
|
|
64
|
+
return float(mpp_x)
|
|
65
|
+
|
|
66
|
+
raise ValueError("Could not retrieve mpp metadata from slide.mpp or openslide.mpp-x property.")
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def read_region(path: str, x: int, y: int, w: int, h: int, level: int) -> np.ndarray:
|
|
70
|
+
"""
|
|
71
|
+
Return the requested region at the given pyramid level as a NumPy array.
|
|
72
|
+
|
|
73
|
+
Args:
|
|
74
|
+
path: Path to the WSI file.
|
|
75
|
+
x: Left edge of the region in level-0 coordinates.
|
|
76
|
+
y: Top edge of the region in level-0 coordinates.
|
|
77
|
+
w: Width of the region in pixels at the requested level.
|
|
78
|
+
h: Height of the region in pixels at the requested level.
|
|
79
|
+
level: Pyramid level to read from.
|
|
80
|
+
|
|
81
|
+
Returns:
|
|
82
|
+
NumPy array of shape (h, w, 3), dtype uint8.
|
|
83
|
+
"""
|
|
84
|
+
slide = _get_cached_slide(path)
|
|
85
|
+
x_native, y_native = slide.convert_level0_to_level_native(x, y, level)
|
|
86
|
+
region = slide.read_region((x_native, y_native), level, (w, h))
|
|
87
|
+
return np.asarray(region.numpy())
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def get_dimensions_for_level(path: str, level: int) -> Tuple[int, int]:
|
|
91
|
+
"""
|
|
92
|
+
Returns:
|
|
93
|
+
W: int
|
|
94
|
+
H: int
|
|
95
|
+
"""
|
|
96
|
+
with _open_slide(path) as slide:
|
|
97
|
+
assert 0 <= level < slide.level_count, f"Level {level} exceeds maximum level {slide.level_count - 1}."
|
|
98
|
+
W, H = slide.level_dimensions[level]
|
|
99
|
+
return int(W), int(H)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def get_level_downsamples(path: str) -> List[float]:
|
|
103
|
+
"""Return the list of downsample factors relative to level 0 for each pyramid level."""
|
|
104
|
+
with _open_slide(path) as slide:
|
|
105
|
+
return [float(ds) for ds in slide.level_downsamples]
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def get_resample_factor(path: str, resolution: float, unit: Literal["mpp", "downsample"], selected_level: int) -> float:
|
|
109
|
+
"""Return resample_factor = requested_value / level_value.
|
|
110
|
+
|
|
111
|
+
Factor > 1.0 means the selected level is finer than requested: read more
|
|
112
|
+
level pixels, then scale down to the requested size.
|
|
113
|
+
|
|
114
|
+
Args:
|
|
115
|
+
path: Path to the WSI file.
|
|
116
|
+
resolution: Requested resolution value (mpp or downsample).
|
|
117
|
+
unit: "mpp" or "downsample".
|
|
118
|
+
selected_level: The pyramid level that was selected for resampling.
|
|
119
|
+
|
|
120
|
+
Returns:
|
|
121
|
+
resample_factor (float > 0); equals 1.0 when level is an exact match.
|
|
122
|
+
"""
|
|
123
|
+
with _open_slide(path) as slide:
|
|
124
|
+
level_downsamples = [float(ds) for ds in slide.level_downsamples]
|
|
125
|
+
level_ds = level_downsamples[selected_level]
|
|
126
|
+
|
|
127
|
+
if unit == "mpp":
|
|
128
|
+
mpp0 = _get_mpp0(slide)
|
|
129
|
+
level_value = mpp0 * level_ds
|
|
130
|
+
elif unit == "downsample":
|
|
131
|
+
level_value = level_ds
|
|
132
|
+
else:
|
|
133
|
+
raise ValueError(f"Unknown unit: {unit}")
|
|
134
|
+
|
|
135
|
+
return float(resolution) if level_value == 0 else float(resolution) / level_value
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def get_level_for_resolution(
|
|
139
|
+
path: str,
|
|
140
|
+
resolution: float,
|
|
141
|
+
unit: Literal["level", "mpp", "downsample"],
|
|
142
|
+
fallback_mode: Literal["nearest", "floor", "ceil", "error", "resample"],
|
|
143
|
+
) -> int:
|
|
144
|
+
"""
|
|
145
|
+
Determine which pyramid level to use for a given resolution specification.
|
|
146
|
+
|
|
147
|
+
Args:
|
|
148
|
+
path: Path to the WSI.
|
|
149
|
+
resolution: Requested resolution value.
|
|
150
|
+
- If unit == "level": pyramid level index (0, 1, 2, ...)
|
|
151
|
+
- If unit == "mpp": microns per pixel.
|
|
152
|
+
- If unit == "downsample": Downsample factor relative to level 0.
|
|
153
|
+
unit: Resolution unit ("level", "mpp", or "downsample").
|
|
154
|
+
fallback_mode:
|
|
155
|
+
- "nearest": pick level whose value is closest to 'resolution'.
|
|
156
|
+
- "floor": pick coarsest level with value >= 'resolution'
|
|
157
|
+
(if none, use coarsest level).
|
|
158
|
+
- "ceil": pick finest level with value <= 'resolution'
|
|
159
|
+
(if none, use finest level, i.e. level 0).
|
|
160
|
+
- "resample": same selection as "ceil"; caller must then resample
|
|
161
|
+
the read pixels to the exact requested resolution.
|
|
162
|
+
Raises ValueError when unit == "level".
|
|
163
|
+
|
|
164
|
+
Returns:
|
|
165
|
+
level_idx: int
|
|
166
|
+
"""
|
|
167
|
+
with _open_slide(path) as slide:
|
|
168
|
+
# --- Guard: resample is not meaningful for discrete level indices ---
|
|
169
|
+
if fallback_mode == "resample" and unit == "level":
|
|
170
|
+
raise ValueError("fallback_mode='resample' is not meaningful for unit='level'.")
|
|
171
|
+
|
|
172
|
+
# --- Trivial case: unit == "level" ---------------------------------
|
|
173
|
+
if unit == "level":
|
|
174
|
+
if not float(resolution).is_integer():
|
|
175
|
+
raise ValueError("When unit is 'level', resolution must be an integer.")
|
|
176
|
+
level_idx = int(resolution)
|
|
177
|
+
if level_idx < 0:
|
|
178
|
+
raise ValueError("Level must be non-negative.")
|
|
179
|
+
if level_idx >= slide.level_count:
|
|
180
|
+
raise ValueError(f"Requested level {level_idx} exceeds maximum level {slide.level_count - 1}.")
|
|
181
|
+
return level_idx
|
|
182
|
+
|
|
183
|
+
# --- Compute per-level values for mpp / downsample --------------------
|
|
184
|
+
level_downsamples = [float(ds) for ds in slide.level_downsamples] # e.g. [1.0, 2.0, 4.0, ...]
|
|
185
|
+
requested = float(resolution)
|
|
186
|
+
|
|
187
|
+
if unit == "mpp":
|
|
188
|
+
mpp0 = _get_mpp0(slide)
|
|
189
|
+
# Effective mpp per level
|
|
190
|
+
values = [mpp0 * ds for ds in level_downsamples]
|
|
191
|
+
|
|
192
|
+
elif unit == "downsample":
|
|
193
|
+
# Downsample factor vs level 0
|
|
194
|
+
values = level_downsamples
|
|
195
|
+
|
|
196
|
+
else:
|
|
197
|
+
raise ValueError(f"Unknown unit: {unit}")
|
|
198
|
+
|
|
199
|
+
# --- Helper: nearest index -----------------------------------------
|
|
200
|
+
def nearest_idx() -> int:
|
|
201
|
+
return min(range(len(values)), key=lambda i: abs(values[i] - requested))
|
|
202
|
+
|
|
203
|
+
# --- Select level according to fallback_mode ------------------------
|
|
204
|
+
if fallback_mode == "nearest":
|
|
205
|
+
level_idx = nearest_idx()
|
|
206
|
+
|
|
207
|
+
elif fallback_mode == "floor":
|
|
208
|
+
# coarsest level with value >= requested (larger value = coarser)
|
|
209
|
+
eligible = [i for i, v in enumerate(values) if v >= requested]
|
|
210
|
+
if eligible:
|
|
211
|
+
level_idx = min(eligible, key=lambda i: values[i])
|
|
212
|
+
else:
|
|
213
|
+
# if none >= requested, use coarsest (last) level
|
|
214
|
+
level_idx = len(values) - 1
|
|
215
|
+
|
|
216
|
+
elif fallback_mode == "ceil":
|
|
217
|
+
# finest level with value <= requested
|
|
218
|
+
eligible = [i for i, v in enumerate(values) if v <= requested]
|
|
219
|
+
if eligible:
|
|
220
|
+
level_idx = max(eligible, key=lambda i: values[i])
|
|
221
|
+
else:
|
|
222
|
+
# if none <= requested, use finest (level 0)
|
|
223
|
+
level_idx = 0
|
|
224
|
+
|
|
225
|
+
elif fallback_mode == "resample":
|
|
226
|
+
# Same selection as "ceil": finest level with value <= requested
|
|
227
|
+
eligible = [i for i, v in enumerate(values) if v <= requested]
|
|
228
|
+
if eligible:
|
|
229
|
+
level_idx = max(eligible, key=lambda i: values[i])
|
|
230
|
+
else:
|
|
231
|
+
level_idx = 0
|
|
232
|
+
|
|
233
|
+
elif fallback_mode == "error":
|
|
234
|
+
tol = 1e-6
|
|
235
|
+
matches = [i for i, v in enumerate(values) if abs(v - requested) <= tol * max(1.0, abs(requested))]
|
|
236
|
+
if not matches:
|
|
237
|
+
raise ValueError(f"No exact {unit} match for requested {requested}; available values: {values}")
|
|
238
|
+
level_idx = matches[0]
|
|
239
|
+
|
|
240
|
+
else:
|
|
241
|
+
raise ValueError(f"Unknown fallback_mode: {fallback_mode}")
|
|
242
|
+
|
|
243
|
+
return level_idx
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import TYPE_CHECKING, Optional
|
|
4
|
+
|
|
5
|
+
if TYPE_CHECKING:
|
|
6
|
+
import cupy as cp
|
|
7
|
+
import numpy as np
|
|
8
|
+
import torch
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def get_torch_device(use_gpu: bool) -> torch.device:
|
|
12
|
+
try:
|
|
13
|
+
import torch
|
|
14
|
+
except ImportError:
|
|
15
|
+
raise ImportError(
|
|
16
|
+
"torch is required to use GPU device selection. Install it with: pip install wsi-patching[gpu]"
|
|
17
|
+
)
|
|
18
|
+
if use_gpu and torch.cuda.is_available():
|
|
19
|
+
return torch.device("cuda")
|
|
20
|
+
elif use_gpu and torch.backends.mps.is_available():
|
|
21
|
+
return torch.device("mps")
|
|
22
|
+
elif use_gpu:
|
|
23
|
+
raise RuntimeError("Requested GPU device, but no CUDA or MPS backend is available.")
|
|
24
|
+
else:
|
|
25
|
+
return torch.device("cpu")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def to_torch_from_xp(
|
|
29
|
+
array: np.ndarray | cp.ndarray, device: torch.device, dtype: Optional[torch.dtype] = None
|
|
30
|
+
) -> torch.Tensor:
|
|
31
|
+
"""Convert a NumPy or CuPy array to a PyTorch tensor on the specified device, with a specified dtype."""
|
|
32
|
+
try:
|
|
33
|
+
import torch
|
|
34
|
+
except ImportError:
|
|
35
|
+
raise ImportError(
|
|
36
|
+
"torch is required to convert arrays to tensors. Install it with: pip install wsi-patching[gpu]"
|
|
37
|
+
)
|
|
38
|
+
if dtype is None:
|
|
39
|
+
dtype = torch.float32
|
|
40
|
+
import numpy as np
|
|
41
|
+
|
|
42
|
+
if isinstance(array, np.ndarray):
|
|
43
|
+
return torch.as_tensor(array, device=device, dtype=dtype)
|
|
44
|
+
else:
|
|
45
|
+
return torch.from_dlpack(array.toDlpack()).to(device=device, dtype=dtype)
|