pytessera 0.1.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 (71) hide show
  1. pytessera/__init__.py +129 -0
  2. pytessera/_internal/__init__.py +8 -0
  3. pytessera/_internal/mask.py +44 -0
  4. pytessera/_internal/memory.py +40 -0
  5. pytessera/annotations/__init__.py +118 -0
  6. pytessera/annotations/_resources.py +38 -0
  7. pytessera/annotations/asap.py +88 -0
  8. pytessera/annotations/cache.py +149 -0
  9. pytessera/annotations/create.py +247 -0
  10. pytessera/annotations/maskspec.py +146 -0
  11. pytessera/annotations/ndpa.py +155 -0
  12. pytessera/annotations/parse.py +164 -0
  13. pytessera/annotations/render.py +433 -0
  14. pytessera/annotations/roles.py +126 -0
  15. pytessera/annotations/templates/__init__.py +7 -0
  16. pytessera/annotations/templates/annotation_template.dcm +0 -0
  17. pytessera/cli/__init__.py +184 -0
  18. pytessera/cli/__main__.py +5 -0
  19. pytessera/cli/_runtime.py +157 -0
  20. pytessera/examples_data/__init__.py +133 -0
  21. pytessera/io/__init__.py +62 -0
  22. pytessera/io/cache.py +72 -0
  23. pytessera/io/case.py +249 -0
  24. pytessera/io/dicom.py +304 -0
  25. pytessera/io/dicom_pyramid.py +174 -0
  26. pytessera/io/fast_decode.py +179 -0
  27. pytessera/io/ndpi_pyramid.py +180 -0
  28. pytessera/io/open_wsi.py +120 -0
  29. pytessera/io/pyramid.py +354 -0
  30. pytessera/io/serialize.py +154 -0
  31. pytessera/io/tiff_pyramid.py +350 -0
  32. pytessera/ml/__init__.py +43 -0
  33. pytessera/ml/dataset.py +393 -0
  34. pytessera/ml/inference.py +120 -0
  35. pytessera/ml/loader.py +136 -0
  36. pytessera/ml/sampler.py +239 -0
  37. pytessera/ml/transforms.py +80 -0
  38. pytessera/models/__init__.py +17 -0
  39. pytessera/models/resnet.py +76 -0
  40. pytessera/pipeline.py +1197 -0
  41. pytessera/segmentation/__init__.py +62 -0
  42. pytessera/segmentation/artefacts.py +233 -0
  43. pytessera/segmentation/evaluation.py +293 -0
  44. pytessera/segmentation/malignancy.py +65 -0
  45. pytessera/segmentation/tissue.py +474 -0
  46. pytessera/tiles/__init__.py +129 -0
  47. pytessera/tiles/build.py +211 -0
  48. pytessera/tiles/cohort.py +110 -0
  49. pytessera/tiles/context.py +64 -0
  50. pytessera/tiles/datatile.py +276 -0
  51. pytessera/tiles/labels.py +400 -0
  52. pytessera/tiles/lazy.py +288 -0
  53. pytessera/tiles/ops.py +242 -0
  54. pytessera/tiles/patchbag.py +183 -0
  55. pytessera/tiles/populate.py +303 -0
  56. pytessera/tiles/quadtree.py +386 -0
  57. pytessera/viz/__init__.py +48 -0
  58. pytessera/viz/backend.py +26 -0
  59. pytessera/viz/overlay.py +61 -0
  60. pytessera/viz/slide.py +172 -0
  61. pytessera/viz/structure.py +206 -0
  62. pytessera/viz/tiles.py +215 -0
  63. pytessera/wsi/__init__.py +37 -0
  64. pytessera/wsi/grid.py +136 -0
  65. pytessera/wsi/magnification.py +457 -0
  66. pytessera-0.1.0.dist-info/METADATA +134 -0
  67. pytessera-0.1.0.dist-info/RECORD +71 -0
  68. pytessera-0.1.0.dist-info/WHEEL +5 -0
  69. pytessera-0.1.0.dist-info/entry_points.txt +2 -0
  70. pytessera-0.1.0.dist-info/licenses/LICENSE +21 -0
  71. pytessera-0.1.0.dist-info/top_level.txt +1 -0
