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,101 @@
1
+ """Pyramidal TIFFs of rasters (label maps, heatmaps) that slide readers open.
2
+
3
+ A generic tiled pyramid, as OpenSlide reads it ("generic-tiff"), and so fastslide and
4
+ QuPath: every level is its own top-level image, full resolution first, each next one
5
+ halved until it fits one tile (floats area-averaged, integers by nearest neighbour).
6
+ Levels stored as SubIFDs are invisible to OpenSlide, which then sees one level. Tiles
7
+ are 256 px, zlib-compressed. Resolution tags give each level's pixel size, which the
8
+ readers report as mpp; the first level's ImageDescription holds the level-0 transform
9
+ (``level0_per_px``, ``origin``) and the run metadata as JSON. A raster whose first pixel
10
+ starts away from the slide's corner (heatmaps start half an overlap in) also gets
11
+ XPosition/YPosition tags, in centimetres like the resolution.
12
+
13
+ Integer rasters (label maps) are written as 8-bit: OpenSlide decodes through 8-bit
14
+ RGBA and reads 16-bit as zeros. Class ids stay as they are, and ``NODATA`` (255) marks
15
+ pixels no tile reached (-1 in the raster). Float rasters stay float32, which tifffile
16
+ and Bio-Formats read but OpenSlide and fastslide do not.
17
+ """
18
+
19
+ import json
20
+ import os
21
+ from fractions import Fraction
22
+ from pathlib import Path
23
+ from typing import Any
24
+
25
+ import cv2
26
+ import numpy as np
27
+ import tifffile
28
+ from loguru import logger
29
+ from numpy.typing import NDArray
30
+
31
+ from pathoinfer._logging import log_call
32
+ from pathoinfer.io.objects import RunInfo
33
+ from pathoinfer.stitch.base import Raster
34
+
35
+ TILE = 256
36
+ NODATA = 255
37
+
38
+
39
+ @log_call
40
+ def write_tiff(path: str | Path, raster: Raster, run: RunInfo) -> Path:
41
+ """Write a 2D ``raster``; its ``origin`` (level-0 px) goes into the description and,
42
+ when not (0, 0), the position tags."""
43
+ path = Path(path)
44
+ if raster.array.ndim != 2:
45
+ raise ValueError(f"expected a 2D raster, got shape {raster.array.shape}")
46
+ levels = _pyramid(_storable(raster.array))
47
+ um_per_px = run.slide_mpp * raster.scale
48
+ description = json.dumps(
49
+ {
50
+ "level0_per_px": raster.scale,
51
+ "um_per_px": um_per_px,
52
+ "origin": list(raster.origin),
53
+ "run": run.to_dict(),
54
+ }
55
+ )
56
+ position = []
57
+ if raster.origin != (0.0, 0.0):
58
+ cm = [Fraction(v * run.slide_mpp / 1e4).limit_denominator(10**9) for v in raster.origin]
59
+ position = [
60
+ (tag, 5, 1, (f.numerator, f.denominator), True)
61
+ for tag, f in zip((286, 287), cm, strict=True)
62
+ ]
63
+ partial = path.with_name(path.name + ".partial")
64
+ with tifffile.TiffWriter(partial, bigtiff=True) as tif:
65
+ for i, level in enumerate(levels):
66
+ px_per_cm = 1e4 / um_per_px * level.shape[1] / raster.array.shape[1]
67
+ tif.write(
68
+ level,
69
+ tile=(TILE, TILE),
70
+ compression="zlib",
71
+ photometric="minisblack",
72
+ resolution=(px_per_cm, px_per_cm),
73
+ resolutionunit="CENTIMETER",
74
+ subfiletype=1 if i else 0, # reduced-resolution image
75
+ description=description if i == 0 else None,
76
+ metadata=None,
77
+ extratags=position,
78
+ )
79
+ os.replace(partial, path)
80
+ logger.info("wrote {} ({} levels)", path, len(levels))
81
+ return path
82
+
83
+
84
+ def _storable(array: NDArray[Any]) -> NDArray[Any]:
85
+ """Integer rasters as uint8 (-1 -> ``NODATA``); floats as float32."""
86
+ if not np.issubdtype(array.dtype, np.integer):
87
+ return array.astype(np.float32, copy=False)
88
+ if array.size and (array.min() < -1 or array.max() >= NODATA):
89
+ raise ValueError(f"label values must be -1 to {NODATA - 1} to fit 8 bits")
90
+ return np.where(array < 0, NODATA, array).astype(np.uint8)
91
+
92
+
93
+ def _pyramid(array: NDArray[Any]) -> list[NDArray[Any]]:
94
+ integer = np.issubdtype(array.dtype, np.integer)
95
+ levels = [array]
96
+ while max(levels[-1].shape) > TILE:
97
+ h, w = levels[-1].shape
98
+ size = (max(1, w // 2), max(1, h // 2))
99
+ interpolation = cv2.INTER_NEAREST if integer else cv2.INTER_AREA
100
+ levels.append(np.asarray(cv2.resize(levels[-1], size, interpolation=interpolation)))
101
+ return levels
@@ -0,0 +1,116 @@
1
+ # pathoinfer - post
2
+
3
+ Post-processing shared by the stitchers. Today that is one module, `vectorise.py`: label
4
+ masks to polygons. The segmentation stitcher (per band, then across band seams) and the
5
+ heatmap stitcher (thresholded core grids) both use it, so their polygons follow the same
6
+ rules.
7
+
8
+ | Module | Status |
9
+ |---|---|
10
+ | `vectorise.py` | Masks to level-0 polygons with holes; used by `stitch/segmentation.py` and `stitch/heatmap.py` |
11
+ | `nms.py` | Empty stub. Cross-tile NMS for detections lives in `stitch/detection.py` (`_nms`) |
12
+ | `smoothing.py` | Empty stub. Polygon smoothing is `vectorise.shape_borders`; heatmap smoothing is in `stitch/heatmap.py` |
13
+
14
+ ## Usage
15
+
16
+ ```python
17
+ import numpy as np
18
+ from pathoinfer.post.vectorise import vectorise
19
+
20
+ mask = np.zeros((100, 100), bool)
21
+ mask[20:60, 30:80] = True # one region, 40 x 50 mask pixels
22
+ mask[35:40, 50:55] = False # with a 5 x 5 hole
23
+ probs = np.where(mask, 0.9, 0.1).astype(np.float32)
24
+
25
+ (feature,) = vectorise(
26
+ mask,
27
+ probs,
28
+ class_id=1,
29
+ class_name="tumour",
30
+ level0_per_px=8.0, # one mask pixel = 8 x 8 level-0 px
31
+ slide_mpp=0.25, # microns per level-0 pixel
32
+ )
33
+ feature.geometry.bounds # (240.0, 160.0, 640.0, 480.0), level-0 px
34
+ feature.measurements # area_um2 7894.3, perimeter_um 390.9, mean_probability 0.9
35
+ ```
36
+
37
+ The pixel count gives 7900 µm² (1975 px of 64 level-0 px² at 0.25 µm). With
38
+ `simplify_px=0, smooth=0` the polygon measures exactly that; the default smoothing rounds
39
+ each corner by about a pixel and measures 7894.3.
40
+
41
+ Mask pixel `(col, row)` covers level-0 `origin + level0_per_px * (col, row)` to
42
+ `origin + level0_per_px * (col + 1, row + 1)`; pass `origin` when the mask does not start
43
+ at the slide's corner (heatmap core grids start half an overlap in).
44
+
45
+ ## Steps
46
+
47
+ Each step is public, so a stitcher can run them on band pieces and merge in between.
48
+
49
+ | Function | Does |
50
+ |---|---|
51
+ | `regions(mask, values, class_id, top, connectivity=8)` | One `Piece` per connected region, with holes, in mask pixels (`top` offsets the rows of a band): the exact union of its pixels. `Piece` keeps the sum of `values` and the pixel count for `mean_probability`. |
52
+ | `merge(pieces, connectivity=8)` | Unions same-class pieces that touch (a region cut by band boundaries): along an edge, or with 8 also at a corner. |
53
+ | `fill_holes(pieces, max_px)` | Fills holes under `max_px` mask px² unless another class has a polygon inside (also one that leaves the hole through a pixel corner), and drops same-class islands inside the filled holes. Returns the pieces and the filled holes (to paint a label map the same way). |
54
+ | `to_features(pieces, names, level0_per_px=..., slide_mpp=..., origin=..., simplify_px=1.5, smooth=2)` | All pieces together: `shape_borders`, then make valid, scale to level 0, round to 0.1 px, and measure `area_um2`, `perimeter_um` and `mean_probability`. `names` maps class ids to names. |
55
+ | `shape_borders(geometries, simplify_px, rounds)` | Simplifies (Douglas-Peucker) and smooths (edges split to at most 4 px, `chaikin`, then simplified at 0.1 px) every border once, so neighbouring regions keep one shared line (see below). |
56
+ | `vectorise(mask, values, class_id, name, ...)` | All of the above on one whole mask, plus `fill_holes_um2` and `connectivity`. |
57
+ | `chaikin(points, rounds, closed=...)` | Chaikin corner cutting on a polyline: each round doubles the vertices and cuts a quarter of each edge from every corner; an open line keeps its ends. Edges are split to at most 4 px first, so a cut is at most about a pixel. |
58
+ | `polygonal(geometry)` | The Polygon or MultiPolygon parts of a geometry, or None. |
59
+
60
+ ## Shared borders
61
+
62
+ Where two classes meet, both polygons must use the same line, or the outlines overlap
63
+ and leave gaps. Simplifying and smoothing each polygon on its own moves each copy of
64
+ a shared border differently: on a real slide that left 1% of the polygon area
65
+ overlapping. `shape_borders` works on the borders instead:
66
+
67
+ 1. Edges are split at every pixel, so a border has the same vertices from both sides.
68
+ 2. Borders are cut into arcs at junctions: vertices with other than two distinct edges
69
+ (three regions meeting, or regions touching at a pixel corner). A border with no
70
+ junction is a loop (an island and the hole around it).
71
+ 3. Each distinct arc is simplified and smoothed once with its ends fixed, in a canonical
72
+ direction (from its smaller end; a loop from its smallest vertex), and every region
73
+ on it takes that result. The steps are symmetric in floating point.
74
+ 4. Arcs about a pixel apart, such as both sides of a 1 px strand, can still cross after
75
+ simplifying. An arc that touches another anywhere but at their shared ends steps back
76
+ to smoothing only, then to its exact pixel line, until no arcs cross.
77
+
78
+ Polygons then overlap only by the 0.1 px rounding (`tests/post/test_vectorise.py`).
79
+
80
+ ## How outlines are traced
81
+
82
+ A region is the exact union of its pixels. `cv2.connectedComponents` labels the regions;
83
+ each row's runs of one label become rectangles, stacked over rows where a run repeats,
84
+ and each region's rectangles are unioned. Areas equal pixel counts, outlines lie on pixel
85
+ edges, and holes keep their corners. On a 2048 x 2048 noisy mask this takes 2.0 s, where
86
+ the previous tracing (contours through pixel centres, widened by half a pixel) took
87
+ 11.4 s and came out 2-4% too large.
88
+
89
+ `connectivity` decides whether parts that touch only at a pixel corner are one region:
90
+
91
+ | | 8 (default) | 4 |
92
+ |---|---|---|
93
+ | Two squares touching at a corner | one region, a MultiPolygon meeting at that point | two regions |
94
+ | A one-pixel diagonal line | one region | one region per pixel |
95
+ | Background reaching outside only through a corner | outside | a hole |
96
+
97
+ On a real slide (dark-pixel model at 2 µm, `min_area_um2: 500`) 8 kept 9.44 mm² in 607
98
+ regions and 4 kept 8.94 mm² in 851: under 4, diagonal strands of tissue break into
99
+ pixels and fall under `min_area_um2`.
100
+
101
+ Smoothing works at pixel scale. Simplification turns pixel staircases into diagonal runs;
102
+ edges are then split to at most 4 px so that Chaikin cuts at most about a pixel from
103
+ each corner per round, and a final 0.1 px simplification drops the near-collinear points
104
+ it leaves. A 40 x 50 px rectangle keeps 99.9% of its area; the synthetic slide's ellipse
105
+ keeps area and perimeter within 0.2% of the analytic shape with 63 vertices. Use
106
+ `smooth=0` for shapes that should keep sharp corners.
107
+
108
+ ## Testing
109
+
110
+ `tests/post/test_vectorise.py` checks that regions equal the mask's pixels exactly (random
111
+ masks, both connectivities), that holes keep their corners, that corner contacts and band
112
+ seams follow the connectivity, and that smoothing cuts about a pixel whatever the size.
113
+ Through its callers: `tests/stitch/test_segmentation.py`
114
+ (analytic disk and annulus, band seams, hole filling, small objects, smoothing),
115
+ `tests/stitch/test_heatmap.py` (checkerboard regions) and the pinned synthetic-slide
116
+ results in `tests/engine/test_regression.py`.
@@ -0,0 +1 @@
1
+ """Post-processing of stitched outputs: vectorisation, NMS, smoothing."""
@@ -0,0 +1,92 @@
1
+ """Nucleus instances from HoVer-Net style outputs: the watershed and each instance's type.
2
+
3
+ Ported from pathotrain's ``cellseg/instances.py`` (Apache-2.0, same authors), which
4
+ validates its models with this code, so inference reproduces training-time results.
5
+ Algorithm: HoVer-Net, Graham et al. 2019, "HoVer-Net: Simultaneous segmentation and
6
+ classification of nuclei in multi-tissue histology images" (written from the paper).
7
+
8
+ Inputs are one tile's maps as NumPy arrays: the nucleus probability ``(H, W)``, the HV
9
+ maps ``(2, H, W)`` and the type logits ``(C, H, W)``. An instance map is ``(H, W)``
10
+ int32, 0 for background and one id per nucleus.
11
+ """
12
+
13
+ import math
14
+
15
+ import numpy as np
16
+ from numpy.typing import NDArray
17
+ from scipy import ndimage as ndi
18
+ from skimage.segmentation import watershed
19
+
20
+ # HoVer-Net takes HV-map gradients with a 21 px Sobel kernel (cv2), whose smoothing is a
21
+ # binomial of variance 20 / 4 = 5: here a Gaussian derivative of that sigma. The maps
22
+ # are min-max scaled afterwards, so the kernel's scale does not matter.
23
+ SOBEL_SIGMA = math.sqrt(5)
24
+ DISK = np.hypot(*np.mgrid[-2:3, -2:3]) <= 2.5 # 5 x 5 ellipse, HoVer-Net's marker opening
25
+
26
+
27
+ def softmax(logits: NDArray[np.floating], axis: int = 0) -> NDArray[np.float32]:
28
+ shifted = np.exp(logits - logits.max(axis, keepdims=True))
29
+ return (shifted / shifted.sum(axis, keepdims=True)).astype(np.float32)
30
+
31
+
32
+ def _minmax(x: NDArray[np.floating]) -> NDArray[np.floating]:
33
+ span = x.max() - x.min()
34
+ return (x - x.min()) / span if span > 0 else np.zeros_like(x)
35
+
36
+
37
+ def _remove_small(labels: NDArray[np.integer], min_size: int) -> NDArray[np.integer]:
38
+ sizes = np.bincount(labels.ravel())
39
+ small = sizes < min_size
40
+ small[0] = False
41
+ return np.where(small[labels], 0, labels)
42
+
43
+
44
+ def watershed_instances(
45
+ foreground: NDArray[np.floating],
46
+ hv: NDArray[np.floating],
47
+ threshold: float = 0.5,
48
+ marker_threshold: float = 0.4,
49
+ min_size: int = 10,
50
+ ) -> NDArray[np.int32]:
51
+ """HoVer-Net's watershed: an instance map from the nucleus probability ``(H, W)`` and
52
+ the HV maps ``(2, H, W)``.
53
+
54
+ Nuclei are where ``foreground >= threshold``. The HV maps rise across a nucleus and fall
55
+ steeply between two touching ones, so their most negative gradients mark boundaries;
56
+ nucleus pixels away from them (gradient energy below ``marker_threshold``) seed a
57
+ watershed over the nuclei. Blobs and seeds under ``min_size`` pixels are dropped.
58
+ """
59
+ blobs, _ = ndi.label(foreground >= threshold)
60
+ nuclei = _remove_small(blobs, min_size) > 0
61
+ if not nuclei.any():
62
+ return np.zeros(foreground.shape, np.int32)
63
+ h, v = _minmax(hv[0]), _minmax(hv[1])
64
+ grad_h = 1 - _minmax(ndi.gaussian_filter(h, SOBEL_SIGMA, order=(0, 1)))
65
+ grad_v = 1 - _minmax(ndi.gaussian_filter(v, SOBEL_SIGMA, order=(1, 0)))
66
+ energy = np.clip(np.maximum(grad_h, grad_v) - ~nuclei, 0, None)
67
+ # HoVer-Net blurs with a 3 px kernel (cv2 sigma 0.8 for that size).
68
+ dist = -ndi.gaussian_filter((1 - energy) * nuclei, 0.8)
69
+ markers = ndi.binary_fill_holes(nuclei & (energy < marker_threshold))
70
+ markers, _ = ndi.label(ndi.binary_opening(markers, DISK))
71
+ markers = _remove_small(markers, min_size).astype(np.int32)
72
+ flooded = watershed(dist, markers, mask=nuclei) # type: ignore[no-untyped-call] # skimage
73
+ return np.asarray(flooded, np.int32)
74
+
75
+
76
+ def instance_types(
77
+ instances: NDArray[np.integer], type_logits: NDArray[np.floating]
78
+ ) -> NDArray[np.int64]:
79
+ """The type of each instance id, indexed by id (``out[0]`` is 0): the most common
80
+ per-pixel argmax of ``type_logits`` ``(C, H, W)`` under it, among types 1..C-1;
81
+ 0 when no pixel of it has one."""
82
+ n_types = type_logits.shape[0]
83
+ size = int(instances.max()) + 1
84
+ labels = type_logits.argmax(0)
85
+ counts = np.bincount(
86
+ instances.ravel().astype(np.int64) * n_types + labels.ravel(),
87
+ minlength=size * n_types,
88
+ ).reshape(size, n_types)
89
+ counts[:, 0] = 0 # background votes only when nothing else does
90
+ out = counts.argmax(1).astype(np.int64)
91
+ out[0] = 0
92
+ return out
pathoinfer/post/nms.py ADDED
@@ -0,0 +1 @@
1
+ """Non-maximum suppression across tile seams. Lands in v0.1."""
@@ -0,0 +1 @@
1
+ """Polygon and heatmap smoothing. Lands in v0.1."""