-
Notifications
You must be signed in to change notification settings - Fork 0
feat: add evaluation callbacks, metrics and analysis #9
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
58bcf58
feat: add evaluation callbacks, metrics and analysis
LAdam-ix cce0264
chore: fix lint
LAdam-ix 8aed482
feat: add mean brightness metric
LAdam-ix e50c106
fix: review ai agent feedback
LAdam-ix 0052904
fix: review ai agent feedback
LAdam-ix 8989a91
fix: review feedback
LAdam-ix e964f1f
feat: use multi-dataloader
LAdam-ix 0e53db7
fix: revert to old mlkit commit to fix broken dependecies and dataloa…
LAdam-ix 240856f
feat: add torchmetrics-based evaluation
LAdam-ix 2befe19
chore: mypy and ruff formating
LAdam-ix 69ca0e3
fix: review feedback
LAdam-ix cbc5a6c
fix: review feedback
LAdam-ix 3674c9d
fix: mypy fix
LAdam-ix 1fb3055
fix: review feedback
LAdam-ix 305f691
fix: remove global output_dir config
LAdam-ix d1a4f64
fix: split stain metric for MetricCollection
LAdam-ix e90fddd
chore: ruff formating
LAdam-ix 17e03c3
fix: disable compute_groups becase of stain metrics
LAdam-ix File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| from stain_normalization.callbacks.tiles_export import TilesExport | ||
| from stain_normalization.callbacks.wsi_assembler import WSIAssembler | ||
|
|
||
|
|
||
| __all__ = ["TilesExport", "WSIAssembler"] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,85 @@ | ||
| from pathlib import Path | ||
| from typing import Any | ||
|
|
||
| import torch | ||
| from lightning import LightningModule, Trainer | ||
| from PIL import Image | ||
|
|
||
| from lightning import Callback | ||
| from stain_normalization.type_aliases import Outputs | ||
|
|
||
|
|
||
| class TilesExport(Callback): | ||
| def __init__( | ||
| self, | ||
| output_dir: str | Path, | ||
| n_first: int = 10, | ||
| sample_rate: float = 0.0005, | ||
| ) -> None: | ||
| super().__init__() | ||
| self.output_dir = Path(output_dir) | ||
| self.output_dir.mkdir(parents=True, exist_ok=True) | ||
| self.n_first = n_first | ||
| self.sample_rate = sample_rate | ||
| self._global_count: int = 0 | ||
|
|
||
| @staticmethod | ||
| def _tensor_to_image(tensor: torch.Tensor) -> Image.Image: | ||
| return Image.fromarray(tensor.mul(255).byte().permute(1, 2, 0).cpu().numpy()) | ||
|
|
||
| def _should_save(self) -> bool: | ||
| count = self._global_count | ||
| self._global_count += 1 | ||
| if count < self.n_first: | ||
| return True | ||
| return torch.rand(1).item() < self.sample_rate | ||
|
|
||
| def on_test_batch_end( # type: ignore[override] # narrowed Lightning STEP_OUTPUT | ||
| self, | ||
| trainer: Trainer, | ||
| pl_module: LightningModule, | ||
| outputs: Outputs, | ||
| batch: tuple[torch.Tensor, list[dict[str, Any]]], | ||
| batch_idx: int, | ||
| dataloader_idx: int = 0, | ||
| ) -> None: | ||
| _, data = batch | ||
| for b in range(len(outputs)): | ||
| slide_name = data[b]["slide_name"] | ||
| if not self._should_save(): | ||
| continue | ||
|
|
||
| xy = data[b]["xy"] | ||
| slide_dir = self.output_dir / slide_name | ||
| slide_dir.mkdir(parents=True, exist_ok=True) | ||
|
|
||
| self._tensor_to_image(outputs[b]).save(slide_dir / f"{xy}_predicted.png") | ||
|
|
||
| original_image = Image.fromarray(data[b]["original_image"].astype("uint8")) | ||
| original_image.save(slide_dir / f"{xy}_original.png") | ||
|
|
||
| modified_image = Image.fromarray( | ||
| (data[b]["modified_image"] * 255).astype("uint8") | ||
| ) | ||
| modified_image.save(slide_dir / f"{xy}_modified.png") | ||
|
|
||
| def on_predict_batch_end( | ||
| self, | ||
| trainer: Trainer, | ||
| pl_module: LightningModule, | ||
| outputs: Outputs, | ||
| batch: tuple[torch.Tensor, list[dict[str, Any]]], | ||
| batch_idx: int, | ||
| dataloader_idx: int = 0, | ||
| ) -> None: | ||
| _, data = batch | ||
| for b in range(len(outputs)): | ||
| slide_name = data[b]["slide_name"] | ||
| if not self._should_save(): | ||
| continue | ||
|
|
||
| xy = data[b]["xy"] | ||
| slide_dir = self.output_dir / slide_name | ||
| slide_dir.mkdir(parents=True, exist_ok=True) | ||
|
|
||
| self._tensor_to_image(outputs[b]).save(slide_dir / f"{xy}.png") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,218 @@ | ||
| import tempfile | ||
| import traceback | ||
| from dataclasses import dataclass | ||
| from pathlib import Path | ||
| from typing import Any | ||
|
|
||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
| import numpy as np | ||
| import torch | ||
| from lightning import LightningModule, Trainer | ||
|
|
||
| from rationai.mlkit.lightning.callbacks import MultiloaderLifecycle | ||
|
|
||
| from stain_normalization.type_aliases import Outputs | ||
|
|
||
|
|
||
| @dataclass | ||
| class _SlideMeta: | ||
| path: str | ||
| level: int | ||
| extent_x: int | ||
| extent_y: int | ||
| tile_extent_x: int | ||
| tile_extent_y: int | ||
| mpp_x: float | ||
| mpp_y: float | ||
|
|
||
|
|
||
| @dataclass | ||
| class _SlideBuffers: | ||
| meta: _SlideMeta | ||
| temp_dir: tempfile.TemporaryDirectory[str] | ||
| result_buffer: np.memmap[Any, Any] | ||
| count_buffer: np.memmap[Any, Any] | ||
|
|
||
|
|
||
| class WSIAssembler(MultiloaderLifecycle): | ||
| """Assembles predicted tiles back into whole-slide pyramid TIFFs. | ||
|
|
||
| Uses one dataloader per slide (via MultiloaderLifecycle) — buffers are | ||
| opened on dataloader start and saved/freed on dataloader end. | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| output_dir: str | Path, | ||
| temp_dir: str | Path | None = None, | ||
| ) -> None: | ||
| super().__init__() | ||
| self.output_dir = Path(output_dir) | ||
| self.temp_dir = str(temp_dir) if temp_dir else None | ||
| self._active: _SlideBuffers | None = None | ||
| self._active_name: str | None = None | ||
| self._failed_slides: list[str] = [] | ||
|
|
||
| def on_predict_start(self, trainer: Trainer, pl_module: LightningModule) -> None: | ||
| self.output_dir.mkdir(parents=True, exist_ok=True) | ||
|
|
||
| def on_predict_dataloader_start( | ||
| self, trainer: Trainer, pl_module: LightningModule, dataloader_idx: int | ||
| ) -> None: | ||
| slide = trainer.datamodule.predict.slides.iloc[dataloader_idx] # type: ignore[attr-defined] | ||
| meta = _SlideMeta( | ||
| path=slide.path, | ||
| level=int(slide.level), | ||
| extent_x=int(slide.extent_x), | ||
| extent_y=int(slide.extent_y), | ||
| tile_extent_x=int(slide.tile_extent_x), | ||
| tile_extent_y=int(slide.tile_extent_y), | ||
| mpp_x=float(slide.mpp_x), | ||
| mpp_y=float(slide.mpp_y), | ||
| ) | ||
| slide_name = Path(slide.path).stem | ||
| self._open_slide(slide_name, meta) | ||
|
|
||
| def on_predict_dataloader_end( | ||
| self, trainer: Trainer, pl_module: LightningModule, dataloader_idx: int | ||
| ) -> None: | ||
| self._close_slide() | ||
|
|
||
| def _open_slide(self, slide_name: str, meta: _SlideMeta) -> None: | ||
| """Allocate memmap buffers for one slide.""" | ||
| h, w = meta.extent_y, meta.extent_x | ||
|
|
||
| tmp = tempfile.TemporaryDirectory( | ||
| prefix=f"wsi_{slide_name}_", dir=self.temp_dir | ||
| ) | ||
| result_buf = np.memmap( | ||
| Path(tmp.name) / "result.raw", | ||
| dtype=np.uint8, | ||
| mode="w+", | ||
| shape=(h, w, 3), | ||
| ) | ||
| count_buf = np.memmap( | ||
| Path(tmp.name) / "count.raw", | ||
| dtype=np.uint8, | ||
| mode="w+", | ||
| shape=(h, w), | ||
| ) | ||
|
LAdam-ix marked this conversation as resolved.
|
||
|
|
||
| self._active = _SlideBuffers( | ||
| meta=meta, | ||
| temp_dir=tmp, | ||
| result_buffer=result_buf, | ||
| count_buffer=count_buf, | ||
| ) | ||
| self._active_name = slide_name | ||
|
|
||
| def _close_slide(self) -> None: | ||
| """Save and free the currently active slide.""" | ||
| if self._active is None: | ||
| return | ||
| assert self._active_name is not None | ||
| slide_name = self._active_name | ||
| try: | ||
| self._save_slide(slide_name, self._active) | ||
| except Exception: | ||
| print(f"ERROR: Failed to save slide '{slide_name}'") | ||
| traceback.print_exc() | ||
| self._failed_slides.append(slide_name) | ||
| finally: | ||
| del self._active.result_buffer | ||
| del self._active.count_buffer | ||
| self._active.temp_dir.cleanup() | ||
| self._active = None | ||
| self._active_name = None | ||
|
|
||
| def on_predict_batch_end( | ||
| self, | ||
| trainer: Trainer, | ||
| pl_module: LightningModule, | ||
| outputs: Outputs, | ||
| batch: tuple[torch.Tensor, list[dict[str, Any]]], | ||
| batch_idx: int, | ||
| dataloader_idx: int = 0, | ||
| ) -> None: | ||
| for b in range(len(outputs)): | ||
| tile = outputs[b].mul(255).byte().permute(1, 2, 0).cpu().numpy() | ||
| metadata = batch[1][b] | ||
| x, y = (int(v) for v in metadata["xy"].split("_")) | ||
| self._place_tile(tile, x, y) | ||
|
|
||
| def _place_tile(self, tile: np.ndarray[Any, Any], x: int, y: int) -> None: | ||
| """Place a predicted tile into the active slide buffer with overlap averaging.""" | ||
| assert self._active is not None | ||
| sb = self._active | ||
| ex, ey = sb.meta.extent_x, sb.meta.extent_y | ||
|
|
||
| h = max(0, min(tile.shape[0], ey - y)) | ||
| w = max(0, min(tile.shape[1], ex - x)) | ||
| if h == 0 or w == 0: | ||
| return | ||
| tile = tile[:h, :w] | ||
|
|
||
| region = sb.result_buffer[y : y + h, x : x + w] | ||
| count = sb.count_buffer[y : y + h, x : x + w] | ||
|
|
||
| # Running average: avg = (old * n + new) / (n + 1) | ||
| overlap = count > 0 | ||
| if overlap.any(): | ||
| n = count[:, :, np.newaxis].astype(np.float32) | ||
| blended = np.where( | ||
| overlap[:, :, np.newaxis], | ||
| (region.astype(np.float32) * n + tile) / (n + 1), | ||
| tile, | ||
| ) | ||
| sb.result_buffer[y : y + h, x : x + w] = np.clip(blended, 0, 255).astype( | ||
| np.uint8 | ||
| ) | ||
| else: | ||
| sb.result_buffer[y : y + h, x : x + w] = tile | ||
|
|
||
| sb.count_buffer[y : y + h, x : x + w] = count + 1 | ||
|
|
||
| def on_predict_end(self, trainer: Trainer, pl_module: LightningModule) -> None: | ||
| if self._failed_slides: | ||
| print( | ||
| f"WARNING: Failed to save {len(self._failed_slides)} slide(s): " | ||
| f"{self._failed_slides}" | ||
| ) | ||
|
|
||
| def _save_slide(self, slide_name: str, sb: _SlideBuffers) -> None: | ||
| # Imported here — module-level import causes OpenSlide segfault (libtiff conflict). | ||
| import pyvips | ||
|
|
||
| meta = sb.meta | ||
| sb.result_buffer.flush() | ||
| sb.count_buffer.flush() | ||
|
|
||
| result_path = Path(sb.temp_dir.name) / "result.raw" | ||
| count_path = Path(sb.temp_dir.name) / "count.raw" | ||
|
|
||
| result_img = pyvips.Image.rawload( | ||
| str(result_path), meta.extent_x, meta.extent_y, 3 | ||
| ) | ||
| result_img = result_img.copy(interpretation=pyvips.Interpretation.SRGB) | ||
|
|
||
| count_img = pyvips.Image.rawload( | ||
| str(count_path), meta.extent_x, meta.extent_y, 1 | ||
| ) | ||
| mask = count_img > 0 | ||
| # add white background for untouched areas (count=0) | ||
| white = (pyvips.Image.black(meta.extent_x, meta.extent_y, bands=3) + 255).cast( | ||
| pyvips.BandFormat.UCHAR | ||
| ) | ||
| final_img = mask.ifthenelse(result_img, white) | ||
|
|
||
| output_path = self.output_dir / f"{slide_name}_norm.tiff" | ||
| final_img.tiffsave( | ||
| str(output_path), | ||
| bigtiff=True, | ||
| compression=pyvips.enums.ForeignTiffCompression.DEFLATE, | ||
| tile=True, | ||
| tile_width=512, | ||
| tile_height=512, | ||
| pyramid=True, | ||
| xres=1000.0 / meta.mpp_x, | ||
| yres=1000.0 / meta.mpp_y, | ||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.