pytessera/__init__.py ADDED
@@ -0,0 +1,129 @@
1
+ """pytessera, WSI tiling utilities for digital pathology pipelines.
2
+
3
+ Top-level convenience
4
+ ---------------------
5
+ :func:`build_dataset` runs the full skeleton-then-populate pipeline for many
6
+ slides in one call, any format, opened via :func:`open_wsi` internally::
7
+
8
+ from pytessera import build_dataset
9
+
10
+ dataset = build_dataset([9, 40], data_root="/path/to/data", magnification=10)
11
+
12
+ :func:`build_datatiles` is the single-slide core it's built on -- take an
13
+ already-opened :class:`~pytessera.io.Pyramid` and one ``slide_id``:
14
+
15
+ build_datatiles one call: skeleton + pixels, one slide
16
+ build_dataset the same, batched over many slides
17
+ build_skeleton skeleton only (no pixels)
18
+ populate_datatiles fill .img / .mask / .category on a skeleton
19
+ classify_masks fill .mask / .category only, no pixel reader opened
20
+ build_patch_bags hierarchical patch-bag grids (no pixels)
21
+ populate_patch_bags fill .img on a patch-bag dataset
22
+ build_datatiles_from_annotations annotated-region set, one slide (from
23
+ pyramid.annotations, format-agnostic),
24
+ grouped by connected region (region_id);
25
+ each leaf's source-polygon label is
26
+ written to DataTile.tissue_class
27
+ build_dataset_from_annotations the same, batched over many slides
28
+
29
+ group_by_region regroup an annotation dataset
30
+ into {slide: {region_id: {...}}}
31
+
32
+ On a built dataset, pixel-free:
33
+
34
+ summarize tile counts per slide and label, as a table
35
+ split_slides train / validation split by whole slide
36
+
37
+ DICOM case-batch convenience, resolving magnification-ladder zoom levels
38
+ (z1=40x, z2=20x, ...) per case via Pyramid.resolve_level:
39
+
40
+ build_datatiles_for_cases DICOM case batch, one call per case,
41
+ thread-pooled over slide_workers
42
+
43
+ Unused (no callers in this package or in ALIVE; kept importable, not called
44
+ by anything above -- see each function's own docstring):
45
+
46
+ build_skeleton_for_cases DICOM-only, separate skeleton implementation
47
+ populate_datatiles_for_cases DICOM-only, separate populate implementation
48
+
49
+ Optional, post-catalog hooks for a caller's own third-party tools -- neither
50
+ bundled nor validated by PyTessera itself, just wired onto existing tiles:
51
+
52
+ attach_tile_labels run a caller-supplied classifier,
53
+ write DataTile.tissue_class
54
+ attach_tile_embeddings run a caller-supplied encoder,
55
+ write DataTile.embedding
56
+
57
+ For finer control, the subpackages are public:
58
+
59
+ :mod:`pytessera.io` load a pyramid, any format
60
+ :mod:`pytessera.wsi` pyramid geometry helpers
61
+ :mod:`pytessera.annotations` parse / render / create / cache
62
+ :mod:`pytessera.segmentation` tissue mask + artefact removal
63
+ :mod:`pytessera.tiles` quadtree, DataTile, patch ops,
64
+ build_skeleton_for_cases,
65
+ populate_datatiles_for_cases,
66
+ group_by_region, attach_tile_labels,
67
+ attach_tile_embeddings
68
+ :mod:`pytessera.pipeline` top-level convenience entry
69
+ :mod:`pytessera.ml` ``[ml]`` extra: TileDataset,
70
+ BalancedTileSampler, build_dataloader
71
+ """
72
+
73
+ from __future__ import annotations
74
+
75
+ from .io.open_wsi import open_wsi
76
+ from .pipeline import (
77
+ build_dataset,
78
+ build_dataset_from_annotations,
79
+ build_datatiles,
80
+ build_datatiles_for_cases,
81
+ build_datatiles_from_annotations,
82
+ build_patch_bags,
83
+ build_skeleton,
84
+ classify_masks,
85
+ populate_datatiles,
86
+ populate_patch_bags,
87
+ )
88
+ from .tiles import (
89
+ PatchBag,
90
+ attach_bag_embeddings,
91
+ attach_context_chain,
92
+ attach_region_labels,
93
+ attach_tile_embeddings,
94
+ attach_tile_labels,
95
+ build_skeleton_for_cases,
96
+ group_by_region,
97
+ populate_datatiles_for_cases,
98
+ select_balanced_subset,
99
+ split_slides,
100
+ summarize,
101
+ )
102
+ from .tiles.datatile import DataTile
103
+
104
+ __all__ = [
105
+ "DataTile",
106
+ "PatchBag",
107
+ "attach_bag_embeddings",
108
+ "attach_context_chain",
109
+ "attach_region_labels",
110
+ "attach_tile_embeddings",
111
+ "attach_tile_labels",
112
+ "build_dataset",
113
+ "build_dataset_from_annotations",
114
+ "build_datatiles",
115
+ "build_datatiles_for_cases",
116
+ "build_datatiles_from_annotations",
117
+ "build_patch_bags",
118
+ "build_skeleton",
119
+ "build_skeleton_for_cases",
120
+ "classify_masks",
121
+ "group_by_region",
122
+ "open_wsi",
123
+ "populate_datatiles",
124
+ "populate_datatiles_for_cases",
125
+ "populate_patch_bags",
126
+ "select_balanced_subset",
127
+ "split_slides",
128
+ "summarize",
129
+ ]
@@ -0,0 +1,8 @@
1
+ """pytessera._internal, Private helpers. NOT part of the public API.
2
+
3
+ Anything here can change without notice between releases. Public code lives
4
+ in the top-level subpackages.
5
+
6
+ Contents:
7
+ memory.py resource/psutil-based memory tracking
8
+ """
@@ -0,0 +1,44 @@
1
+ """Resolve the tissue mask a builder tiles from: the caller's own segmentation
2
+ if supplied, else PyTessera's built-in :func:`~pytessera.segmentation.tissue_mask`.
3
+
4
+ This is the bring-your-own-segmentation hook, the mask-side counterpart to the
5
+ encoder/classifier hooks. A ``mask_fn`` maps a coarse RGB slide image to a tissue
6
+ mask; any truthy pixel is treated as tissue.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from collections.abc import Callable
12
+ from typing import TYPE_CHECKING
13
+
14
+ import numpy as np
15
+
16
+ if TYPE_CHECKING:
17
+ from ..segmentation.tissue import TissueType
18
+
19
+ #: ``coarse_rgb (H, W, 3) uint8 -> mask (H, W)``. The mask may be boolean, 0/1, or
20
+ #: 0/255; any value ``> 0`` counts as tissue.
21
+ MaskFn = Callable[[np.ndarray], np.ndarray]
22
+
23
+
24
+ def resolve_mask_u8(
25
+ rgb: np.ndarray,
26
+ mask_fn: MaskFn | None,
27
+ *,
28
+ tissue_type: TissueType = "dense",
29
+ smooth_sigma: float = 0.30,
30
+ ) -> np.ndarray:
31
+ """Return a ``(H, W)`` 0/255 uint8 tissue mask for ``rgb``.
32
+
33
+ ``mask_fn(rgb)`` when a caller supplies one, otherwise the built-in
34
+ ``tissue_mask(rgb, tissue_type=..., smooth_sigma=...)``. The result is
35
+ normalised to 0/255 so it feeds :func:`~pytessera.tiles.build_quadtree_from_mask`
36
+ regardless of whether the mask came back boolean, 0/1, or 0/255.
37
+ """
38
+ if mask_fn is not None:
39
+ mask = mask_fn(rgb)
40
+ else:
41
+ from ..segmentation import tissue_mask
42
+
43
+ mask = tissue_mask(rgb, tissue_type=tissue_type, smooth_sigma=smooth_sigma)
44
+ return (np.asarray(mask) > 0).astype(np.uint8) * 255
@@ -0,0 +1,40 @@
1
+ """Process-level resource limits.
2
+
3
+ Private helper used at the very start of long-running scripts to cap
4
+ how much memory the Python interpreter is allowed to allocate. This
5
+ is the kind of guard you set once in a launcher script, not something
6
+ the library calls implicitly.
7
+
8
+ Linux-only at the moment (Windows does not expose RLIMIT_AS through
9
+ the stdlib). The call is a no-op on platforms that lack ``resource``.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ try:
15
+ import resource # type: ignore[import-not-found]
16
+ except ImportError:
17
+ resource = None # type: ignore[assignment]
18
+
19
+
20
+ __all__ = ["set_memory_limit"]
21
+
22
+
23
+ def set_memory_limit(max_memory_in_gb: float) -> None:
24
+ """Cap the process's virtual address space.
25
+
26
+ Parameters
27
+ ----------
28
+ max_memory_in_gb : float
29
+ Soft + hard limit in gigabytes. Allocations past the limit
30
+ raise :class:`MemoryError`.
31
+
32
+ Notes
33
+ -----
34
+ No-op on platforms without ``resource`` (notably Windows). Use
35
+ a Job object via pywin32 if you need an equivalent guard there.
36
+ """
37
+ if resource is None:
38
+ return
39
+ n_bytes = int(max_memory_in_gb * 1024 * 1024 * 1024)
40
+ resource.setrlimit(resource.RLIMIT_AS, (n_bytes, n_bytes))
@@ -0,0 +1,118 @@
1
+ """pytessera.annotations, Parse, rasterise, and create DICOM annotations.
2
+
3
+ Public surface:
4
+
5
+ Parsing
6
+ extract_annotations, scale_polygons_with_labels (DICOM .graphics)
7
+ parse_asap_xml (ASAP/CAMELYON)
8
+ parse_ndpa, load_ndpa_polygons (Hamamatsu NDPI .ndpa)
9
+ Rendering
10
+ draw_polylines_on_mask, build_annotation_mask, mask_to_polylines,
11
+ prepare_annotation_ops, rasterize_tile_mask (memory-flat, per-tile)
12
+ get_full_bool_mask_from_pyramid, get_annotation_ops_from_pyramid
13
+ (format-agnostic, any open Pyramid -- full-raster and memory-flat
14
+ forms, respectively)
15
+ Label policy (opt-in; default is neutral foreground)
16
+ AnnotationResolver, foreground_resolver, set_default_resolver,
17
+ Role + label_map_resolver (declarative), MaskSpec + multiclass_resolver
18
+ Creation
19
+ sync_metadata, assign_new_uids, add_referenced_series,
20
+ add_graphic_layer, build_polyline_annotation, to_display_units,
21
+ render_overlay_to_image
22
+ Caching (DICOM-only; prefer the Pyramid-native forms above for an
23
+ already-open Pyramid of any format)
24
+ update_mask_cache_for_slide, get_full_bool_mask_for_slide,
25
+ get_annotation_ops_for_slide
26
+ Templates
27
+ template_path, template_bytes
28
+ """
29
+
30
+ from ._resources import DEFAULT_TEMPLATE, template_bytes, template_path
31
+ from .asap import parse_asap_xml
32
+ from .cache import (
33
+ get_annotation_ops_for_slide,
34
+ get_full_bool_mask_for_slide,
35
+ update_mask_cache_for_slide,
36
+ )
37
+ from .create import (
38
+ add_graphic_layer,
39
+ add_referenced_series,
40
+ assign_new_uids,
41
+ build_polyline_annotation,
42
+ render_overlay_to_image,
43
+ sync_metadata,
44
+ to_display_units,
45
+ )
46
+ from .maskspec import (
47
+ MaskSpec,
48
+ count_distinct_class_overlap,
49
+ multiclass_resolver,
50
+ )
51
+ from .ndpa import (
52
+ NdpaRegion,
53
+ load_ndpa_polygons,
54
+ ndpa_to_level0_polygons,
55
+ parse_ndpa,
56
+ )
57
+ from .parse import extract_annotations, scale_polygons_with_labels
58
+ from .render import (
59
+ AnnotationResolver,
60
+ build_annotation_mask,
61
+ clamp_pts,
62
+ compute_nesting_depths,
63
+ draw_polylines_on_mask,
64
+ foreground_resolver,
65
+ get_annotation_ops_from_pyramid,
66
+ get_default_resolver,
67
+ get_full_bool_mask_from_pyramid,
68
+ is_valid_poly,
69
+ is_wholly_inside,
70
+ mask_to_polylines,
71
+ prepare_annotation_ops,
72
+ rasterize_tile_mask,
73
+ set_default_resolver,
74
+ )
75
+ from .roles import Role, label_map_resolver
76
+
77
+ __all__ = [
78
+ "AnnotationResolver",
79
+ "MaskSpec",
80
+ "Role",
81
+ "label_map_resolver",
82
+ "count_distinct_class_overlap",
83
+ "multiclass_resolver",
84
+ "DEFAULT_TEMPLATE",
85
+ "NdpaRegion",
86
+ "add_graphic_layer",
87
+ "clamp_pts",
88
+ "compute_nesting_depths",
89
+ "foreground_resolver",
90
+ "get_default_resolver",
91
+ "is_valid_poly",
92
+ "is_wholly_inside",
93
+ "set_default_resolver",
94
+ "load_ndpa_polygons",
95
+ "ndpa_to_level0_polygons",
96
+ "parse_ndpa",
97
+ "parse_asap_xml",
98
+ "add_referenced_series",
99
+ "assign_new_uids",
100
+ "build_annotation_mask",
101
+ "build_polyline_annotation",
102
+ "draw_polylines_on_mask",
103
+ "extract_annotations",
104
+ "get_annotation_ops_from_pyramid",
105
+ "get_annotation_ops_for_slide",
106
+ "get_full_bool_mask_from_pyramid",
107
+ "get_full_bool_mask_for_slide",
108
+ "mask_to_polylines",
109
+ "prepare_annotation_ops",
110
+ "rasterize_tile_mask",
111
+ "render_overlay_to_image",
112
+ "scale_polygons_with_labels",
113
+ "sync_metadata",
114
+ "template_bytes",
115
+ "template_path",
116
+ "to_display_units",
117
+ "update_mask_cache_for_slide",
118
+ ]
@@ -0,0 +1,38 @@
1
+ """Access to package-data resources (DICOM annotation templates).
2
+
3
+ Use :func:`template_path` instead of constructing paths with ``__file__``
4
+ , after ``pip install`` the package may live inside a zip wheel and the
5
+ filesystem path is not guaranteed to exist.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import Iterator
11
+ from contextlib import contextmanager
12
+ from importlib.resources import as_file, files
13
+ from pathlib import Path
14
+
15
+ DEFAULT_TEMPLATE = "annotation_template.dcm"
16
+
17
+
18
+ @contextmanager
19
+ def template_path(name: str = DEFAULT_TEMPLATE) -> Iterator[Path]:
20
+ """Yield a filesystem :class:`Path` for a shipped annotation template.
21
+
22
+ Use as a context manager, the path is only guaranteed to exist for
23
+ the duration of the ``with`` block::
24
+
25
+ from pytessera.annotations import template_path
26
+ import pydicom
27
+
28
+ with template_path() as p:
29
+ ds = pydicom.dcmread(p)
30
+ """
31
+ resource = files("pytessera.annotations.templates") / name
32
+ with as_file(resource) as p:
33
+ yield Path(p)
34
+
35
+
36
+ def template_bytes(name: str = DEFAULT_TEMPLATE) -> bytes:
37
+ """Return the raw bytes of a shipped template, for in-memory parsing."""
38
+ return (files("pytessera.annotations.templates") / name).read_bytes()
@@ -0,0 +1,88 @@
1
+ """Parse ASAP / CAMELYON ``.xml`` annotations into polygons.
2
+
3
+ ASAP (the annotation tool used by CAMELYON16/17 and many public WSI sets)
4
+ stores region annotations as XML polygons in level-0 (full-resolution) pixel
5
+ coordinates. This parser returns ``(polygon, label)`` pairs in the exact shape
6
+ :func:`pytessera.annotations.parse.scale_polygons_with_labels` and
7
+ :func:`pytessera.annotations.render.build_annotation_mask` expect, so a
8
+ non-Sectra dataset can reuse the package's scaling + rasterisation unchanged.
9
+
10
+ Example
11
+ -------
12
+ ::
13
+
14
+ from pytessera.annotations import parse_asap_xml, scale_polygons_with_labels
15
+ from pytessera.annotations import build_annotation_mask, label_map_resolver, Role
16
+
17
+ # Map this export's group names to what they mean (your policy, not ours).
18
+ group_labels = {"_0": "tumour", "metastases": "tumour", "_2": "normal"}
19
+ polys = parse_asap_xml("patient_004_node_4.xml", group_labels=group_labels)
20
+ scaled = scale_polygons_with_labels(
21
+ [{"coordinates": p.tolist(), "label": lbl} for p, lbl in polys],
22
+ target_z_dim=(Ht, Wt), orig_z_dim=(H0, W0), # H0,W0 = level-0 dims
23
+ )
24
+ resolver = label_map_resolver({"tumour": Role.INCLUDE, "normal": Role.EXCLUDE})
25
+ mask = build_annotation_mask(scaled, mask_shape=(Ht, Wt), resolver=resolver)
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import xml.etree.ElementTree as ET
31
+ from pathlib import Path
32
+
33
+ import numpy as np
34
+
35
+ __all__ = ["parse_asap_xml"]
36
+
37
+
38
+ def parse_asap_xml(
39
+ path: str | Path,
40
+ *,
41
+ group_labels: dict[str, str] | None = None,
42
+ min_points: int = 3,
43
+ ) -> list[tuple[np.ndarray, str | None]]:
44
+ """Parse an ASAP XML file into ``(polygon, label)`` pairs.
45
+
46
+ Parameters
47
+ ----------
48
+ path
49
+ Path to an ASAP ``.xml`` annotation file.
50
+ group_labels
51
+ Optional mapping from each annotation's ``PartOfGroup`` to a
52
+ Sectra-style label (``"i"`` include / ``"e"`` exclude / ...).
53
+ When ``None`` the raw group string is kept as the label.
54
+ min_points
55
+ Polygons with fewer vertices are skipped.
56
+
57
+ Returns
58
+ -------
59
+ list of (polygon, label)
60
+ ``polygon`` is an ``(N, 2)`` float32 array of ``(x, y)`` vertices
61
+ in level-0 (full-resolution) pixel coordinates; ``label`` is the
62
+ mapped group (or the raw group string, or ``None``).
63
+ """
64
+ root = ET.parse(str(path)).getroot()
65
+ out: list[tuple[np.ndarray, str | None]] = []
66
+ for ann in root.iter("Annotation"):
67
+ coords_el = ann.find("Coordinates")
68
+ if coords_el is None:
69
+ continue
70
+ pts = sorted(
71
+ coords_el.findall("Coordinate"),
72
+ key=lambda c: int(float(c.get("Order", "0"))),
73
+ )
74
+ # X/Y are required by the ASAP schema, but a hand-edited file can omit
75
+ # them; drop the malformed point rather than crashing the whole parse.
76
+ xy = [
77
+ (float(x), float(y))
78
+ for c in pts
79
+ if (x := c.get("X")) is not None and (y := c.get("Y")) is not None
80
+ ]
81
+ if len(xy) < min_points:
82
+ continue
83
+ group = ann.get("PartOfGroup")
84
+ label: str | None = group
85
+ if group_labels is not None and group is not None:
86
+ label = group_labels.get(group, group)
87
+ out.append((np.asarray(xy, dtype=np.float32), label))
88
+ return out
@@ -0,0 +1,149 @@
1
+ """Cache annotation-mask rasterisation so repeated per-slide lookups are cheap.
2
+
3
+ Each function takes a caller-owned dict, mutates it in place, and returns it.
4
+ Cache keys: ``str(slide_id)`` for the default-zoom mask, and
5
+ ``(str(slide_id), int(z), "full_bool")`` for an explicit per-zoom mask.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Any
11
+
12
+ import numpy as np
13
+
14
+ from ..io.cache import get_case_info_cached
15
+ from .parse import extract_annotations, scale_polygons_with_labels
16
+ from .render import AnnotationResolver, build_annotation_mask, prepare_annotation_ops
17
+
18
+
19
+ def update_mask_cache_for_slide(
20
+ cache: dict,
21
+ *,
22
+ slide_id: Any,
23
+ data_root: str,
24
+ target_z: int = 2,
25
+ resolver: AnnotationResolver | None = None,
26
+ ) -> dict:
27
+ """Compute and cache the boolean annotation mask for ``slide_id`` at ``target_z``.
28
+
29
+ Sets ``cache[str(slide_id)] = mask`` and returns ``cache``.
30
+
31
+ Empty result if the slide has no annotations OR no polygon survives
32
+ scaling, both are cached as an all-zeros mask so subsequent calls
33
+ don't re-walk the DICOM.
34
+ """
35
+ info = get_case_info_cached(str(slide_id), data_root=data_root)
36
+ zoom_info = info["zoom_info"]
37
+ # Annotation polygons live in the slide's finest (base) level coordinates.
38
+ # Under magnification keying the base is the smallest present z, that is 1
39
+ # for a 40x-base slide but higher for a downsized / non-40x slide (which has
40
+ # no z1). Hardcoding z1 here KeyError'd on those slides.
41
+ base_z = min(zoom_info)
42
+ target_dim = zoom_info[target_z]["dim"]["PixelDim"]
43
+ orig_dim = zoom_info[base_z]["dim"]["PixelDim"]
44
+ Ht, Wt = map(int, target_dim)
45
+ Ho, Wo = map(int, orig_dim)
46
+
47
+ if info["orig_ann"] is None:
48
+ cache[str(slide_id)] = np.zeros((Ht, Wt), dtype=bool)
49
+ return cache
50
+
51
+ annotation_dict = extract_annotations(
52
+ info["orig_ann"], zoom_info[base_z]["dim"]
53
+ )
54
+ polys = scale_polygons_with_labels(
55
+ list(annotation_dict.values()),
56
+ target_z_dim=(Ht, Wt),
57
+ orig_z_dim=(Ho, Wo),
58
+ )
59
+ if not polys:
60
+ cache[str(slide_id)] = np.zeros((Ht, Wt), dtype=bool)
61
+ return cache
62
+
63
+ cache[str(slide_id)] = build_annotation_mask(polys, mask_shape=(Ht, Wt), resolver=resolver)
64
+ return cache
65
+
66
+
67
+ def get_full_bool_mask_for_slide(
68
+ cache: dict,
69
+ *,
70
+ slide_id: Any,
71
+ z: int,
72
+ data_root: str,
73
+ resolver: AnnotationResolver | None = None,
74
+ ) -> np.ndarray | None:
75
+ """Return cached boolean full mask for ``(slide_id, z)``, building it if needed.
76
+
77
+ The per-zoom entry is keyed ``(str(slide_id), int(z), "full_bool")``.
78
+ Returns ``None`` if the slide has no usable annotations.
79
+ """
80
+ sid = str(slide_id)
81
+ z = int(z)
82
+ key = (sid, z, "full_bool")
83
+
84
+ full_bool = cache.get(key)
85
+ if full_bool is not None:
86
+ return full_bool
87
+
88
+ update_mask_cache_for_slide(
89
+ cache, slide_id=sid, data_root=str(data_root), target_z=z, resolver=resolver,
90
+ )
91
+ full = cache.get(sid)
92
+ if full is None:
93
+ return None
94
+
95
+ arr = np.asarray(full)
96
+ if arr.dtype != np.bool_:
97
+ arr = arr != 0
98
+ cache[key] = arr
99
+ return arr
100
+
101
+
102
+ def get_annotation_ops_for_slide(
103
+ cache: dict,
104
+ *,
105
+ slide_id: Any,
106
+ z: int,
107
+ data_root: str,
108
+ resolver: AnnotationResolver | None = None,
109
+ ) -> list | None:
110
+ """Return cached, slide-clamped fill ops for ``(slide_id, z)``.
111
+
112
+ The memory-flat alternative to :func:`get_full_bool_mask_for_slide`:
113
+ instead of caching a full-slide boolean raster (which is ~2 GB at
114
+ z=2, ~8 GB at z=1), this caches the prepared polygon fill ops (KB)
115
+ so callers can rasterise individual tile windows on demand via
116
+ :func:`pytessera.annotations.render.rasterize_tile_mask`. Peak
117
+ memory is then O(tile), not O(slide).
118
+
119
+ The per-zoom entry is keyed ``(str(slide_id), int(z), "ops")``.
120
+ Returns ``None`` (cached) when the slide has no usable annotations.
121
+ """
122
+ sid = str(slide_id)
123
+ z = int(z)
124
+ key = (sid, z, "ops")
125
+ if key in cache:
126
+ return cache[key]
127
+
128
+ info = get_case_info_cached(sid, data_root=str(data_root))
129
+ Ht, Wt = map(int, info["zoom_info"][z]["dim"]["PixelDim"])
130
+ Ho, Wo = map(int, info["zoom_info"][1]["dim"]["PixelDim"])
131
+
132
+ if info["orig_ann"] is None:
133
+ cache[key] = None
134
+ return None
135
+
136
+ annotation_dict = extract_annotations(
137
+ info["orig_ann"], info["zoom_info"][1]["dim"]
138
+ )
139
+ polys = scale_polygons_with_labels(
140
+ list(annotation_dict.values()),
141
+ target_z_dim=(Ht, Wt),
142
+ orig_z_dim=(Ho, Wo),
143
+ )
144
+ if not polys:
145
+ cache[key] = None
146
+ return None
147
+
148
+ cache[key] = prepare_annotation_ops(polys, slide_shape=(Ht, Wt), resolver=resolver)
149
+ return cache[key]