pathoinfer 0.2.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 (80) hide show
  1. pathoinfer/__init__.py +6 -0
  2. pathoinfer/_extras.py +18 -0
  3. pathoinfer/_logging.py +91 -0
  4. pathoinfer/analysis.py +68 -0
  5. pathoinfer/cli.py +480 -0
  6. pathoinfer/config.py +395 -0
  7. pathoinfer/convert/README.md +340 -0
  8. pathoinfer/convert/__init__.py +4 -0
  9. pathoinfer/convert/common.py +98 -0
  10. pathoinfer/convert/fp16.py +135 -0
  11. pathoinfer/convert/parity.py +484 -0
  12. pathoinfer/convert/ptq.py +163 -0
  13. pathoinfer/convert/tensorrt.py +139 -0
  14. pathoinfer/convert/vlm.py +359 -0
  15. pathoinfer/convert/vlm_parity.py +233 -0
  16. pathoinfer/engine/README.md +134 -0
  17. pathoinfer/engine/__init__.py +3 -0
  18. pathoinfer/engine/pipeline.py +437 -0
  19. pathoinfer/engine/scheduler.py +161 -0
  20. pathoinfer/io/README.md +79 -0
  21. pathoinfer/io/__init__.py +1 -0
  22. pathoinfer/io/interop.py +21 -0
  23. pathoinfer/io/objects.py +232 -0
  24. pathoinfer/io/writers/__init__.py +1 -0
  25. pathoinfer/io/writers/geojson.py +106 -0
  26. pathoinfer/io/writers/overlay.py +102 -0
  27. pathoinfer/io/writers/parquet.py +188 -0
  28. pathoinfer/io/writers/tiff.py +101 -0
  29. pathoinfer/post/README.md +116 -0
  30. pathoinfer/post/__init__.py +1 -0
  31. pathoinfer/post/instances.py +92 -0
  32. pathoinfer/post/nms.py +1 -0
  33. pathoinfer/post/smoothing.py +1 -0
  34. pathoinfer/post/vectorise.py +486 -0
  35. pathoinfer/py.typed +0 -0
  36. pathoinfer/registry/README.md +72 -0
  37. pathoinfer/registry/__init__.py +1 -0
  38. pathoinfer/registry/create.py +71 -0
  39. pathoinfer/registry/legacy.py +71 -0
  40. pathoinfer/registry/loader.py +171 -0
  41. pathoinfer/registry/model_card.py +309 -0
  42. pathoinfer/registry/onnx_info.py +45 -0
  43. pathoinfer/registry/schema/model_card.v1.json +1049 -0
  44. pathoinfer/runtime/README.md +119 -0
  45. pathoinfer/runtime/__init__.py +1 -0
  46. pathoinfer/runtime/base.py +86 -0
  47. pathoinfer/runtime/factory.py +51 -0
  48. pathoinfer/runtime/local/__init__.py +1 -0
  49. pathoinfer/runtime/local/onnx.py +155 -0
  50. pathoinfer/runtime/local/tensorrt.py +70 -0
  51. pathoinfer/runtime/local/torch.py +57 -0
  52. pathoinfer/runtime/local/vllm_offline.py +56 -0
  53. pathoinfer/runtime/remote/README.md +124 -0
  54. pathoinfer/runtime/remote/__init__.py +1 -0
  55. pathoinfer/runtime/remote/triton.py +77 -0
  56. pathoinfer/runtime/remote/vllm.py +137 -0
  57. pathoinfer/runtime/vlm.py +138 -0
  58. pathoinfer/serving/README.md +124 -0
  59. pathoinfer/serving/__init__.py +2 -0
  60. pathoinfer/serving/api.py +359 -0
  61. pathoinfer/serving/triton_repo.py +146 -0
  62. pathoinfer/serving/vllm.py +101 -0
  63. pathoinfer/stitch/README.md +209 -0
  64. pathoinfer/stitch/__init__.py +1 -0
  65. pathoinfer/stitch/base.py +133 -0
  66. pathoinfer/stitch/detection.py +241 -0
  67. pathoinfer/stitch/heatmap.py +211 -0
  68. pathoinfer/stitch/instance.py +232 -0
  69. pathoinfer/stitch/segmentation.py +247 -0
  70. pathoinfer/tiling/README.md +143 -0
  71. pathoinfer/tiling/__init__.py +4 -0
  72. pathoinfer/tiling/dataset.py +82 -0
  73. pathoinfer/tiling/grid.py +232 -0
  74. pathoinfer/tiling/slide_id.py +18 -0
  75. pathoinfer/tiling/synthetic.py +36 -0
  76. pathoinfer-0.2.0.dist-info/METADATA +369 -0
  77. pathoinfer-0.2.0.dist-info/RECORD +80 -0
  78. pathoinfer-0.2.0.dist-info/WHEEL +4 -0
  79. pathoinfer-0.2.0.dist-info/entry_points.txt +2 -0
  80. pathoinfer-0.2.0.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1,21 @@
