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.
- pathoinfer/__init__.py +6 -0
- pathoinfer/_extras.py +18 -0
- pathoinfer/_logging.py +91 -0
- pathoinfer/analysis.py +68 -0
- pathoinfer/cli.py +480 -0
- pathoinfer/config.py +395 -0
- pathoinfer/convert/README.md +340 -0
- pathoinfer/convert/__init__.py +4 -0
- pathoinfer/convert/common.py +98 -0
- pathoinfer/convert/fp16.py +135 -0
- pathoinfer/convert/parity.py +484 -0
- pathoinfer/convert/ptq.py +163 -0
- pathoinfer/convert/tensorrt.py +139 -0
- pathoinfer/convert/vlm.py +359 -0
- pathoinfer/convert/vlm_parity.py +233 -0
- pathoinfer/engine/README.md +134 -0
- pathoinfer/engine/__init__.py +3 -0
- pathoinfer/engine/pipeline.py +437 -0
- pathoinfer/engine/scheduler.py +161 -0
- pathoinfer/io/README.md +79 -0
- pathoinfer/io/__init__.py +1 -0
- pathoinfer/io/interop.py +21 -0
- pathoinfer/io/objects.py +232 -0
- pathoinfer/io/writers/__init__.py +1 -0
- pathoinfer/io/writers/geojson.py +106 -0
- pathoinfer/io/writers/overlay.py +102 -0
- pathoinfer/io/writers/parquet.py +188 -0
- pathoinfer/io/writers/tiff.py +101 -0
- pathoinfer/post/README.md +116 -0
- pathoinfer/post/__init__.py +1 -0
- pathoinfer/post/instances.py +92 -0
- pathoinfer/post/nms.py +1 -0
- pathoinfer/post/smoothing.py +1 -0
- pathoinfer/post/vectorise.py +486 -0
- pathoinfer/py.typed +0 -0
- pathoinfer/registry/README.md +72 -0
- pathoinfer/registry/__init__.py +1 -0
- pathoinfer/registry/create.py +71 -0
- pathoinfer/registry/legacy.py +71 -0
- pathoinfer/registry/loader.py +171 -0
- pathoinfer/registry/model_card.py +309 -0
- pathoinfer/registry/onnx_info.py +45 -0
- pathoinfer/registry/schema/model_card.v1.json +1049 -0
- pathoinfer/runtime/README.md +119 -0
- pathoinfer/runtime/__init__.py +1 -0
- pathoinfer/runtime/base.py +86 -0
- pathoinfer/runtime/factory.py +51 -0
- pathoinfer/runtime/local/__init__.py +1 -0
- pathoinfer/runtime/local/onnx.py +155 -0
- pathoinfer/runtime/local/tensorrt.py +70 -0
- pathoinfer/runtime/local/torch.py +57 -0
- pathoinfer/runtime/local/vllm_offline.py +56 -0
- pathoinfer/runtime/remote/README.md +124 -0
- pathoinfer/runtime/remote/__init__.py +1 -0
- pathoinfer/runtime/remote/triton.py +77 -0
- pathoinfer/runtime/remote/vllm.py +137 -0
- pathoinfer/runtime/vlm.py +138 -0
- pathoinfer/serving/README.md +124 -0
- pathoinfer/serving/__init__.py +2 -0
- pathoinfer/serving/api.py +359 -0
- pathoinfer/serving/triton_repo.py +146 -0
- pathoinfer/serving/vllm.py +101 -0
- pathoinfer/stitch/README.md +209 -0
- pathoinfer/stitch/__init__.py +1 -0
- pathoinfer/stitch/base.py +133 -0
- pathoinfer/stitch/detection.py +241 -0
- pathoinfer/stitch/heatmap.py +211 -0
- pathoinfer/stitch/instance.py +232 -0
- pathoinfer/stitch/segmentation.py +247 -0
- pathoinfer/tiling/README.md +143 -0
- pathoinfer/tiling/__init__.py +4 -0
- pathoinfer/tiling/dataset.py +82 -0
- pathoinfer/tiling/grid.py +232 -0
- pathoinfer/tiling/slide_id.py +18 -0
- pathoinfer/tiling/synthetic.py +36 -0
- pathoinfer-0.2.0.dist-info/METADATA +369 -0
- pathoinfer-0.2.0.dist-info/RECORD +80 -0
- pathoinfer-0.2.0.dist-info/WHEEL +4 -0
- pathoinfer-0.2.0.dist-info/entry_points.txt +2 -0
- pathoinfer-0.2.0.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
# pathoinfer - stitch
|
|
2
|
+
|
|
3
|
+
Turns per-tile model outputs into one slide-level result in level-0 pixel coordinates
|
|
4
|
+
(x right, y down): shapely geometries with their class and measurements, plus optional
|
|
5
|
+
rasters. One stitcher per task.
|
|
6
|
+
|
|
7
|
+
## Contract
|
|
8
|
+
|
|
9
|
+
| | |
|
|
10
|
+
|---|---|
|
|
11
|
+
| `Stitcher.add(specs, outputs)` | One batch: row `i` of every tensor in `outputs` (a runtime's raw outputs, on any device) belongs to `specs[i]`. Batches arrive in any tile order. |
|
|
12
|
+
| `Stitcher.finalize()` | Called once after the last batch; returns a `StitchResult`. |
|
|
13
|
+
| `StitchResult.features` | `Feature(geometry, class_id, class_name, measurements)`; `geometry` is a shapely `Polygon` or `MultiPolygon` in level-0 pixels. |
|
|
14
|
+
| `StitchResult.rasters` | `Raster(array, scale, origin)`: pixel `(col, row)` covers level-0 `origin + scale * (col, row)` to `origin + scale * (col + 1, row + 1)`. |
|
|
15
|
+
|
|
16
|
+
## Usage
|
|
17
|
+
|
|
18
|
+
Stitching runs on its own CPU thread, so the model never waits on it. `StitchThread`
|
|
19
|
+
feeds it through a bounded queue: `put` blocks while the queue is full, which slows the
|
|
20
|
+
reader instead of filling memory. A stitcher error is raised from the next `put` or from
|
|
21
|
+
`finalize`.
|
|
22
|
+
|
|
23
|
+
```python
|
|
24
|
+
from pathoinfer.stitch.base import StitchThread
|
|
25
|
+
from pathoinfer.stitch.segmentation import SegmentationStitcher
|
|
26
|
+
|
|
27
|
+
stitcher = SegmentationStitcher(card, grid, output_mpp=2.0, min_area_um2=50)
|
|
28
|
+
with StitchThread(stitcher, maxsize=8) as thread:
|
|
29
|
+
for tiles, specs in loader: # pathoinfer.tiling.dataset.make_loader
|
|
30
|
+
thread.put(specs, runtime.predict(tiles))
|
|
31
|
+
result = thread.finalize()
|
|
32
|
+
|
|
33
|
+
for feature in result.features:
|
|
34
|
+
print(feature.class_name, feature.measurements["area_um2"], feature.geometry.bounds)
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
`card` is a `SegmentationCard` (from `registry.loader.load_model`), `grid` a `SlideGrid`
|
|
38
|
+
(from `tiling.grid.build_grid`) and `runtime` a `Runtime` (from
|
|
39
|
+
`runtime.factory.make_runtime`).
|
|
40
|
+
|
|
41
|
+
## Segmentation
|
|
42
|
+
|
|
43
|
+
`SegmentationStitcher(card, grid, ...)`:
|
|
44
|
+
|
|
45
|
+
| Option | Default | Meaning |
|
|
46
|
+
|---|---|---|
|
|
47
|
+
| `output_mpp` | `2.0` | Resolution the probabilities are blended and polygonised at; never finer than the model's mpp |
|
|
48
|
+
| `simplify_px` | `1.5` | Douglas-Peucker tolerance in output pixels (topology kept); turns pixel staircases into diagonal runs |
|
|
49
|
+
| `smooth` | `2` | Rounds of Chaikin corner cutting after simplifying: each replaces every vertex with points 1/4 and 3/4 along its edges, doubling the vertices, so outlines are curves rather than pixel steps. `0` keeps outlines on pixel edges |
|
|
50
|
+
| `min_area_um2` | `0.0` | Remove small objects: drop regions smaller than this, checked on the merged region (before simplifying, so specks cost nothing more) and again on the final polygon |
|
|
51
|
+
| `connectivity` | `8` | 8: parts touching only at a pixel corner are one region (a MultiPolygon meeting at the point); 4: separate regions, so diagonal strands break up |
|
|
52
|
+
| `fill_holes_um2` | `0.0` | Fill holes smaller than this. A hole that holds another class's region is kept, so classes never overlap; same-class islands inside a filled hole are dropped. `.inf` in YAML fills every hole |
|
|
53
|
+
| `band_height` | `2 * tile` | Rows per band, in output pixels |
|
|
54
|
+
| `keep_labels` | `False` | Also return the slide's label map as `rasters["labels"]` (-1 where no tile reached; 255 in the TIFF) |
|
|
55
|
+
|
|
56
|
+
How it works (the module docstring has the maths):
|
|
57
|
+
|
|
58
|
+
1. **Blend.** Each tile's class probabilities (softmax of the logits, unless the card's
|
|
59
|
+
output activation is `probs`) are area-resampled to `output_mpp` and weighted by a
|
|
60
|
+
centre-heavy Gaussian (nnU-Net style, sigma = tile / 8). Weighted probabilities and
|
|
61
|
+
weights are summed into separate canvases and divided at the end, so tile edges, where
|
|
62
|
+
models are least reliable, count least.
|
|
63
|
+
2. **Stream in bands.** The canvas is held as horizontal bands. Each band counts the grid
|
|
64
|
+
tiles that overlap it and is finalised when the last one arrives, so memory stays at a
|
|
65
|
+
few bands, not the slide, whatever order the DataLoader workers deliver tiles in.
|
|
66
|
+
Peak canvas memory is logged (`peak_bytes`).
|
|
67
|
+
3. **Polygonise each band.** Argmax gives a label map. For every class except the card's
|
|
68
|
+
`background_id`, each connected region (`connectivity`, default 8) becomes the exact
|
|
69
|
+
union of its pixels, holes included (`post.vectorise.regions`), so areas equal pixel
|
|
70
|
+
counts.
|
|
71
|
+
4. **Merge seams.** Polygons that reach a band boundary are kept aside and, once every
|
|
72
|
+
band is done, unioned with the same-class polygons they touch (STRtree query, then
|
|
73
|
+
`unary_union` of each touching group).
|
|
74
|
+
5. **Fill holes, remove small objects.** On whole merged regions (after the seam merge,
|
|
75
|
+
so band boundaries never split a hole or an object), as the two options say.
|
|
76
|
+
6. **Clean up.** Drop collinear vertices, simplify, smooth (Chaikin), make valid, keep polygonal parts, drop
|
|
77
|
+
regions under `min_area_um2`, scale to level 0 and round to 0.1 px.
|
|
78
|
+
|
|
79
|
+
Measurements per feature: `area_um2`, `perimeter_um` and `mean_probability` (the blended
|
|
80
|
+
probability of the feature's class over its pixels).
|
|
81
|
+
|
|
82
|
+
Two pitfalls the code avoids, both covered by tests:
|
|
83
|
+
|
|
84
|
+
- Never buffer a whole pixel-centre contour as one line. Such a contour can run back over
|
|
85
|
+
itself, and GEOS then drops parts of it; buffering segment by segment does not.
|
|
86
|
+
- Drop collinear vertices before simplifying. Otherwise Douglas-Peucker chooses between
|
|
87
|
+
near-tied points and moves corners depending on how a polygon was assembled.
|
|
88
|
+
|
|
89
|
+
## Detection
|
|
90
|
+
|
|
91
|
+
`DetectionStitcher(card, grid, score_threshold=None, nms_iou=None)`; the run config's
|
|
92
|
+
`detection:` section sets both and the output `geometry`.
|
|
93
|
+
|
|
94
|
+
1. **Decode.** Boxes are read as the card says (`xyxy` or `cxcywh`, `pixel` or
|
|
95
|
+
`normalised`), converted to `xyxy` and moved to level 0:
|
|
96
|
+
`(tile_origin_model + box) * downsample`. Scores below the threshold (the config's,
|
|
97
|
+
else the card's) are dropped.
|
|
98
|
+
2. **Ownership.** A detection is kept only by the tile whose core contains its box
|
|
99
|
+
centre. Cores partition the slide, so an object seen whole by every overlapping tile is
|
|
100
|
+
reported exactly once. That holds for objects whose half-size is at most
|
|
101
|
+
`overlap // 2` model pixels (up to about `overlap` wide): the owning tile's core is
|
|
102
|
+
`overlap // 2` inside the tile, so the owner sees the whole object. A warning is
|
|
103
|
+
logged when the grid's overlap is below the card's `recommended_overlap`.
|
|
104
|
+
3. **NMS (optional).** Wider objects are cut by tile edges, shift their centres and can
|
|
105
|
+
be reported twice. With `nms_iou` set, detections centred within `overlap` model px
|
|
106
|
+
of an interior core edge go through class-aware NMS against other tiles' detections
|
|
107
|
+
(STRtree pairs, greedy by score); a tile's own detections are never merged. Two tiles
|
|
108
|
+
see such an object cut at their edges, so the IoU is about `overlap / width`: NMS
|
|
109
|
+
removes the duplicate only when `nms_iou` is below that. More overlap is the
|
|
110
|
+
dependable fix.
|
|
111
|
+
|
|
112
|
+
`finalize()` returns `StitchResult(features=[], detections=Detections(...))`: NumPy
|
|
113
|
+
columns `boxes` (level-0 `xyxy`), `scores`, `labels` and, when the card names a
|
|
114
|
+
`class_probs` output, `class_probs`. Writers read them as columns too
|
|
115
|
+
(`io.objects.ObjectTable.from_result`), so no Python object exists per detection.
|
|
116
|
+
Output formats are in `docs/outputs.md`.
|
|
117
|
+
|
|
118
|
+
## Instance (nuclei)
|
|
119
|
+
|
|
120
|
+
`InstanceStitcher(card, grid, threshold=0.5, marker_threshold=0.4, min_size_px=10,
|
|
121
|
+
simplify_px=1.0, smooth=2, workers=0)`; the run config's `instance:` section sets them
|
|
122
|
+
(there `workers` defaults to 4).
|
|
123
|
+
|
|
124
|
+
`workers` > 0 runs steps 1 and 3 for each tile in that many `forkserver` processes
|
|
125
|
+
(`tile_columns`; the stitcher thread keeps the softmax and the joining). At most
|
|
126
|
+
`2 * workers` tiles are in flight, so the stitch queue still back-pressures the reader,
|
|
127
|
+
and results are joined in submission order, so the output equals the serial one. On the
|
|
128
|
+
PanNuke mosaic with an RTX 5090: 64 tiles/s on one thread, 160 with 4 processes, 228 with
|
|
129
|
+
8 (each slide pays ~0.9 s to start the pool), against 279 tiles/s for the FP16 TensorRT
|
|
130
|
+
plan. A worker's error is raised from the next `add` or from `finalize`.
|
|
131
|
+
|
|
132
|
+
1. **Per tile.** The `np` softmax gives each pixel's nucleus probability, and HoVer-Net's
|
|
133
|
+
watershed on it and the `hv` maps gives an instance map (`post/instances.py`,
|
|
134
|
+
ported from pathotrain so inference matches its validation). Each instance takes the
|
|
135
|
+
majority non-background type of the `nt` argmax under it. Untyped instances are
|
|
136
|
+
dropped.
|
|
137
|
+
2. **Ownership.** As for detections, an instance is kept only by the tile whose core holds
|
|
138
|
+
its centroid. A nucleus up to about `overlap` wide is seen whole by its owner and
|
|
139
|
+
reported once; a neighbour that sees it cut has its shifted centroid outside its core.
|
|
140
|
+
Larger objects can be cut or reported twice (warning below the card's
|
|
141
|
+
`recommended_overlap`).
|
|
142
|
+
3. **Polygons.** A tile's kept instances are traced together from its label map
|
|
143
|
+
(`post/vectorise.label_pieces`, then `to_features`), so touching nuclei share one
|
|
144
|
+
border line.
|
|
145
|
+
|
|
146
|
+
`finalize()` returns `StitchResult(features=[], instances=Instances(...))`: NumPy columns
|
|
147
|
+
`geometry`, `class_id`, `score` (the type's mean probability), `area_um2` and
|
|
148
|
+
measurements `perimeter_um`, `nucleus_probability`.
|
|
149
|
+
|
|
150
|
+
## Classification heatmaps
|
|
151
|
+
|
|
152
|
+
`HeatmapStitcher(card, grid, sigma_tiles=0, thresholds=None, ...)` for a
|
|
153
|
+
`ClassificationCard` (one `(batch, n_classes)` output per tile):
|
|
154
|
+
|
|
155
|
+
1. **Average into cores.** A core's probabilities are the mean of every kept tile that
|
|
156
|
+
overlaps it, weighted by overlap area: its own tile counts `stride²`, each side
|
|
157
|
+
neighbour `stride * overlap/2`, each corner neighbour `(overlap/2)²`. Cores of tiles
|
|
158
|
+
that were not kept have no value (NaN).
|
|
159
|
+
2. **Smooth (optional).** `sigma_tiles` > 0 applies a Gaussian over the core grid,
|
|
160
|
+
normalised so cores without a value neither count nor change.
|
|
161
|
+
3. **Outputs.**
|
|
162
|
+
- `rasters["prob_<class>"]`: float16, one pixel per core, with `scale` the grid stride
|
|
163
|
+
and `origin` half the overlap in level-0 px (exact for interior cores; edge cores
|
|
164
|
+
reach the slide edge, half an overlap further than their pixel).
|
|
165
|
+
- `detections`: one object per kept core (its box), `labels` the argmax class,
|
|
166
|
+
`scores` its probability, `class_probs` every class's probability; writers emit them
|
|
167
|
+
as QuPath detections with `prob_<class>` measurements, for measurement maps.
|
|
168
|
+
- `features`: with `thresholds={"tumour": 0.5}`, region polygons where the class's
|
|
169
|
+
probability reaches the threshold, traced on the core grid by `post.vectorise`
|
|
170
|
+
(`simplify_px` default 1 core, `smooth` 2, `min_area_um2`, `fill_holes_um2`).
|
|
171
|
+
|
|
172
|
+
The engine runs it from the config's `classification:` section. `ObjectTable.from_result`
|
|
173
|
+
writes the tiles as detections and the regions after them as annotations (a per-row
|
|
174
|
+
`object_type`); the summary counts tiles only.
|
|
175
|
+
|
|
176
|
+
## Shared vectoriser
|
|
177
|
+
|
|
178
|
+
Segmentation and heatmap regions both use `post/vectorise.py`: `regions` (contours with
|
|
179
|
+
holes on pixel edges), `merge` (across band seams), `fill_holes`, `to_features`
|
|
180
|
+
(simplify and smooth every border once so neighbours share it, scale to level 0,
|
|
181
|
+
measure) and `vectorise` (all of them on one whole
|
|
182
|
+
mask). Regions are exact pixel unions; with `connectivity` 8 (default) parts that touch
|
|
183
|
+
only at a pixel corner are one region, with 4 separate regions. `post/README.md` has
|
|
184
|
+
the details and measurements.
|
|
185
|
+
|
|
186
|
+
## Testing
|
|
187
|
+
|
|
188
|
+
`tests/stitch/test_heatmap.py` feeds a checkerboard of 3 x 3-tile blocks: the raster
|
|
189
|
+
equals a brute-force average that intersects every core with every tile (also with
|
|
190
|
+
missing tiles); one hot tile spreads exactly `stride²`, `stride * overlap/2` and
|
|
191
|
+
`(overlap/2)²` over `(stride + overlap)²`; the thresholded region is exactly the tumour
|
|
192
|
+
cores (one region with connectivity 8, four with 4); smoothing keeps probabilities summing to 1 and gaps empty.
|
|
193
|
+
|
|
194
|
+
`tests/stitch/test_detection.py` uses an ideal detector that reports every object a tile
|
|
195
|
+
overlaps, clipped at the tile edge: objects on four-tile corners and edges are reported
|
|
196
|
+
once, a dense lattice gives the exact count and boxes, NMS removes duplicates only below
|
|
197
|
+
`overlap / width`, and 1 million detections stitch in about a second (measured, one run).
|
|
198
|
+
|
|
199
|
+
`tests/stitch/test_segmentation.py` builds a synthetic `SlideGrid` and feeds analytic
|
|
200
|
+
logits, so expected results are exact:
|
|
201
|
+
|
|
202
|
+
- a disk centred on the corner of four tiles is one polygon within 2% of its analytic
|
|
203
|
+
area and perimeter (measured: 0.11% and 0.06%);
|
|
204
|
+
- an annulus keeps exactly one interior ring;
|
|
205
|
+
- banded output equals a single canvas to 1e-4 of area without simplification, and
|
|
206
|
+
within the simplification tolerance with it;
|
|
207
|
+
- shuffled tile order gives the same result;
|
|
208
|
+
- peak band memory stays under half a full canvas;
|
|
209
|
+
- `StitchThread` matches a direct call and re-raises stitcher errors.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Stitchers: tile outputs back to slide level, one per task."""
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
"""Stitcher protocol, its result, and the thread that runs it.
|
|
2
|
+
|
|
3
|
+
A stitcher turns tile outputs into one slide-level result in level-0 pixel coordinates.
|
|
4
|
+
It runs on its own CPU thread (:class:`StitchThread`), fed through a bounded queue, so
|
|
5
|
+
the model never waits on stitching and a slow stitcher back-pressures the reader instead
|
|
6
|
+
of filling memory.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import queue
|
|
10
|
+
import threading
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
from types import TracebackType
|
|
13
|
+
from typing import Any, Protocol, Self
|
|
14
|
+
|
|
15
|
+
import numpy as np
|
|
16
|
+
from loguru import logger
|
|
17
|
+
from numpy.typing import NDArray
|
|
18
|
+
|
|
19
|
+
from pathoinfer.runtime.base import Outputs
|
|
20
|
+
from pathoinfer.tiling.grid import TileSpec
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass(frozen=True)
|
|
24
|
+
class Feature:
|
|
25
|
+
"""One slide-level object: a shapely Polygon or MultiPolygon in level-0 pixels."""
|
|
26
|
+
|
|
27
|
+
geometry: Any
|
|
28
|
+
class_id: int
|
|
29
|
+
class_name: str
|
|
30
|
+
measurements: dict[str, float]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass(frozen=True)
|
|
34
|
+
class Raster:
|
|
35
|
+
"""A slide-level image. Level-0 transform: pixel ``(col, row)`` covers level-0
|
|
36
|
+
``origin + scale * (col, row)`` to ``origin + scale * (col + 1, row + 1)``."""
|
|
37
|
+
|
|
38
|
+
array: NDArray[np.generic]
|
|
39
|
+
scale: float
|
|
40
|
+
origin: tuple[float, float] = (0.0, 0.0)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass(frozen=True)
|
|
44
|
+
class StitchResult:
|
|
45
|
+
"""``features`` for polygon tasks; ``detections`` (a columnar table, see
|
|
46
|
+
``stitch.detection.Detections``) for detection, turned into features by writers;
|
|
47
|
+
``instances`` (``stitch.instance.Instances``, polygons as columns) for instance."""
|
|
48
|
+
|
|
49
|
+
features: list[Feature]
|
|
50
|
+
rasters: dict[str, Raster] = field(default_factory=dict)
|
|
51
|
+
detections: Any = None
|
|
52
|
+
instances: Any = None
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class Stitcher(Protocol):
|
|
56
|
+
def add(self, specs: list[TileSpec], outputs: Outputs) -> None:
|
|
57
|
+
"""Merge one batch: ``outputs`` row ``i`` (any device) belongs to ``specs[i]``.
|
|
58
|
+
Batches may arrive in any tile order."""
|
|
59
|
+
...
|
|
60
|
+
|
|
61
|
+
def finalize(self) -> StitchResult:
|
|
62
|
+
"""Called once, after the last batch."""
|
|
63
|
+
...
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
_DONE = object()
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class StitchThread:
|
|
70
|
+
"""Run ``stitcher`` on a background thread fed by a queue of ``maxsize`` batches.
|
|
71
|
+
|
|
72
|
+
``put`` blocks while the queue is full. An error in the stitcher is raised from the
|
|
73
|
+
next ``put`` or from ``finalize``; the thread keeps draining the queue meanwhile, so
|
|
74
|
+
the producer never deadlocks.
|
|
75
|
+
"""
|
|
76
|
+
|
|
77
|
+
def __init__(self, stitcher: Stitcher, maxsize: int = 8) -> None:
|
|
78
|
+
self.stitcher = stitcher
|
|
79
|
+
self._queue: queue.Queue[Any] = queue.Queue(maxsize)
|
|
80
|
+
self._error: BaseException | None = None
|
|
81
|
+
self._result: StitchResult | None = None
|
|
82
|
+
self._thread = threading.Thread(target=self._work, name="stitcher", daemon=True)
|
|
83
|
+
self._thread.start()
|
|
84
|
+
|
|
85
|
+
def put(self, specs: list[TileSpec], outputs: Outputs) -> None:
|
|
86
|
+
self._raise()
|
|
87
|
+
self._queue.put((specs, outputs))
|
|
88
|
+
|
|
89
|
+
def finalize(self) -> StitchResult:
|
|
90
|
+
self._queue.put(_DONE)
|
|
91
|
+
self._thread.join()
|
|
92
|
+
self._raise()
|
|
93
|
+
assert self._result is not None
|
|
94
|
+
return self._result
|
|
95
|
+
|
|
96
|
+
def _work(self) -> None:
|
|
97
|
+
finalize = True
|
|
98
|
+
while (item := self._queue.get()) is not _DONE and item is not None:
|
|
99
|
+
if self._error is None:
|
|
100
|
+
try:
|
|
101
|
+
self.stitcher.add(*item)
|
|
102
|
+
except Exception as e: # noqa: BLE001 re-raised from put/finalize
|
|
103
|
+
logger.exception("stitcher failed")
|
|
104
|
+
self._error = e
|
|
105
|
+
if item is None:
|
|
106
|
+
finalize = False
|
|
107
|
+
if finalize and self._error is None:
|
|
108
|
+
try:
|
|
109
|
+
self._result = self.stitcher.finalize()
|
|
110
|
+
except Exception as e: # noqa: BLE001 re-raised from finalize
|
|
111
|
+
logger.exception("stitcher failed to finalize")
|
|
112
|
+
self._error = e
|
|
113
|
+
|
|
114
|
+
def _raise(self) -> None:
|
|
115
|
+
if self._error is not None:
|
|
116
|
+
raise RuntimeError("stitcher failed") from self._error
|
|
117
|
+
|
|
118
|
+
def close(self) -> None:
|
|
119
|
+
"""Stop without finalizing (e.g. after an error upstream)."""
|
|
120
|
+
if self._thread.is_alive():
|
|
121
|
+
self._queue.put(None)
|
|
122
|
+
self._thread.join()
|
|
123
|
+
|
|
124
|
+
def __enter__(self) -> Self:
|
|
125
|
+
return self
|
|
126
|
+
|
|
127
|
+
def __exit__(
|
|
128
|
+
self,
|
|
129
|
+
exc_type: type[BaseException] | None,
|
|
130
|
+
exc: BaseException | None,
|
|
131
|
+
tb: TracebackType | None,
|
|
132
|
+
) -> None:
|
|
133
|
+
self.close()
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
"""Detection stitcher: tile detections to slide-level objects, each reported once.
|
|
2
|
+
|
|
3
|
+
Decoding. Boxes are read as the card says (``xyxy`` or ``cxcywh``, tile ``pixel``s or
|
|
4
|
+
``normalised`` to the tile size), turned into ``xyxy`` and moved from tile pixels at the
|
|
5
|
+
model's mpp to level-0 pixels: ``level0 = (tile_origin_model + box) * downsample``.
|
|
6
|
+
Detections below the score threshold (the stitcher's, else the card's) are dropped.
|
|
7
|
+
|
|
8
|
+
Ownership. A detection is kept only by the tile whose core contains its box centre. Cores
|
|
9
|
+
partition the slide, so a detection that every overlapping tile sees whole, at the same
|
|
10
|
+
centre, is reported exactly once. That holds for every object whose half-size is at most
|
|
11
|
+
``overlap // 2`` model pixels (objects up to about ``overlap`` wide): its owning tile's core
|
|
12
|
+
lies ``overlap // 2`` inside the tile, so the owner sees it whole. Larger objects may be
|
|
13
|
+
cut by tile edges, shift their predicted centre into a neighbour's core and be reported
|
|
14
|
+
twice; a warning is logged when the grid's overlap is below the card's
|
|
15
|
+
``recommended_overlap``.
|
|
16
|
+
|
|
17
|
+
NMS (optional, ``nms_iou``). For those larger objects, detections whose centre lies within
|
|
18
|
+
``overlap`` model pixels of an interior core edge go through class-aware NMS against
|
|
19
|
+
detections from other tiles (STRtree candidate pairs, greedy by score). Detections from
|
|
20
|
+
the same tile are never suppressed against each other: that is the model's job. Two tiles
|
|
21
|
+
see an object of width ``W`` cut at their own edges, so their boxes share only the
|
|
22
|
+
``overlap`` strip: IoU is about ``overlap / W``, and NMS removes the duplicate only when
|
|
23
|
+
``nms_iou`` is below that. Objects cut by two seams (a corner) overlap less still. Raising
|
|
24
|
+
the overlap is the dependable fix; NMS is the fallback.
|
|
25
|
+
|
|
26
|
+
Scale. Everything is held as NumPy columns (one chunk per batch, joined once); writers
|
|
27
|
+
read them as columns too (``io.objects.ObjectTable``), so no Python object per detection
|
|
28
|
+
exists.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
from dataclasses import dataclass
|
|
32
|
+
from typing import Any, Literal
|
|
33
|
+
|
|
34
|
+
import numpy as np
|
|
35
|
+
import shapely
|
|
36
|
+
import torch
|
|
37
|
+
from loguru import logger
|
|
38
|
+
from numpy.typing import NDArray
|
|
39
|
+
|
|
40
|
+
from pathoinfer.registry.model_card import DetectionCard
|
|
41
|
+
from pathoinfer.runtime.base import Outputs
|
|
42
|
+
from pathoinfer.stitch.base import StitchResult
|
|
43
|
+
from pathoinfer.tiling.grid import SlideGrid, TileSpec
|
|
44
|
+
|
|
45
|
+
Geometry = Literal["point", "box"]
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass(frozen=True)
|
|
49
|
+
class Detections:
|
|
50
|
+
"""Slide-level detections as columns, level-0 pixels."""
|
|
51
|
+
|
|
52
|
+
boxes: NDArray[np.float64]
|
|
53
|
+
scores: NDArray[np.float32]
|
|
54
|
+
labels: NDArray[np.int64]
|
|
55
|
+
class_probs: NDArray[np.float32] | None = None
|
|
56
|
+
|
|
57
|
+
def __len__(self) -> int:
|
|
58
|
+
return len(self.scores)
|
|
59
|
+
|
|
60
|
+
def centroids(self) -> NDArray[np.float64]:
|
|
61
|
+
return (self.boxes[:, :2] + self.boxes[:, 2:]) / 2
|
|
62
|
+
|
|
63
|
+
def geometries(self, kind: Geometry = "box") -> NDArray[np.object_]:
|
|
64
|
+
"""Vectorised shapely Points (box centres) or box Polygons."""
|
|
65
|
+
if kind == "point":
|
|
66
|
+
return np.asarray(shapely.points(self.centroids()))
|
|
67
|
+
return np.asarray(shapely.box(*self.boxes.T))
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@dataclass
|
|
71
|
+
class _Chunk:
|
|
72
|
+
boxes: NDArray[np.float64]
|
|
73
|
+
scores: NDArray[np.float32]
|
|
74
|
+
labels: NDArray[np.int64]
|
|
75
|
+
probs: NDArray[np.float32] | None
|
|
76
|
+
tiles: NDArray[np.int64]
|
|
77
|
+
near_edge: NDArray[np.bool_]
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class DetectionStitcher:
|
|
81
|
+
def __init__(
|
|
82
|
+
self,
|
|
83
|
+
card: DetectionCard,
|
|
84
|
+
grid: SlideGrid,
|
|
85
|
+
*,
|
|
86
|
+
score_threshold: float | None = None,
|
|
87
|
+
nms_iou: float | None = None,
|
|
88
|
+
) -> None:
|
|
89
|
+
self.card, self.grid = card, grid
|
|
90
|
+
self.threshold = card.output.score_threshold if score_threshold is None else score_threshold
|
|
91
|
+
self.nms_iou = nms_iou
|
|
92
|
+
self.margin = grid.overlap * grid.downsample
|
|
93
|
+
recommended = round(card.recommended_overlap * grid.tile_size)
|
|
94
|
+
if grid.overlap < recommended:
|
|
95
|
+
logger.warning(
|
|
96
|
+
"grid overlap {} px is below the card's recommended {} px; objects wider than "
|
|
97
|
+
"about the overlap may be reported twice (consider nms_iou)",
|
|
98
|
+
grid.overlap,
|
|
99
|
+
recommended,
|
|
100
|
+
)
|
|
101
|
+
self._chunks: list[_Chunk] = []
|
|
102
|
+
|
|
103
|
+
def add(self, specs: list[TileSpec], outputs: Outputs) -> None:
|
|
104
|
+
out, grid = self.card.output, self.grid
|
|
105
|
+
scores = _numpy(outputs[out.scores]).astype(np.float32)
|
|
106
|
+
b, d = np.nonzero(scores >= self.threshold)
|
|
107
|
+
if len(b) == 0:
|
|
108
|
+
return
|
|
109
|
+
boxes = _numpy(outputs[out.boxes])[b, d].astype(np.float64)
|
|
110
|
+
if out.box_format == "cxcywh":
|
|
111
|
+
half = boxes[:, 2:] / 2
|
|
112
|
+
boxes = np.concatenate([boxes[:, :2] - half, boxes[:, :2] + half], axis=1)
|
|
113
|
+
if out.box_units == "normalised":
|
|
114
|
+
boxes *= grid.tile_size
|
|
115
|
+
tiles = np.array([[s.xm, s.ym, *_core(s), s.row * grid.n_cols + s.col] for s in specs])
|
|
116
|
+
origins = tiles[b, :2]
|
|
117
|
+
boxes = (boxes + np.concatenate([origins, origins], axis=1)) * grid.downsample
|
|
118
|
+
centre = (boxes[:, :2] + boxes[:, 2:]) / 2
|
|
119
|
+
x0, y0, x1, y1 = tiles[b, 2:6].T
|
|
120
|
+
owned = (
|
|
121
|
+
(centre[:, 0] >= x0) & (centre[:, 0] < x1) & (centre[:, 1] >= y0) & (centre[:, 1] < y1)
|
|
122
|
+
)
|
|
123
|
+
interior = np.array([_interior_edges(s, grid) for s in specs])[b]
|
|
124
|
+
gaps = np.stack(
|
|
125
|
+
[centre[:, 0] - x0, centre[:, 1] - y0, x1 - centre[:, 0], y1 - centre[:, 1]], axis=1
|
|
126
|
+
)
|
|
127
|
+
near_edge = (np.where(interior, gaps, np.inf) < self.margin).any(axis=1)
|
|
128
|
+
probs = None
|
|
129
|
+
if out.class_probs is not None:
|
|
130
|
+
probs = _numpy(outputs[out.class_probs])[b, d].astype(np.float32)[owned]
|
|
131
|
+
self._chunks.append(
|
|
132
|
+
_Chunk(
|
|
133
|
+
boxes=boxes[owned],
|
|
134
|
+
scores=scores[b, d][owned],
|
|
135
|
+
labels=_numpy(outputs[out.labels])[b, d].astype(np.int64)[owned],
|
|
136
|
+
probs=probs,
|
|
137
|
+
tiles=tiles[b, 6].astype(np.int64)[owned],
|
|
138
|
+
near_edge=near_edge[owned],
|
|
139
|
+
)
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
def finalize(self) -> StitchResult:
|
|
143
|
+
detections = self._join()
|
|
144
|
+
if self.nms_iou is not None and len(detections.scores):
|
|
145
|
+
keep = np.ones(len(detections.scores), bool)
|
|
146
|
+
candidates = np.flatnonzero(detections.near_edge)
|
|
147
|
+
suppressed = _nms(
|
|
148
|
+
detections.boxes[candidates],
|
|
149
|
+
detections.scores[candidates],
|
|
150
|
+
detections.labels[candidates],
|
|
151
|
+
detections.tiles[candidates],
|
|
152
|
+
self.nms_iou,
|
|
153
|
+
)
|
|
154
|
+
keep[candidates[suppressed]] = False
|
|
155
|
+
detections = _Chunk(
|
|
156
|
+
detections.boxes[keep],
|
|
157
|
+
detections.scores[keep],
|
|
158
|
+
detections.labels[keep],
|
|
159
|
+
None if detections.probs is None else detections.probs[keep],
|
|
160
|
+
detections.tiles[keep],
|
|
161
|
+
detections.near_edge[keep],
|
|
162
|
+
)
|
|
163
|
+
logger.info("detection: {} objects", len(detections.scores))
|
|
164
|
+
return StitchResult(
|
|
165
|
+
features=[],
|
|
166
|
+
detections=Detections(
|
|
167
|
+
detections.boxes, detections.scores, detections.labels, detections.probs
|
|
168
|
+
),
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
def _join(self) -> _Chunk:
|
|
172
|
+
if not self._chunks:
|
|
173
|
+
n = self.card.output
|
|
174
|
+
empty_probs = (
|
|
175
|
+
None if n.class_probs is None else np.empty((0, len(self.card.classes)), np.float32)
|
|
176
|
+
)
|
|
177
|
+
return _Chunk(
|
|
178
|
+
np.empty((0, 4)),
|
|
179
|
+
np.empty(0, np.float32),
|
|
180
|
+
np.empty(0, np.int64),
|
|
181
|
+
empty_probs,
|
|
182
|
+
np.empty(0, np.int64),
|
|
183
|
+
np.empty(0, bool),
|
|
184
|
+
)
|
|
185
|
+
c = self._chunks
|
|
186
|
+
probs = None if c[0].probs is None else np.concatenate([x.probs for x in c])
|
|
187
|
+
return _Chunk(
|
|
188
|
+
np.concatenate([x.boxes for x in c]),
|
|
189
|
+
np.concatenate([x.scores for x in c]),
|
|
190
|
+
np.concatenate([x.labels for x in c]),
|
|
191
|
+
probs,
|
|
192
|
+
np.concatenate([x.tiles for x in c]),
|
|
193
|
+
np.concatenate([x.near_edge for x in c]),
|
|
194
|
+
)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _numpy(tensor: torch.Tensor) -> NDArray[Any]:
|
|
198
|
+
return tensor.detach().cpu().numpy()
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _core(spec: TileSpec) -> tuple[int, int, int, int]:
|
|
202
|
+
return spec.core.x0, spec.core.y0, spec.core.x1, spec.core.y1
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _interior_edges(spec: TileSpec, grid: SlideGrid) -> tuple[bool, bool, bool, bool]:
|
|
206
|
+
"""Which core edges (left, top, right, bottom) face a neighbour, not the slide edge."""
|
|
207
|
+
return spec.col > 0, spec.row > 0, spec.col < grid.n_cols - 1, spec.row < grid.n_rows - 1
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _nms(
|
|
211
|
+
boxes: NDArray[np.float64],
|
|
212
|
+
scores: NDArray[np.float32],
|
|
213
|
+
labels: NDArray[np.int64],
|
|
214
|
+
tiles: NDArray[np.int64],
|
|
215
|
+
iou_threshold: float,
|
|
216
|
+
) -> NDArray[np.int64]:
|
|
217
|
+
"""Indices suppressed by greedy class-aware NMS between detections of different tiles."""
|
|
218
|
+
if len(scores) < 2:
|
|
219
|
+
return np.empty(0, np.int64)
|
|
220
|
+
tree = shapely.STRtree(shapely.box(*boxes.T))
|
|
221
|
+
i, j = tree.query(shapely.box(*boxes.T))
|
|
222
|
+
pair = (i < j) & (labels[i] == labels[j]) & (tiles[i] != tiles[j])
|
|
223
|
+
i, j = i[pair], j[pair]
|
|
224
|
+
lo = np.maximum(boxes[i, :2], boxes[j, :2])
|
|
225
|
+
hi = np.minimum(boxes[i, 2:], boxes[j, 2:])
|
|
226
|
+
inter = np.clip(hi - lo, 0, None).prod(axis=1)
|
|
227
|
+
area = (boxes[:, 2:] - boxes[:, :2]).prod(axis=1)
|
|
228
|
+
iou = inter / (area[i] + area[j] - inter)
|
|
229
|
+
i, j = i[iou > iou_threshold], j[iou > iou_threshold]
|
|
230
|
+
# Each pair as (stronger, weaker); ties go to the lower index, as a stable sort would.
|
|
231
|
+
stronger_i = (scores[i] > scores[j]) | ((scores[i] == scores[j]) & (i < j))
|
|
232
|
+
strong, weak = np.where(stronger_i, i, j), np.where(stronger_i, j, i)
|
|
233
|
+
order = np.argsort(strong, kind="stable")
|
|
234
|
+
strong, weak = strong[order], weak[order]
|
|
235
|
+
starts = np.searchsorted(strong, np.arange(len(scores)))
|
|
236
|
+
ends = np.searchsorted(strong, np.arange(len(scores)), side="right")
|
|
237
|
+
suppressed = np.zeros(len(scores), bool)
|
|
238
|
+
for k in np.argsort(-scores, kind="stable"):
|
|
239
|
+
if not suppressed[k] and starts[k] < ends[k]:
|
|
240
|
+
suppressed[weak[starts[k] : ends[k]]] = True
|
|
241
|
+
return np.flatnonzero(suppressed)
|