Skip to content

Commit 16ba015

Browse files
committed
add docstrings
1 parent 159959f commit 16ba015

6 files changed

Lines changed: 22 additions & 0 deletions

File tree

tests/engines/test_multi_task_segmentor.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1273,6 +1273,7 @@ def fake_store_probabilities(
12731273
*_: Any, # noqa: ANN401
12741274
**__: Any, # noqa: ANN401
12751275
) -> tuple[zarr.Array | None, da.Array | None]:
1276+
"""Record unexpected probability-store calls during merge tests."""
12761277
nonlocal called_store
12771278
called_store = True
12781279
return None, None
@@ -1719,26 +1720,31 @@ def test_post_save_json_store_deletes_empty_store(
17191720
# ---- Proxy object that LOOKS like a zarr.Group ----
17201721
class GroupProxy:
17211722
def __init__(self: GroupProxy, group: zarr.Group, path: Path | str) -> None:
1723+
"""Wrap a Zarr group with a path used by cleanup code."""
17221724
self._group = group
17231725
self.path = path
17241726
self.store = group.store
17251727

17261728
# Make isinstance(proxy, zarr.Group) return True
17271729
@property
17281730
def __class__(self: GroupProxy) -> type[zarr.Group]:
1731+
"""Expose the wrapped object as a Zarr group for isinstance."""
17291732
return zarr.Group
17301733

17311734
# Delegate attribute access
17321735
def __getattr__(
17331736
self: GroupProxy, item: str
17341737
) -> zarr.Group | zarr.Array | str | int | float | Iterable[str]:
1738+
"""Delegate unknown attributes to the wrapped Zarr group."""
17351739
return getattr(self._group, item)
17361740

17371741
# Delegate mapping behavior
17381742
def keys(self: GroupProxy) -> Iterable[str]:
1743+
"""Return keys from the wrapped Zarr group."""
17391744
return self._group.keys()
17401745

17411746
def __getitem__(self: GroupProxy, item: str) -> zarr.Group | zarr.Array:
1747+
"""Return an item from the wrapped Zarr group."""
17421748
return self._group[item]
17431749

17441750
processed_predictions = GroupProxy(root, "dummy")
@@ -1747,6 +1753,7 @@ def __getitem__(self: GroupProxy, item: str) -> zarr.Group | zarr.Array:
17471753
called = {"flag": False}
17481754

17491755
def fake_rmtree(path: Path | str, *, ignore_errors: bool) -> None: # noqa: ARG001
1756+
"""Record that cleanup attempted to remove an empty Zarr store."""
17501757
called["flag"] = True
17511758

17521759
monkeypatch.setattr(shutil, "rmtree", fake_rmtree)
@@ -1830,6 +1837,7 @@ def fake_save_qupath_json(
18301837
save_path: Path | None, # noqa: ARG001
18311838
qupath_json: dict[str, Any],
18321839
) -> dict[str, Any]:
1840+
"""Return generated QuPath JSON instead of writing it to disk."""
18331841
return qupath_json
18341842

18351843
monkeypatch.setattr(
@@ -1866,6 +1874,7 @@ def _build_single_qupath_feature(
18661874
scale_factor: tuple[float, float],
18671875
class_colors: dict[int, Any],
18681876
) -> dict[str, Any]:
1877+
"""Delegate feature construction to the production JSON store."""
18691878
return DaskDelayedJSONStore._build_single_qupath_feature(
18701879
self, i, class_dict, origin, scale_factor, class_colors
18711880
)

tests/models/test_arch_cerberus.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ def _mock_torch_load(
4141
*_args: object,
4242
**_kwargs: object,
4343
) -> dict[str, dict[str, torch.Tensor]]:
44+
"""Return a synthetic Cerberus checkpoint for load-weight tests."""
4445
return checkpoint
4546

4647
monkeypatch.setattr(torch, "load", _mock_torch_load)
@@ -63,6 +64,7 @@ def _mock_torch_load(
6364
*_args: object,
6465
**_kwargs: object,
6566
) -> dict[str, dict[str, torch.Tensor]]:
67+
"""Return a synthetic Cerberus checkpoint for registry loading."""
6668
return checkpoint
6769

6870
monkeypatch.setattr(torch, "load", _mock_torch_load)
@@ -153,6 +155,7 @@ def _mock_post_process(
153155
tissue_mode: str,
154156
ds_factor: float,
155157
) -> tuple[np.ndarray, np.ndarray | None]:
158+
"""Return deterministic task maps for Cerberus postproc testing."""
156159
calls.append((tissue_mode, raw_map.shape, idx_dict, ds_factor))
157160
inst_map = np.zeros(output_shape, dtype=np.int32)
158161
type_map = np.ones(output_shape, dtype=np.uint8)
@@ -172,6 +175,7 @@ def _mock_get_instance_info(
172175
offset: tuple[int, int],
173176
verbose: object,
174177
) -> dict[int, dict]:
178+
"""Return deterministic instance metadata for Cerberus postproc tests."""
175179
assert offset == (7, 11)
176180
assert verbose is False
177181
type_value = 0 if type_map is None else int(type_map[inst_map > 0][0])

tiatoolbox/models/architecture/cerberus/backbone/resnet.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,7 @@ def _make_layer(
8383
blocks: int,
8484
stride: int = 1,
8585
) -> nn.Sequential:
86+
"""Build one ResNet stage with optional downsampling."""
8687
downsample = None
8788
if stride != 1 or self.inplanes != planes * BasicBlock.expansion:
8889
downsample = nn.Sequential(

tiatoolbox/models/architecture/cerberus/model.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,7 @@ def postproc(
185185

186186

187187
def _strip_dataparallel_prefix(state: dict) -> dict:
188+
"""Remove ``module.`` prefixes from DataParallel checkpoint keys."""
188189
if all(key.split(".")[0] == "module" for key in state):
189190
return {".".join(key.split(".")[1:]): value for key, value in state.items()}
190191
return state
@@ -194,6 +195,7 @@ def _crop_center_tensor(
194195
tensor: torch.Tensor,
195196
output_shape: tuple[int, int],
196197
) -> torch.Tensor:
198+
"""Crop a BHWC tensor to the requested center output shape."""
197199
h, w = tensor.shape[1:3]
198200
out_h, out_w = output_shape
199201
top = max((h - out_h) // 2, 0)
@@ -204,6 +206,7 @@ def _crop_center_tensor(
204206
def _build_tissue_raw_map(
205207
head_map: dict[str, np.ndarray], tissue_name: str
206208
) -> tuple[np.ndarray, dict[str, list[int]]]:
209+
"""Combine Cerberus heads for one tissue into a raw postproc map."""
207210
idx_dict = {}
208211
maps = []
209212
start = 0
@@ -223,6 +226,7 @@ def _build_tissue_raw_map(
223226

224227

225228
def _inst_dict_for_dask_processing(inst_info_dict: dict, *, is_dask: bool) -> dict:
229+
"""Convert instance metadata into arrays with optional Dask wrapping."""
226230
if not inst_info_dict:
227231
output = {
228232
"box": np.empty((0, 4), dtype=np.int32),

tiatoolbox/models/architecture/cerberus/postproc.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ class PostProcInstErodedContourMap:
2626

2727
@staticmethod
2828
def _proc_gland(inst_fg: np.ndarray, ds_factor: float = 1.0) -> np.ndarray:
29+
"""Extract labelled gland instances from inner and contour maps."""
2930
ksize = int((11 - 1) * ds_factor)
3031
k_disk = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (ksize, ksize))
3132

@@ -44,6 +45,7 @@ def _proc_gland(inst_fg: np.ndarray, ds_factor: float = 1.0) -> np.ndarray:
4445

4546
@staticmethod
4647
def _proc_lumen(inst_fg: np.ndarray, ds_factor: float = 1.0) -> np.ndarray:
48+
"""Extract labelled lumen instances from inner and contour maps."""
4749
ksize = int((3 - 1) * ds_factor)
4850
k_disk = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (ksize, ksize))
4951

@@ -62,6 +64,7 @@ def _proc_lumen(inst_fg: np.ndarray, ds_factor: float = 1.0) -> np.ndarray:
6264

6365
@staticmethod
6466
def _proc_nuclei(inst_fg: np.ndarray, ds_factor: float = 1.0) -> np.ndarray:
67+
"""Extract labelled nuclei instances from inner and contour maps."""
6568
_ = ds_factor
6669
k_disk = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
6770

tiatoolbox/models/engine/multi_task_segmentor.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4104,6 +4104,7 @@ def _post_save_json_store(
41044104
save_path: Path | None,
41054105
**kwargs: Unpack[MultiTaskSegmentorRunParams],
41064106
) -> None:
4107+
"""Clean temporary JSON-store data and report unsupported probability saves."""
41074108
for key in keys_to_compute:
41084109
del processed_predictions[key]
41094110

0 commit comments

Comments
 (0)