1
+ """to_geodataframe(): optional interop for users who want geopandas, behind the
2
+ ``[geopandas]`` extra. The only module allowed to import geopandas; core and tests never
3
+ call it.
4
+ """
5
+
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ import polars as pl
10
+ import shapely
11
+
12
+ from pathoinfer._extras import extra, require
13
+
14
+
15
+ def to_geodataframe(parquet: str | Path) -> Any:
16
+ """Read an objects Parquet file into a ``geopandas.GeoDataFrame``. The geometry is in
17
+ level-0 pixels, so the frame has no CRS."""
18
+ gpd = require("geopandas", extra("geopandas"))
19
+ frame = pl.read_parquet(parquet)
20
+ geometry = shapely.from_wkb(frame["geometry"].to_numpy())
21
+ return gpd.GeoDataFrame(frame.drop("geometry").to_pandas(), geometry=geometry, crs=None)
@@ -0,0 +1,232 @@
1
+ """What every writer consumes: the run's metadata and the slide's objects as columns.
2
+
3
+ ``RunInfo`` is recorded in every output. ``ObjectTable`` holds one row per object as
4
+ NumPy columns, built from a stitcher's ``StitchResult``; detections never become Python
5
+ objects on the way. Coordinates are level-0 pixels, x right and y down.
6
+ """
7
+
8
+ from collections.abc import Collection, Mapping
9
+ from dataclasses import asdict, dataclass
10
+ from datetime import UTC, datetime
11
+ from importlib.metadata import version
12
+ from typing import Any, Literal
13
+
14
+ import numpy as np
15
+ import shapely
16
+ from numpy.typing import NDArray
17
+
18
+ from pathoinfer.registry.model_card import RGB, ClassInfo, ModelCard, Task
19
+ from pathoinfer.stitch.base import Feature, StitchResult
20
+ from pathoinfer.tiling.grid import SlideGrid
21
+
22
+ ObjectType = Literal["annotation", "detection"]
23
+ # QuPath object type per task: regions are annotations, cells and tiles are detections.
24
+ # Classification runs also write threshold regions, as annotations (``ObjectTable``).
25
+ OBJECT_TYPES: dict[Task, ObjectType] = {
26
+ "segmentation": "annotation",
27
+ "detection": "detection",
28
+ "classification": "detection",
29
+ "instance": "detection", # nuclei, as QuPath's cells
30
+ }
31
+
32
+
33
+ @dataclass(frozen=True)
34
+ class RunInfo:
35
+ """One slide's run. ``classes`` are the classes an object can have (the card's minus
36
+ its ``background_id``), with any colour overrides applied."""
37
+
38
+ slide_id: str
39
+ slide_name: str
40
+ task: Task
41
+ model_name: str
42
+ model_version: str
43
+ precision: str
44
+ model_source: str
45
+ model_card_schema: int
46
+ slide_mpp: float
47
+ model_mpp: float
48
+ output_mpp: float | None
49
+ tile_size: int
50
+ overlap: int
51
+ tissue_area_um2: float
52
+ classes: tuple[ClassInfo, ...]
53
+ pathoinfer_version: str
54
+ patchology_version: str
55
+ created_at: str
56
+
57
+ @classmethod
58
+ def create(
59
+ cls,
60
+ card: ModelCard,
61
+ grid: SlideGrid,
62
+ model_source: str,
63
+ output_mpp: float | None = None,
64
+ colors: Mapping[str, RGB] | None = None,
65
+ exclude: Collection[int] = (),
66
+ rename: Mapping[int, str] | None = None,
67
+ precision: str | None = None,
68
+ ) -> "RunInfo":
69
+ """``precision``: what the model ran in (default the card's; the autocast dtype for
70
+ an autocast PyTorch model). ``exclude``: class ids no object can have (dropped or
71
+ merged into another);
72
+ ``rename``: new names by class id. ``colors`` are by output name (a renamed class's
73
+ new name, else its card name). Raises ValueError if ``colors`` names a class the
74
+ run does not have."""
75
+ colors, rename = colors or {}, rename or {}
76
+ unknown = set(colors) - {c.name for c in card.classes} - set(rename.values())
77
+ if unknown:
78
+ raise ValueError(f"colours for unknown classes {sorted(unknown)}")
79
+ background = getattr(card, "background_id", None)
80
+ mask = grid.tissue_mask
81
+ tissue_px = float(mask.array.sum()) * mask.downsample[0] * mask.downsample[1]
82
+ return cls(
83
+ slide_id=grid.slide_id,
84
+ slide_name=grid.slide_path.name,
85
+ task=card.task,
86
+ model_name=card.name,
87
+ model_version=card.version,
88
+ precision=precision or card.precision,
89
+ model_source=model_source,
90
+ model_card_schema=card.schema_version,
91
+ slide_mpp=grid.slide_mpp,
92
+ model_mpp=grid.mpp,
93
+ output_mpp=output_mpp,
94
+ tile_size=grid.tile_size,
95
+ overlap=grid.overlap,
96
+ tissue_area_um2=tissue_px * grid.slide_mpp**2,
97
+ classes=tuple(
98
+ c.model_copy(
99
+ update={
100
+ "name": rename.get(c.id, c.name),
101
+ "color": colors.get(rename.get(c.id, c.name), c.color),
102
+ }
103
+ )
104
+ for c in card.classes
105
+ if c.id != background and c.id not in exclude
106
+ ),
107
+ pathoinfer_version=version("pathoinfer"),
108
+ patchology_version=version("patchology"),
109
+ created_at=datetime.now(UTC).isoformat(timespec="seconds"),
110
+ )
111
+
112
+ @property
113
+ def object_type(self) -> ObjectType:
114
+ return OBJECT_TYPES[self.task]
115
+
116
+ def to_dict(self) -> dict[str, Any]:
117
+ """JSON-ready metadata; ``classes`` as ``{id, name, color}`` objects."""
118
+ out = asdict(self)
119
+ out["classes"] = [c.model_dump(mode="json") for c in self.classes]
120
+ return out
121
+
122
+
123
+ @dataclass(frozen=True)
124
+ class ObjectTable:
125
+ """One row per object. ``score``: the detection score; for regions (segmentation)
126
+ their ``mean_probability``, for instances the mean probability of the nucleus's
127
+ type; NaN for objects without one;
128
+ ``measurements`` are extra float columns in output order (NaN where a row has none).
129
+ ``object_type``: each row's QuPath type when rows differ (classification tiles and
130
+ regions), else None and every row has the run's."""
131
+
132
+ geometry: NDArray[np.object_]
133
+ class_id: NDArray[np.int64]
134
+ score: NDArray[np.float32]
135
+ area_um2: NDArray[np.float64]
136
+ measurements: dict[str, NDArray[np.float64]]
137
+ object_type: NDArray[np.str_] | None = None
138
+
139
+ def __len__(self) -> int:
140
+ return len(self.class_id)
141
+
142
+ def take(self, rows: NDArray[np.intp]) -> "ObjectTable":
143
+ return ObjectTable(
144
+ self.geometry[rows],
145
+ self.class_id[rows],
146
+ self.score[rows],
147
+ self.area_um2[rows],
148
+ {k: v[rows] for k, v in self.measurements.items()},
149
+ None if self.object_type is None else self.object_type[rows],
150
+ )
151
+
152
+ def object_types(self, run: RunInfo) -> NDArray[np.str_]:
153
+ """Every row's QuPath object type."""
154
+ if self.object_type is not None:
155
+ return self.object_type
156
+ return np.full(len(self), run.object_type)
157
+
158
+ @classmethod
159
+ def from_result(
160
+ cls,
161
+ result: StitchResult,
162
+ run: RunInfo,
163
+ geometry: Literal["point", "box"] = "box",
164
+ ) -> "ObjectTable":
165
+ """``geometry`` picks box polygons or centre points for detections. A detection's
166
+ ``area_um2`` is its box area either way. Instances are polygons already.
167
+ Detections of a class the run excludes (a classification card's background) are
168
+ dropped. A result with both detections and features (classification tiles and
169
+ regions) gives the detections first, then the features as annotations."""
170
+ if result.instances is not None:
171
+ i = result.instances
172
+ return cls(i.geometry, i.class_id, i.score, i.area_um2, dict(i.measurements))
173
+ if result.detections is None:
174
+ return cls._from_features(result.features)
175
+ d = result.detections
176
+ keep = np.isin(d.labels, [c.id for c in run.classes])
177
+ size = d.boxes[keep, 2:] - d.boxes[keep, :2]
178
+ measurements = {}
179
+ if d.class_probs is not None:
180
+ measurements = {
181
+ f"prob_{c.name}": d.class_probs[keep, c.id].astype(np.float64)
182
+ for c in sorted(run.classes, key=lambda c: c.id)
183
+ }
184
+ tiles = cls(
185
+ d.geometries(geometry)[keep],
186
+ d.labels[keep].astype(np.int64),
187
+ d.scores[keep].astype(np.float32),
188
+ size.prod(axis=1) * run.slide_mpp**2,
189
+ measurements,
190
+ )
191
+ ids = {c.id for c in run.classes}
192
+ regions = [f for f in result.features if f.class_id in ids]
193
+ return tiles.concat(cls._from_features(regions), run) if regions else tiles
194
+
195
+ def concat(self, other: "ObjectTable", run: RunInfo) -> "ObjectTable":
196
+ """Rows of ``self`` then ``other``, each keeping its object type; a measurement
197
+ only one side has is NaN on the other."""
198
+ keys = list(dict.fromkeys([*self.measurements, *other.measurements]))
199
+
200
+ def column(t: ObjectTable, k: str) -> NDArray[np.float64]:
201
+ return t.measurements.get(k, np.full(len(t), np.nan))
202
+
203
+ return ObjectTable(
204
+ np.concatenate([self.geometry, other.geometry]),
205
+ np.concatenate([self.class_id, other.class_id]),
206
+ np.concatenate([self.score, other.score]),
207
+ np.concatenate([self.area_um2, other.area_um2]),
208
+ {k: np.concatenate([column(self, k), column(other, k)]) for k in keys},
209
+ np.concatenate([self.object_types(run), np.full(len(other), "annotation")]).astype(
210
+ np.str_
211
+ ),
212
+ )
213
+
214
+ @classmethod
215
+ def _from_features(cls, features: list[Feature]) -> "ObjectTable":
216
+ keys = [k for k in (features[0].measurements if features else {}) if k != "area_um2"]
217
+ return cls(
218
+ np.array([f.geometry for f in features] or [], dtype=object),
219
+ np.array([f.class_id for f in features], np.int64),
220
+ np.array(
221
+ [f.measurements.get("mean_probability", np.nan) for f in features], np.float32
222
+ ),
223
+ np.array([f.measurements.get("area_um2", np.nan) for f in features], np.float64),
224
+ {k: np.array([f.measurements[k] for f in features], np.float64) for k in keys},
225
+ )
226
+
227
+ def bounds(self) -> NDArray[np.float64]:
228
+ """``(n, 4)`` ``x0, y0, x1, y1`` per object."""
229
+ return np.asarray(shapely.bounds(self.geometry)).reshape(-1, 4)
230
+
231
+ def centroids(self) -> NDArray[np.float64]:
232
+ return np.asarray(shapely.get_coordinates(shapely.centroid(self.geometry))).reshape(-1, 2)
@@ -0,0 +1 @@
1
+ """Writers: GeoJSON for viewers, Parquet for analysis, TIFF for heatmaps (``docs/outputs.md``)."""
@@ -0,0 +1,106 @@
1
+ """GeoJSON FeatureCollections that QuPath imports.
2
+
3
+ Coordinates are level-0 pixels (x right, y down), rounded to 0.1 px: the convention of
4
+ pathology viewers, not RFC 7946's WGS84 longitude and latitude. Each feature carries
5
+ QuPath's properties ``objectType``, ``classification {name, color}``, ``isLocked`` and
6
+ ``measurements``, plus ``object_id`` (the row in the Parquet table). The collection's
7
+ ``properties`` hold the run metadata (a foreign member, which QuPath ignores).
8
+
9
+ Features are streamed to disk, so a million detections never sit in memory as JSON.
10
+ ``.geojson.gz`` is gzip-compressed. The file appears only once complete.
11
+ """
12
+
13
+ import gzip
14
+ import json
15
+ import math
16
+ import os
17
+ import re
18
+ from collections.abc import Iterator
19
+ from pathlib import Path
20
+
21
+ import numpy as np
22
+ import shapely
23
+ from loguru import logger
24
+ from numpy.typing import NDArray
25
+
26
+ from pathoinfer._logging import log_call
27
+ from pathoinfer.io.objects import ObjectTable, RunInfo
28
+
29
+ SUFFIXES = (".geojson", ".geojson.gz")
30
+ _CHUNK = 10_000
31
+
32
+
33
+ @log_call
34
+ def write_geojson(
35
+ path: str | Path, objects: ObjectTable, run: RunInfo, per_class: bool = False
36
+ ) -> list[Path]:
37
+ """Write ``objects`` to ``path`` (``.geojson`` or ``.geojson.gz``).
38
+
39
+ ``per_class`` writes one file per class with objects instead, named
40
+ ``<stem>.<class>.geojson[.gz]``. Returns the files written.
41
+ """
42
+ path = Path(path)
43
+ suffix = next((s for s in SUFFIXES if path.name.endswith(s)), None)
44
+ if suffix is None:
45
+ raise ValueError(f"{path}: expected a .geojson or .geojson.gz file")
46
+ if not per_class:
47
+ _write(path, objects, run, np.arange(len(objects)))
48
+ return [path]
49
+ stem = path.name.removesuffix(suffix)
50
+ names = {c.id: c.name for c in run.classes}
51
+ written = []
52
+ for class_id in np.unique(objects.class_id):
53
+ name = re.sub(r"[^\w.-]+", "_", names[int(class_id)])
54
+ out = path.with_name(f"{stem}.{name}{suffix}")
55
+ _write(out, objects, run, np.flatnonzero(objects.class_id == class_id))
56
+ written.append(out)
57
+ return written
58
+
59
+
60
+ def _write(path: Path, objects: ObjectTable, run: RunInfo, rows: NDArray[np.intp]) -> None:
61
+ partial = path.with_name(path.name + ".partial")
62
+ with (
63
+ gzip.open(partial, "wt", compresslevel=6, encoding="utf-8")
64
+ if path.name.endswith(".gz")
65
+ else open(partial, "w", encoding="utf-8")
66
+ ) as f:
67
+ f.write('{"type":"FeatureCollection","properties":')
68
+ f.write(json.dumps(run.to_dict()))
69
+ f.write(',"features":[')
70
+ for start in range(0, len(rows), _CHUNK):
71
+ chunk = rows[start : start + _CHUNK]
72
+ for i, feature in enumerate(_features(objects.take(chunk), chunk, run)):
73
+ f.write(feature if start + i == 0 else ",\n" + feature)
74
+ f.write("]}\n")
75
+ os.replace(partial, path)
76
+ logger.info("wrote {} ({} objects)", path, len(rows))
77
+
78
+
79
+ def _features(objects: ObjectTable, ids: NDArray[np.intp], run: RunInfo) -> Iterator[str]:
80
+ """One JSON string per object; ``ids`` are their ``object_id``s."""
81
+ rounded = shapely.transform(objects.geometry, lambda c: np.round(c, 1))
82
+ geometries = shapely.to_geojson(rounded)
83
+ classification = {
84
+ c.id: json.dumps({"name": c.name, "color": list(c.color)}) for c in run.classes
85
+ }
86
+ columns: dict[str, NDArray[np.floating]] = {
87
+ "score": objects.score,
88
+ "area_um2": objects.area_um2,
89
+ **objects.measurements,
90
+ }
91
+ names = list(columns)
92
+ rows = zip(*(columns[k].tolist() for k in names), strict=True)
93
+ types = objects.object_types(run).tolist()
94
+ for geometry, object_type, class_id, object_id, values in zip(
95
+ geometries, types, objects.class_id.tolist(), ids.tolist(), rows, strict=True
96
+ ):
97
+ # JSON has no NaN; QuPath reads a missing measurement as NaN.
98
+ measurements = json.dumps(
99
+ {k: v for k, v in zip(names, values, strict=True) if not math.isnan(v)}
100
+ )
101
+ yield (
102
+ f'{{"type":"Feature","geometry":{geometry},"properties":'
103
+ f'{{"objectType":"{object_type}","isLocked":false,"classification":'
104
+ f'{classification[class_id]},"measurements":{measurements},'
105
+ f'"object_id":{object_id}}}}}'
106
+ )
@@ -0,0 +1,102 @@
1
+ """PNG overlay: the whole slide at a chosen mpp, with every object filled in its class
2
+ colour at ``ALPHA`` opacity, outlined at full opacity, and a legend of the classes.
3
+ Detections drawn as points are circles. Outlines lie on pixel edges, as the coordinates
4
+ mean: level-0 pixel ``(i, j)`` covers ``[i, i+1] x [j, j+1]``.
5
+ """
6
+
7
+ import os
8
+ from collections.abc import Iterable, Sequence
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ import cv2
13
+ import numpy as np
14
+ from loguru import logger
15
+ from numpy.typing import NDArray
16
+
17
+ from pathoinfer._logging import log_call
18
+ from pathoinfer.io.objects import ObjectTable, RunInfo
19
+
20
+ ALPHA = 0.4 # fill opacity: the tissue stays readable under the colour
21
+ SHIFT = 4 # cv2 sub-pixel bits
22
+
23
+ Color = tuple[int, int, int]
24
+
25
+
26
+ def render(
27
+ image: NDArray[np.uint8],
28
+ geometries: Iterable[Any],
29
+ colors: Sequence[Color],
30
+ legend: dict[str, Color],
31
+ level0_per_px: float,
32
+ alpha: float = ALPHA,
33
+ ) -> NDArray[np.uint8]:
34
+ """``image`` (RGB, pixel ``(0, 0)`` at level-0 ``(0, 0)``, ``level0_per_px`` level-0 px
35
+ per pixel) with ``geometries`` (level-0 px) filled at ``alpha``, outlined, and a
36
+ legend of ``legend`` (class name to colour) in the top-left corner."""
37
+ image = np.ascontiguousarray(image[..., :3])
38
+ fill = image.copy()
39
+ for geometry, color in zip(geometries, colors, strict=True):
40
+ if geometry.geom_type != "Point":
41
+ cv2.fillPoly(fill, _rings(geometry, level0_per_px), color, cv2.LINE_AA, SHIFT)
42
+ out = np.asarray(cv2.addWeighted(fill, alpha, image, 1 - alpha, 0), dtype=np.uint8)
43
+ for geometry, color in zip(geometries, colors, strict=True):
44
+ if geometry.geom_type == "Point":
45
+ xy = np.round((np.array([geometry.x, geometry.y]) / level0_per_px - 0.5) * 2**SHIFT)
46
+ centre = (int(xy[0]), int(xy[1]))
47
+ cv2.circle(out, centre, 3 * 2**SHIFT, color, 1, cv2.LINE_AA, SHIFT)
48
+ else:
49
+ cv2.polylines(out, _rings(geometry, level0_per_px), True, color, 1, cv2.LINE_AA, SHIFT)
50
+ _legend(out, legend)
51
+ return out
52
+
53
+
54
+ @log_call
55
+ def write_overlay(
56
+ path: str | Path, slide: Any, objects: ObjectTable, run: RunInfo, mpp: float = 6.0
57
+ ) -> Path:
58
+ """Read ``slide`` (an open patchology slide) at ``mpp`` and write the overlay of
59
+ ``objects`` as a PNG. The level-0 resolution is ``run.slide_mpp``, so an
60
+ ``mpp_override`` applies here too."""
61
+ path = Path(path)
62
+ level0_per_px = mpp / run.slide_mpp
63
+ size = tuple(max(1, int(d / level0_per_px)) for d in slide.dimensions)
64
+ image = slide.read_region_scaled((0, 0), level0_per_px, size)
65
+ colors: dict[int, Color] = {c.id: c.color for c in run.classes}
66
+ present = set(objects.class_id.tolist())
67
+ legend = {c.name: colors[c.id] for c in run.classes if c.id in present}
68
+ drawn = render(
69
+ image,
70
+ objects.geometry,
71
+ [colors[i] for i in objects.class_id.tolist()],
72
+ legend,
73
+ level0_per_px,
74
+ )
75
+ partial = path.with_name(path.name + ".partial.png")
76
+ if not cv2.imwrite(str(partial), cv2.cvtColor(drawn, cv2.COLOR_RGB2BGR)):
77
+ raise OSError(f"could not write {partial}")
78
+ os.replace(partial, path)
79
+ logger.info("wrote {} ({} x {} px at {:g} mpp)", path, *size, mpp)
80
+ return path
81
+
82
+
83
+ def _rings(geometry: Any, level0_per_px: float) -> list[NDArray[np.int32]]:
84
+ """``geometry``'s rings in image px, cv2 fixed point."""
85
+ scale = 2**SHIFT / level0_per_px
86
+ return [
87
+ np.round(np.asarray(r.coords) * scale - 2 ** (SHIFT - 1)).astype(np.int32)
88
+ for p in getattr(geometry, "geoms", [geometry])
89
+ for r in (p.exterior, *p.interiors)
90
+ ]
91
+
92
+
93
+ def _legend(image: NDArray[np.uint8], legend: dict[str, Color]) -> None:
94
+ if not legend:
95
+ return
96
+ font, scale, line = cv2.FONT_HERSHEY_SIMPLEX, 0.6, 24
97
+ width = max(cv2.getTextSize(name, font, scale, 1)[0][0] for name in legend) + 50
98
+ cv2.rectangle(image, (8, 8), (8 + width, 16 + line * len(legend)), (255, 255, 255), -1)
99
+ for n, (name, color) in enumerate(sorted(legend.items())):
100
+ y = 12 + line * n
101
+ cv2.rectangle(image, (14, y + 4), (34, y + 18), color, -1)
102
+ cv2.putText(image, name, (42, y + 17), font, scale, (0, 0, 0), 1, cv2.LINE_AA)
@@ -0,0 +1,188 @@
1
+ """Parquet tables for analysis: one row per object, and one summary row per class (or
2
+ the summary as JSON: ``write_summary`` to a ``.json`` path).
3
+
4
+ The objects table is a Polars frame built straight from NumPy columns. Geometry is WKB in
5
+ level-0 pixels. Every file also stores the run metadata as JSON under the Parquet
6
+ key-value metadata key ``pathoinfer``.
7
+
8
+ ``geoparquet=True`` writes through DuckDB's spatial extension instead, which adds the
9
+ GeoParquet ``geo`` metadata. Without a ``crs`` that metadata would mean longitude and
10
+ latitude (OGC:CRS84), so the geometry is tagged with a PROJJSON engineering CRS for
11
+ level-0 pixels, y down. DuckDB writes the metadata; every write reads it back and fails
12
+ if the ``geo`` entry is missing or names another CRS.
13
+ """
14
+
15
+ import json
16
+ import os
17
+ from pathlib import Path
18
+ from typing import Any
19
+
20
+ import duckdb
21
+ import numpy as np
22
+ import polars as pl
23
+ import shapely
24
+ from loguru import logger
25
+
26
+ from pathoinfer._logging import log_call
27
+ from pathoinfer.io.objects import ObjectTable, RunInfo
28
+
29
+ ROW_GROUP = 100_000
30
+ META_KEY = "pathoinfer"
31
+
32
+
33
+ def objects_frame(objects: ObjectTable, run: RunInfo) -> pl.DataFrame:
34
+ """The objects table as written to Parquet."""
35
+ bounds, centroids = objects.bounds(), objects.centroids()
36
+ names = np.array([""] * (max((c.id for c in run.classes), default=-1) + 1), dtype=object)
37
+ for c in run.classes:
38
+ names[c.id] = c.name
39
+ columns: dict[str, Any] = {
40
+ "slide_id": pl.repeat(run.slide_id, len(objects), eager=True),
41
+ "object_id": np.arange(len(objects), dtype=np.int64),
42
+ "task": pl.repeat(run.task, len(objects), eager=True),
43
+ "object_type": pl.Series(objects.object_types(run), dtype=pl.String),
44
+ "class_id": objects.class_id,
45
+ "class_name": pl.Series(names[objects.class_id], dtype=pl.String),
46
+ "score": pl.Series(objects.score).fill_nan(None),
47
+ "centroid_x": centroids[:, 0],
48
+ "centroid_y": centroids[:, 1],
49
+ "bbox_x0": bounds[:, 0],
50
+ "bbox_y0": bounds[:, 1],
51
+ "bbox_x1": bounds[:, 2],
52
+ "bbox_y1": bounds[:, 3],
53
+ "area_um2": objects.area_um2,
54
+ **objects.measurements,
55
+ "geometry": pl.Series(shapely.to_wkb(objects.geometry), dtype=pl.Binary),
56
+ "model_name": pl.repeat(run.model_name, len(objects), eager=True),
57
+ "model_version": pl.repeat(run.model_version, len(objects), eager=True),
58
+ }
59
+ return pl.DataFrame(columns)
60
+
61
+
62
+ @log_call
63
+ def write_parquet(
64
+ path: str | Path, objects: ObjectTable, run: RunInfo, geoparquet: bool = False
65
+ ) -> Path:
66
+ """Write the objects table (zstd, statistics, ~100k-row row groups)."""
67
+ path = Path(path)
68
+ frame = objects_frame(objects, run)
69
+ partial = path.with_name(path.name + ".partial")
70
+ if geoparquet:
71
+ _write_geoparquet(partial, frame, run)
72
+ else:
73
+ frame.write_parquet(
74
+ partial,
75
+ compression="zstd",
76
+ statistics=True,
77
+ row_group_size=ROW_GROUP,
78
+ metadata={META_KEY: json.dumps(run.to_dict())},
79
+ )
80
+ os.replace(partial, path)
81
+ logger.info("wrote {} ({} objects)", path, len(objects))
82
+ return path
83
+
84
+
85
+ def summary_frame(objects: ObjectTable, run: RunInfo) -> pl.DataFrame:
86
+ """One row per class, zero-count classes included: ``count``, ``mean_score`` (null
87
+ without scores), ``total_area_um2``, the slide's ``tissue_area_um2`` and the run
88
+ metadata. Only objects of the run's type count, so a classification summary counts
89
+ tiles, not the threshold regions drawn over them."""
90
+ objects = objects.take(np.flatnonzero(objects.object_types(run) == run.object_type))
91
+ per_object = pl.DataFrame(
92
+ {
93
+ "class_id": objects.class_id,
94
+ "score": pl.Series(objects.score).fill_nan(None),
95
+ "area_um2": objects.area_um2,
96
+ }
97
+ )
98
+ stats = per_object.group_by("class_id").agg(
99
+ pl.len().alias("count"),
100
+ pl.col("score").mean().alias("mean_score"),
101
+ pl.col("area_um2").sum().alias("total_area_um2"),
102
+ )
103
+ meta = {k: v for k, v in run.to_dict().items() if k != "classes"}
104
+ first = ["slide_id", "class_id", "class_name", "count", "mean_score", "total_area_um2"]
105
+ return (
106
+ pl.DataFrame(
107
+ {"class_id": [c.id for c in run.classes], "class_name": [c.name for c in run.classes]},
108
+ schema={"class_id": pl.Int64, "class_name": pl.String},
109
+ )
110
+ .join(stats, on="class_id", how="left")
111
+ .with_columns(
112
+ pl.col("count").fill_null(0).cast(pl.UInt32),
113
+ pl.col("total_area_um2").fill_null(0.0),
114
+ **{k: pl.lit(v) for k, v in meta.items()},
115
+ )
116
+ .select(*first, *(k for k in meta if k not in first))
117
+ )
118
+
119
+
120
+ @log_call
121
+ def write_summary(path: str | Path, objects: ObjectTable, run: RunInfo) -> Path:
122
+ """``summary_frame`` as Parquet, or as JSON when ``path`` ends in ``.json``: the run
123
+ metadata once, and ``classes`` mapping each class name to ``class_id``, ``count``,
124
+ ``mean_score`` and ``total_area_um2``."""
125
+ path = Path(path)
126
+ frame = summary_frame(objects, run)
127
+ if path.suffix == ".json":
128
+ meta = {k: v for k, v in run.to_dict().items() if k != "classes"}
129
+ stats = ["class_id", "count", "mean_score", "total_area_um2"]
130
+ classes = {
131
+ row["class_name"]: {k: row[k] for k in stats} for row in frame.iter_rows(named=True)
132
+ }
133
+ partial = path.with_name(path.name + ".partial")
134
+ partial.write_text(json.dumps({**meta, "classes": classes}, indent=2) + "\n")
135
+ os.replace(partial, path)
136
+ else:
137
+ frame.write_parquet(
138
+ path, compression="zstd", metadata={META_KEY: json.dumps(run.to_dict())}
139
+ )
140
+ logger.info("wrote {}", path)
141
+ return path
142
+
143
+
144
+ def pixel_crs(slide_mpp: float) -> dict[str, Any]:
145
+ """PROJJSON for level-0 pixels: x right, y down, one unit = ``slide_mpp`` microns."""
146
+ unit = {"type": "LinearUnit", "name": "level-0 pixel", "conversion_factor": slide_mpp * 1e-6}
147
+ return {
148
+ "type": "EngineeringCRS",
149
+ "name": "Slide level-0 pixels",
150
+ "datum": {"type": "EngineeringDatum", "name": "Slide level-0 top-left corner"},
151
+ "coordinate_system": {
152
+ "subtype": "Cartesian",
153
+ "axis": [
154
+ {"name": "x", "abbreviation": "x", "direction": "east", "unit": unit},
155
+ {"name": "y", "abbreviation": "y", "direction": "south", "unit": unit},
156
+ ],
157
+ },
158
+ }
159
+
160
+
161
+ def _write_geoparquet(path: Path, frame: pl.DataFrame, run: RunInfo) -> None:
162
+ con = duckdb.connect()
163
+ try:
164
+ con.load_extension("spatial")
165
+ except duckdb.Error:
166
+ con.install_extension("spatial")
167
+ con.load_extension("spatial")
168
+ crs = pixel_crs(run.slide_mpp)
169
+ con.register("objects", frame.to_arrow())
170
+ con.sql(
171
+ "COPY (SELECT * REPLACE (ST_SetCRS(ST_GeomFromWKB(geometry), $crs) AS geometry) "
172
+ "FROM objects) TO '" + str(path).replace("'", "''") + "' (FORMAT parquet, "
173
+ f"COMPRESSION zstd, ROW_GROUP_SIZE {ROW_GROUP}, KV_METADATA {{{META_KEY}: $meta}})",
174
+ params={"crs": json.dumps(crs), "meta": json.dumps(run.to_dict())},
175
+ )
176
+ con.close()
177
+ geo = json.loads(pl.read_parquet_metadata(path).get("geo", "{}"))
178
+ column = geo.get("columns", {}).get("geometry", {})
179
+ if (
180
+ geo.get("primary_column") != "geometry"
181
+ or column.get("encoding") != "WKB"
182
+ or (column.get("crs") != crs)
183
+ ):
184
+ path.unlink()
185
+ raise RuntimeError(
186
+ f"DuckDB {duckdb.__version__} did not write the expected GeoParquet metadata "
187
+ f"(got {geo}); write with geoparquet=False"
188
+ )