Skip to content

Turn any AI agent into an AI Scientist. The #1 Agent Skills library for science, used by 250,000+ scientists worldwide. 177 ready-to-use validated skills plus 100+ scientific databases covering biology, chemistry, medicine, and drug discovery. Compatible with Cursor, Claude Code, Codex, Pi, Antigravity, and the open Agent Skills standard.

Update PathML skill for current workflows

Timothy Kassis191e153a29d6
diff --git a/skills/pathml/SKILL.md b/skills/pathml/SKILL.md
index c91fc35a..a4cfcf6d 100644
--- a/skills/pathml/SKILL.md
+++ b/skills/pathml/SKILL.md
@@ -1,163 +1,222 @@
---
name: pathml
-description: Full-featured computational pathology toolkit. Use for advanced WSI analysis including multiplexed immunofluorescence (CODEX, Vectra), nucleus segmentation, tissue graph construction, and ML model training on pathology data. Supports 160+ slide formats. For simple tile extraction from H&E slides, histolab may be simpler.
-license: GPL-2.0 license
-metadata: {"version": "1.0", "skill-author": "K-Dense Inc."}
+description: "Use PathML for local, research-only computational pathology workflows: load and tile slides, build preprocessing and QC pipelines, manage h5path data, quantify multiplex images, construct spatial graphs, and plan bounded model inference."
+license: MIT
+compatibility: PathML 3.0.5 is the latest PyPI release and targets Python 3.10-3.12; installation needs uv plus platform libraries for OpenSlide, BLAS/LAPACK, and Java/Bio-Formats. Bundled Python 3.10+ CLIs are local, bounded, dependency-free, and network-free.
+allowed-tools: Read, Write, Edit, Bash, Glob
+metadata:
+ version: "1.1"
+ skill-author: K-Dense Inc.
---
# PathML
-## Overview
+## Scope and safety boundary
-PathML is a comprehensive Python toolkit for computational pathology workflows, designed to facilitate machine learning and image analysis for whole-slide pathology images. The framework provides modular, composable tools for loading diverse slide formats, preprocessing images, constructing spatial graphs, training deep learning models, and analyzing multiparametric imaging data from technologies like CODEX and multiplex immunofluorescence.
+Use PathML for **local computational pathology research**. It is beta research
+software, not a validated medical device, diagnostic system, clinical decision
+support tool, or substitute for a pathologist. Do not use outputs to diagnose,
+grade, stage, or treat a patient.
-## When to Use This Skill
+Pathology files may contain faces, labels, accession numbers, patient identifiers,
+DICOM tags, filenames, or linked clinical data. Before processing:
-Apply this skill for:
-- Loading and processing whole-slide images (WSI) in various proprietary formats
-- Preprocessing H&E stained tissue images with stain normalization
-- Nucleus detection, segmentation, and classification workflows
-- Building cell and tissue graphs for spatial analysis
-- Training or deploying machine learning models (HoVer-Net, HACTNet) on pathology data
-- Analyzing multiparametric imaging (CODEX, Vectra, MERFISH) for spatial proteomics
-- Quantifying marker expression from multiplex immunofluorescence
-- Managing large-scale pathology datasets with HDF5 storage
-- Tile-based analysis and stitching operations
+1. Confirm authorization, consent/waiver, data-use terms, and institutional policy.
+2. De-identify pixels and metadata; keep the re-identification key outside the
+ analysis workspace.
+3. Use pseudonymous `patient_id`, `slide_id`, and `specimen_id` values. Do not put
+ direct identifiers in filenames, logs, `.h5path` labels, model cards, or reports.
+4. Keep inputs, intermediates, and outputs on approved local encrypted storage.
+5. Split by patient (then slide) before tiling or fitting any preprocessing step.
-## Core Capabilities
+## Version baseline, verified 2026-07-23
-PathML provides six major capability areas documented in detail within reference files:
+- **Installable stable release:** PyPI `pathml==3.0.5`, published 2026-03-24.
+- The v3.0.5 release notes state Python **3.10-3.12** and sunset 3.9.
+ PyPI does not declare `Requires-Python` and still has a stale 3.8 classifier, so
+ use the release statement and test the exact environment.
+- GitHub releases v3.0.6 (2026-04-14) and v3.0.7 (2026-07-09) exist, but PyPI has
+ no artifacts for them as of this review. v3.0.7 updates Torch/TorchVision/
+ torch-geometric and ONNX export code. Do not mix those source dependencies with
+ the 3.0.5 wheel.
+- ReadTheDocs `/latest` identifies itself as 3.0.5. Examples here were checked
+ against the v3.0.5 tag and PyPI wheel metadata, not unversioned snippets.
+- This skill is MIT-licensed. PathML itself is GPL-2.0 with upstream commercial
+ licensing options; review upstream terms before redistribution.
-### 1. Image Loading & Formats
+## Reproducible installation
-Load whole-slide images from 160+ proprietary formats including Aperio SVS, Hamamatsu NDPI, Leica SCN, Zeiss ZVI, DICOM, and OME-TIFF. PathML automatically handles vendor-specific formats and provides unified interfaces for accessing image pyramids, metadata, and regions of interest.
-
-**See:** `references/image_loading.md` for supported formats, loading strategies, and working with different slide types.
-
-### 2. Preprocessing Pipelines
-
-Build modular preprocessing pipelines by composing transforms for image manipulation, quality control, stain normalization, tissue detection, and mask operations. PathML's Pipeline architecture enables reproducible, scalable preprocessing across large datasets.
-
-**Key transforms:**
-- `StainNormalizationHE` - Macenko/Vahadane stain normalization
-- `TissueDetectionHE`, `NucleusDetectionHE` - Tissue/nucleus segmentation
-- `MedianBlur`, `GaussianBlur` - Noise reduction
-- `LabelArtifactTileHE` - Quality control for artifacts
-
-**See:** `references/preprocessing.md` for complete transform catalog, pipeline construction, and preprocessing workflows.
-
-### 3. Graph Construction
-
-Construct spatial graphs representing cellular and tissue-level relationships. Extract features from segmented objects to create graph-based representations suitable for graph neural networks and spatial analysis.
-
-**See:** `references/graphs.md` for graph construction methods, feature extraction, and spatial analysis workflows.
-
-### 4. Machine Learning
-
-Train and deploy deep learning models for nucleus detection, segmentation, and classification. PathML integrates PyTorch with pre-built models (HoVer-Net, HACTNet), custom DataLoaders, and ONNX support for inference.
-
-**Key models:**
-- **HoVer-Net** - Simultaneous nucleus segmentation and classification
-- **HACTNet** - Hierarchical cell-type classification
-
-**See:** `references/machine_learning.md` for model training, evaluation, inference workflows, and working with public datasets.
-
-### 5. Multiparametric Imaging
-
-Analyze spatial proteomics and gene expression data from CODEX, Vectra, MERFISH, and other multiplex imaging platforms. PathML provides specialized slide classes and transforms for processing multiparametric data, cell segmentation with Mesmer, and quantification workflows.
-
-**See:** `references/multiparametric.md` for CODEX/Vectra workflows, cell segmentation, marker quantification, and integration with AnnData.
-
-### 6. Data Management
-
-Efficiently store and manage large pathology datasets using HDF5 format. PathML handles tiles, masks, metadata, and extracted features in unified storage structures optimized for machine learning workflows.
-
-**See:** `references/data_management.md` for HDF5 integration, tile management, dataset organization, and batch processing strategies.
-
-## Quick Start
-
-### Installation
+Use Python 3.11 unless the project has tested another supported interpreter:
```bash
-# Install PathML
-uv pip install pathml
-
-# With optional dependencies for all features
-uv pip install pathml[all]
+uv venv --python 3.11
+source .venv/bin/activate
+uv pip install "pathml==3.0.5"
+python -c "import importlib.metadata as m; print(m.version('pathml'))"
```
-### Basic Workflow Example
+PathML 3.0.5 declares no package extras: do **not** use `pathml[all]`. Its base
+distribution pins a large scientific/ML stack, including Torch 2.8.0, ONNX 1.17.0,
+ONNX Runtime 1.17.x, OpenSlide Python 1.3.1, python-bioformats 4.1.0, and
+python-javabridge 4.0.4.
-```python
-from pathml.core import SlideData
-from pathml.preprocessing import Pipeline, StainNormalizationHE, TissueDetectionHE
+Install native prerequisites before the uv command:
-# Load a whole-slide image
-wsi = SlideData.from_slide("path/to/slide.svs")
-
-# Create preprocessing pipeline
-pipeline = Pipeline([
- TissueDetectionHE(),
- StainNormalizationHE(target='normalize', stain_estimation_method='macenko')
-])
+```bash
+# Debian/Ubuntu
+sudo apt-get install openslide-tools gcc g++ libblas-dev liblapack-dev openjdk-17-jdk
-# Run pipeline
-pipeline.run(wsi)
+# macOS
+brew install openslide openjdk@17
-# Access processed tiles
-for tile in wsi.tiles:
- processed_image = tile.image
- tissue_mask = tile.masks['tissue']
+# Windows OpenSlide option documented upstream
+vcpkg install openslide
```
-### Common Workflows
-
-**H&E Image Analysis:**
-1. Load WSI with appropriate slide class
-2. Apply tissue detection and stain normalization
-3. Perform nucleus detection or train segmentation models
-4. Extract features and build spatial graphs
-5. Conduct downstream analysis
-
-**Multiparametric Imaging (CODEX):**
-1. Load CODEX slide with `CODEXSlide`
-2. Collapse multi-run channel data
-3. Segment cells using Mesmer model
-4. Quantify marker expression
-5. Export to AnnData for single-cell analysis
+Java/Bio-Formats is needed for the broad multidimensional format backend.
+OpenSlide handles common brightfield WSI formats more efficiently. CUDA is
+optional and must match the pinned PyTorch build; follow PyTorch's platform
+selector rather than guessing a CUDA wheel. See `references/image_loading.md`.
-**Training ML Models:**
-1. Prepare dataset with public pathology data
-2. Create PyTorch DataLoader with PathML datasets
-3. Train HoVer-Net or custom models
-4. Evaluate on held-out test sets
-5. Deploy with ONNX for inference
+## Stable minimal workflow
-## References to Detailed Documentation
+PathML 3.0.5 uses slide convenience classes and `SlideData.run()`. It does not
+provide `SlideData.from_slide()`, and `Pipeline` does not have `run()`:
-When working on specific tasks, refer to the appropriate reference file for comprehensive information:
-
-- **Loading images:** `references/image_loading.md`
-- **Preprocessing workflows:** `references/preprocessing.md`
-- **Spatial analysis:** `references/graphs.md`
-- **Model training:** `references/machine_learning.md`
-- **CODEX/multiplex IF:** `references/multiparametric.md`
-- **Data storage:** `references/data_management.md`
-
-## Resources
+```python
+from pathml.core import HESlide
+from pathml.preprocessing import BoxBlur, Pipeline, TissueDetectionHE
+
+slide = HESlide("data/pseudonymous_slide.svs", backend="openslide")
+pipeline = Pipeline(
+ [
+ BoxBlur(kernel_size=5),
+ TissueDetectionHE(mask_name="tissue", min_region_size=5000),
+ ]
+)
+slide.run(
+ pipeline,
+ distributed=False,
+ tile_size=512,
+ tile_stride=512,
+ level=0,
+ tile_pad=False,
+)
+slide.write("derived/pseudonymous_slide.h5path")
+```
-This skill includes comprehensive reference documentation organized by capability area. Each reference file contains detailed API information, workflow examples, best practices, and troubleshooting guidance for specific PathML functionality.
+Start with a bounded manual sample before a full run:
-### references/
+```python
+from itertools import islice
-Documentation files providing in-depth coverage of PathML capabilities:
+for tile in islice(slide.generate_tiles(shape=512, stride=512, level=0), 8):
+ pipeline.apply(tile)
+ assert tile.masks["tissue"].shape[:2] == tile.image.shape[:2]
+```
-- `image_loading.md` - Whole-slide image formats, loading strategies, slide classes
-- `preprocessing.md` - Complete transform catalog, pipeline construction, preprocessing workflows
-- `graphs.md` - Graph construction methods, feature extraction, spatial analysis
-- `machine_learning.md` - Model architectures, training workflows, evaluation, inference
-- `multiparametric.md` - CODEX, Vectra, multiplex IF analysis, cell segmentation, quantification
-- `data_management.md` - HDF5 storage, tile management, batch processing, dataset organization
+Tiles use `(i, j)` = `(row, column)` coordinates at the selected pyramid level.
+For OpenSlide, PathML maps them to level-0 coordinates internally. Record the
+level and downsample; convert to `(x, y)` or micrometres explicitly downstream.
+
+## Research workflow
+
+1. **Inventory locally.** Validate the manifest, reject URLs/symlinks, inspect only
+ allowlisted technical metadata, and remove identifiers.
+2. **Freeze splits.** Assign every patient and all their slides to one split before
+ generating overlapping tiles, graphs, normalization references, or features.
+3. **Plan bounds.** Estimate tile count, RAM, output size, and pipeline stages.
+4. **Pilot preprocessing.** Inspect tissue masks, whitespace/artifact labels,
+ stain behavior, edge padding, and empty-mask cases on representative training
+ slides. Do not tune from test slides.
+5. **Run and preserve coordinates.** Keep tile level, `(i, j)`, downsample, MPP,
+ mask names, QC decisions, and failed/skipped tiles.
+6. **Build spatial data deliberately.** Validate channel order, physical units,
+ instance labels, node-feature alignment, graph edges, and cell-to-tissue
+ assignments.
+7. **Infer in bounded batches.** Verify model provenance and checksum without
+ loading unknown pickle checkpoints. Keep predictions linked to slide/tile
+ coordinates and stitch overlaps with a documented rule.
+8. **Report provenance and limits.** Include package lock, source hashes, scanner,
+ stain, parameters, seeds, split manifest, model card, exclusions, and QC.
+
+## No-network default and explicit consent gate
+
+Do not instantiate download-capable classes or set dataset `download=True` unless
+the user explicitly opts in after receiving the endpoint and disclosure:
+
+- `SegmentMIFRemote` downloads an ONNX file from
+ `https://huggingface.co/pathml/test/resolve/main/mesmer.onnx` at construction,
+ then runs inference locally. Stable source does **not** upload image pixels.
+ The request still discloses network metadata such as IP address and headers and
+ creates `temp.onnx`; there is no built-in checksum or offline flag.
+- Deprecated `SegmentMIF` imports local DeepCell Mesmer, but DeepCell model
+ initialization may need separately provisioned weights. It is not a PathML
+ extra and is not the preferred stable API.
+- `RemoteTestHoverNet` downloads a model from Hugging Face.
+- `PanNukeDataModule(download=True)` contacts Warwick; `DeepFocusDataModule`
+ contacts Zenodo. Both default to `download=False`.
+
+Before any future hosted prediction call, state the exact destination, pixel
+channels/regions, metadata, identifiers, retention, legal basis, and safeguards;
+obtain explicit consent; and never send PHI by default. Prefer reviewed,
+checksummed local model artifacts and local inference.
+
+## Model-code security
+
+- PyTorch `model.eval()` means **evaluation mode** for modules; it is not Python's
+ dangerous built-in evaluator. Never use Python dynamic evaluation or execution.
+- Do not name local files `pathml.py`, `torch.py`, `onnx.py`, or after standard
+ libraries; shadow modules can silently change imports.
+- PathML's `EntityDataset` loads `.pt` objects with `weights_only=False`. Never
+ open an untrusted graph/checkpoint. Treat pickle-based pipelines and `.pt` files
+ as executable code.
+- ONNX is safer than pickle but not inherently trusted. Verify source, SHA-256,
+ expected input/output schema, file size, and runtime limits; use isolation for
+ third-party models.
+
+## Bundled local CLIs
+
+All helpers reject URLs and symlinks, cap inputs/work, use strict JSON, avoid
+network access, and require no PathML import for `--help`:
-Load these references as needed when working on specific computational pathology tasks.
+```bash
+python scripts/slide_manifest.py validate --manifest manifest.csv --root .
+python scripts/slide_manifest.py inspect --slide data/example.svs --root .
+python scripts/plan_pipeline.py --width 100000 --height 80000 --tile-size 512 --stride 512
+python scripts/image_qc.py synthetic --width 256 --height 256
+python scripts/validate_spatial_schema.py graph --input graph.json --root .
+python scripts/validate_spatial_schema.py multiplex --input cells.csv --root .
+python scripts/plan_inference.py --tile-count 4000 --batch-size 16 --height 256 --width 256
+```
+The inference planner reads numbers or a bounded JSON model card only; it never
+imports a model framework or opens a checkpoint.
+
+## Detailed references
+
+- `references/image_loading.md` — slide classes, backends, formats, levels,
+ coordinates, technical metadata, and privacy.
+- `references/preprocessing.md` — stable transforms, masks/QC, stain processing,
+ pipeline execution, and leakage prevention.
+- `references/data_management.md` — `.h5path`, manifests, datasets, provenance,
+ splits, and safe downloads.
+- `references/multiparametric.md` — multidimensional layout, CODEX/Vectra,
+ quantification, AnnData, DeepCell/Mesmer, and network disclosure.
+- `references/graphs.md` — instance maps, feature alignment, KNN/RAG/HACT graphs,
+ spatial units, schemas, and validation.
+- `references/machine_learning.md` — HoVer-Net/HACTNet, local ONNX inference,
+ batching, checkpoint trust, evaluation, and model provenance.
+
+## Primary sources
+
+All checked 2026-07-23:
+
+- PyPI metadata: https://pypi.org/project/pathml/3.0.5/
+- Stable source tag: https://github.com/Dana-Farber-AIOS/pathml/tree/v3.0.5
+- Releases: https://github.com/Dana-Farber-AIOS/pathml/releases
+- Stable documentation: https://pathml.readthedocs.io/en/stable/
+- Rosenthal et al. (2022), PathML toolkit:
+ https://doi.org/10.1158/1541-7786.MCR-21-0665
+- Omar et al. (2025), multiplex workflows:
+ https://doi.org/10.1016/j.labinv.2025.104220
diff --git a/skills/pathml/references/data_management.md b/skills/pathml/references/data_management.md
index 0e6a78ed..4ed9e72c 100644
--- a/skills/pathml/references/data_management.md
+++ b/skills/pathml/references/data_management.md
@@ -1,742 +1,357 @@
-# Data Management & Storage
+# Data management, h5path, manifests, datasets, and provenance
-## Overview
+This reference targets **PathML 3.0.5 stable** and a local, de-identified research
+workflow.
-PathML provides efficient data management solutions for handling large-scale pathology datasets through HDF5 storage, tile management strategies, and optimized batch processing workflows. The framework enables seamless storage and retrieval of images, masks, features, and metadata in formats optimized for machine learning pipelines and downstream analysis.
+## Data boundaries
-## HDF5 Integration
+Separate four classes of data:
-HDF5 (Hierarchical Data Format) is the primary storage format for processed PathML data, providing:
-- Efficient compression and chunked storage
-- Fast random access to subsets of data
-- Support for arbitrarily large datasets
-- Hierarchical organization of heterogeneous data types
-- Cross-platform compatibility
+1. **Source slides** — immutable, access-controlled originals.
+2. **Linkage data** — direct identifiers and the pseudonym mapping, held outside
+ the analysis workspace by an authorized custodian.
+3. **Analysis data** — pseudonymous manifests, tiles, masks, counts, graphs, and
+ features.
+4. **Reports/models** — potentially identifying derived artifacts that still
+ require governance.
-### Saving to HDF5
+Do not assume derived images or embeddings are anonymous. Rare morphology,
+scanner metadata, dates, or cohort combinations can re-identify a participant.
+Apply the minimum-necessary principle and institutional retention policy.
-**Single slide:**
-```python
-from pathml.core import SlideData
+## Manifest first
-# Load and process slide
-wsi = SlideData.from_slide("slide.svs")
-wsi.generate_tiles(level=1, tile_size=256, stride=256)
+Use one row per slide. Recommended columns:
-# Run preprocessing pipeline
-pipeline.run(wsi)
-
-# Save to HDF5
-wsi.to_hdf5("processed_slide.h5")
+```text
+slide_id,patient_id,specimen_id,path,split,stain,backend,site,scanner
```
-**Multiple slides (SlideDataset):**
-```python
-from pathml.core import SlideDataset
-import glob
+Rules:
-# Create dataset
-slide_paths = glob.glob("data/*.svs")
-dataset = SlideDataset(slide_paths, tile_size=256, stride=256, level=1)
+- IDs are pseudonyms, not MRNs, accessions, initials, dates, or names.
+- `slide_id` is unique.
+- one `patient_id` maps to exactly one split;
+- one slide path maps to one slide ID;
+- paths are local, relative to a declared root where possible;
+- URLs and symlinks are rejected;
+- split values are a fixed allowlist such as `train`, `validation`, `test`;
+- serial sections, rescans, and multiple blocks from one patient remain together.
-# Process
-dataset.run(pipeline, distributed=True, n_workers=8)
+Validate before PathML:
-# Save entire dataset
-dataset.to_hdf5("processed_dataset.h5")
+```bash
+python scripts/slide_manifest.py validate \
+ --manifest metadata/manifest.csv \
+ --root .
```
-### HDF5 File Structure
-
-PathML HDF5 files are organized hierarchically:
-
-```
-processed_dataset.h5
-├── slide_0/
-│ ├── metadata/
-│ │ ├── name
-│ │ ├── level
-│ │ ├── dimensions
-│ │ └── ...
-│ ├── tiles/
-│ │ ├── tile_0/
-│ │ │ ├── image (H, W, C) array
-│ │ │ ├── coords (x, y)
-│ │ │ └── masks/
-│ │ │ ├── tissue
-│ │ │ ├── nucleus
-│ │ │ └── ...
-│ │ ├── tile_1/
-│ │ └── ...
-│ └── features/
-│ ├── tile_features (n_tiles, n_features)
-│ └── feature_names
-├── slide_1/
-└── ...
+The validator checks strict CSV structure, duplicate IDs/paths, missing local
+files, unsafe paths, supported suffixes, and patient/slide leakage. It does not
+upload data or inspect arbitrary clinical fields.
+
+## h5path format
+
+PathML processes slides into an HDF5-based `.h5path` file. Stable documentation
+describes:
+
+```text
+root/
+├── fields/
+│ ├── labels/ # slide-level attributes
+│ └── slide_type/ # stain/platform flags
+├── masks/ # slide-level masks
+├── counts/ # AnnData-like counts storage
+└── tiles/
+ ├── attributes # tile_shape, tile_stride
+ └── "(i, j)"/
+ ├── array
+ ├── masks/
+ ├── labels/
+ └── attributes # coords, name
```
-### Loading from HDF5
+Write and reopen through public APIs:
-**Load entire slide:**
```python
from pathml.core import SlideData
-# Load from HDF5
-wsi = SlideData.from_hdf5("processed_slide.h5")
-
-# Access tiles
-for tile in wsi.tiles:
- image = tile.image
- masks = tile.masks
- # Process tile...
+slide.write("derived/slide-001.h5path")
+reopened = SlideData("derived/slide-001.h5path")
```
-**Load specific tiles:**
-```python
-# Load only tiles at specific indices
-tile_indices = [0, 10, 20, 30]
-tiles = wsi.load_tiles_from_hdf5("processed_slide.h5", indices=tile_indices)
+There is no stable `to_hdf5()`, `from_hdf5()`, or
+`load_tiles_from_hdf5()` API. `SlideDataset.write(directory, filenames=None)`
+calls each slide's `write()`.
-for tile in tiles:
- # Process subset...
- pass
-```
+Stable documentation states HDF5 datasets are stored as `float16`; confirm dtype
+for the exact arrays your workflow writes. Quantitative marker intensities can
+lose precision if silently cast. Record and test expected dtype, range, NaN/Inf,
+compression, and round-trip tolerance.
-**Memory-mapped access:**
-```python
-import h5py
-
-# Open HDF5 file without loading into memory
-with h5py.File("processed_dataset.h5", 'r') as f:
- # Access specific data
- tile_0_image = f['slide_0/tiles/tile_0/image'][:]
- tissue_mask = f['slide_0/tiles/tile_0/masks/tissue'][:]
-
- # Iterate through tiles efficiently
- for tile_key in f['slide_0/tiles'].keys():
- tile_image = f[f'slide_0/tiles/{tile_key}/image'][:]
- # Process without loading all tiles...
-```
+## h5path trust boundary
-## Tile Management
+Treat `.h5path` as a structured binary input, not harmless data:
-### Tile Generation Strategies
+- HDF5 parsers have a large attack surface; open third-party files in isolation.
+- PathML 3.0.5 `TileDataset` dynamically interprets the stored `tile_shape`
+ attribute as a Python expression. Never open an untrusted `.h5path`.
+- Labels can contain sensitive values. Do not copy direct identifiers into HDF5.
+- A malformed file can request large allocations. Check file size and schema
+ before loading.
+- Do not edit HDF5 concurrently from multiple processes unless the access pattern
+ is explicitly designed and tested.
-**Fixed-size tiles with no overlap:**
-```python
-wsi.generate_tiles(
- level=1,
- tile_size=256,
- stride=256, # stride = tile_size → no overlap
- pad=False # Don't pad edge tiles
-)
-```
-- **Use case:** Standard tile-based processing, classification
-- **Pros:** Simple, no redundancy, fast processing
-- **Cons:** Edge effects at tile boundaries
-
-**Overlapping tiles:**
-```python
-wsi.generate_tiles(
- level=1,
- tile_size=256,
- stride=128, # 50% overlap
- pad=False
-)
-```
-- **Use case:** Segmentation, detection (reduces boundary artifacts)
-- **Pros:** Better boundary handling, smoother stitching
-- **Cons:** More tiles, redundant computation
-
-**Adaptive tiling based on tissue content:**
-```python
-from pathml.utils import adaptive_tile_generation
+Use a sidecar JSON manifest for provenance rather than relying on arbitrary HDF5
+labels. Keep the JSON strict, bounded, pseudonymous, and versioned.
-# Generate tiles only in tissue regions
-wsi.generate_tiles(level=1, tile_size=256, stride=256)
+## PyTorch tile dataset
-# Filter to keep only tiles with sufficient tissue
-tissue_tiles = []
-for tile in wsi.tiles:
- if tile.masks.get('tissue') is not None:
- tissue_coverage = tile.masks['tissue'].sum() / (tile_size**2)
- if tissue_coverage > 0.5: # Keep tiles with >50% tissue
- tissue_tiles.append(tile)
-
-wsi.tiles = tissue_tiles
-```
-- **Use case:** Sparse tissue samples, efficiency
-- **Pros:** Reduces processing of background tiles
-- **Cons:** Requires tissue detection preprocessing step
-
-### Tile Stitching
-
-Reconstruct full slide from processed tiles:
+The canonical stable import is:
```python
-from pathml.utils import stitch_tiles
-
-# Process tiles
-for tile in wsi.tiles:
- tile.prediction = model.predict(tile.image)
-
-# Stitch predictions back to full resolution
-full_prediction_map = stitch_tiles(
- wsi.tiles,
- output_shape=wsi.level_dimensions[1], # Use level 1 dimensions
- tile_size=256,
- stride=256,
- method='average' # 'average', 'max', or 'first'
+from pathml.datasets import TileDataset
+from torch.utils.data import DataLoader
+
+tiles = TileDataset("derived/slide-001.h5path")
+loader = DataLoader(
+ tiles,
+ batch_size=8,
+ shuffle=False,
+ num_workers=0,
)
-
-# Visualize
-import matplotlib.pyplot as plt
-plt.figure(figsize=(15, 15))
-plt.imshow(full_prediction_map)
-plt.title('Stitched Prediction Map')
-plt.axis('off')
-plt.show()
```
-**Stitching methods:**
-- `'average'`: Average overlapping regions (smooth transitions)
-- `'max'`: Maximum value in overlapping regions
-- `'first'`: Keep first tile's value (no blending)
-- `'weighted'`: Distance-weighted blending for smooth boundaries
-
-### Tile Caching
-
-Cache frequently accessed tiles for faster iteration:
+Each item is:
-```python
-from pathml.utils import TileCache
-
-# Create cache
-cache = TileCache(max_size_gb=10)
-
-# Cache tiles during first iteration
-for i, tile in enumerate(wsi.tiles):
- cache.add(f'tile_{i}', tile.image)
- # Process tile...
-
-# Subsequent iterations use cached data
-for i in range(len(wsi.tiles)):
- cached_image = cache.get(f'tile_{i}')
- # Fast access...
+```text
+(tile_image, tile_masks, tile_labels, slide_labels)
```
-## Dataset Organization
+Shapes:
-### Directory Structure for Large Projects
+- RGB/multichannel 3-D input becomes `(C, H, W)`.
+- 5-D PathML input `(i, j, z, c, t)` becomes `(T, C, Z, W, H)` in stable
+ source; verify axis semantics before use.
+- masks are stacked as `(n_masks, tile_height, tile_width)` when present.
+- label dictionaries are user-defined and may need a custom `collate_fn`.
-Organize pathology projects with consistent structure:
+Do not assume mask dictionary order carries semantics. Persist ordered mask names
+in a separate schema and assert them when loading.
-```
-project/
-├── raw_slides/
-│ ├── cohort1/
-│ │ ├── slide001.svs
-│ │ ├── slide002.svs
-│ │ └── ...
-│ └── cohort2/
-│ └── ...
-├── processed/
-│ ├── cohort1/
-│ │ ├── slide001.h5
-│ │ ├── slide002.h5
-│ │ └── ...
-│ └── cohort2/
-│ └── ...
-├── features/
-│ ├── cohort1_features.h5
-│ └── cohort2_features.h5
-├── models/
-│ ├── hovernet_checkpoint.pth
-│ └── classifier.onnx
-├── results/
-│ ├── predictions/
-│ ├── visualizations/
-│ └── metrics.csv
-└── metadata/
- ├── clinical_data.csv
- └── slide_manifest.csv
-```
+`pathml.ml.TileDataset` is also exported in 3.0.5, but
+`pathml.datasets.TileDataset` is the documented dataset API.
-### Metadata Management
+## SlideDataset
-Store slide-level and cohort-level metadata:
+`SlideDataset(slides)` accepts a list of already constructed `SlideData` objects:
```python
-import pandas as pd
-
-# Slide manifest
-manifest = pd.DataFrame({
- 'slide_id': ['slide001', 'slide002', 'slide003'],
- 'path': ['raw_slides/cohort1/slide001.svs', ...],
- 'cohort': ['cohort1', 'cohort1', 'cohort2'],
- 'tissue_type': ['breast', 'breast', 'lung'],
- 'scanner': ['Aperio', 'Hamamatsu', 'Aperio'],
- 'magnification': [40, 40, 20],
- 'staining': ['H&E', 'H&E', 'H&E']
-})
-
-manifest.to_csv('metadata/slide_manifest.csv', index=False)
-
-# Clinical data
-clinical = pd.DataFrame({
- 'slide_id': ['slide001', 'slide002', 'slide003'],
- 'patient_id': ['P001', 'P002', 'P003'],
- 'age': [55, 62, 48],
- 'diagnosis': ['invasive', 'in_situ', 'invasive'],
- 'stage': ['II', 'I', 'III'],
- 'outcome': ['favorable', 'favorable', 'poor']
-})
-
-clinical.to_csv('metadata/clinical_data.csv', index=False)
-
-# Load and merge
-manifest = pd.read_csv('metadata/slide_manifest.csv')
-clinical = pd.read_csv('metadata/clinical_data.csv')
-data = manifest.merge(clinical, on='slide_id')
+from pathml.core import HESlide, SlideDataset
+
+slides = [
+ HESlide("data/slide-001.svs", backend="openslide"),
+ HESlide("data/slide-002.svs", backend="openslide"),
+]
+cohort = SlideDataset(slides)
+cohort.run(pipeline, distributed=False, tile_size=512, level=0)
+cohort.write("derived")
```
-## Batch Processing Strategies
+It does not accept a glob/path list plus tiling arguments as a constructor.
+Preserve a deterministic manifest order and map output filenames explicitly.
-### Sequential Processing
+## Public data modules
-Process slides one at a time (memory-efficient):
+Stable `pathml.datasets` exports:
```python
-import glob
-from pathml.core import SlideData
-from pathml.preprocessing import Pipeline
-
-slide_paths = glob.glob('raw_slides/**/*.svs', recursive=True)
-
-for slide_path in slide_paths:
- # Load slide
- wsi = SlideData.from_slide(slide_path)
- wsi.generate_tiles(level=1, tile_size=256, stride=256)
-
- # Process
- pipeline.run(wsi)
-
- # Save
- output_path = slide_path.replace('raw_slides', 'processed').replace('.svs', '.h5')
- wsi.to_hdf5(output_path)
-
- print(f"Processed: {slide_path}")
+from pathml.datasets import DeepFocusDataModule, PanNukeDataModule
```
-### Parallel Processing with Dask
-
-Process multiple slides in parallel:
+### PanNuke
```python
-from pathml.core import SlideDataset
-from dask.distributed import Client, LocalCluster
-from pathml.preprocessing import Pipeline
-
-# Start Dask cluster
-cluster = LocalCluster(
- n_workers=8,
- threads_per_worker=2,
- memory_limit='8GB',
- dashboard_address=':8787' # View progress at localhost:8787
-)
-client = Client(cluster)
-
-# Create dataset
-slide_paths = glob.glob('raw_slides/**/*.svs', recursive=True)
-dataset = SlideDataset(slide_paths, tile_size=256, stride=256, level=1)
-
-# Distribute processing
-dataset.run(
- pipeline,
- distributed=True,
- client=client,
- scheduler='distributed'
+pannuke = PanNukeDataModule(
+ data_dir="approved_data/pannuke",
+ download=False,
+ shuffle=True,
+ nucleus_type_labels=True,
+ split=1,
+ batch_size=8,
+ hovernet_preprocess=True,
)
-
-# Save results
-for i, slide in enumerate(dataset):
- output_path = slide_paths[i].replace('raw_slides', 'processed').replace('.svs', '.h5')
- slide.to_hdf5(output_path)
-
-client.close()
-cluster.close()
-```
-
-### Batch Processing with Job Arrays
-
-For HPC clusters (SLURM, PBS):
-
-```python
-# submit_jobs.py
-import os
-import glob
-
-slide_paths = glob.glob('raw_slides/**/*.svs', recursive=True)
-
-# Write slide list
-with open('slide_list.txt', 'w') as f:
- for path in slide_paths:
- f.write(path + '\n')
-
-# Create SLURM job script
-slurm_script = """#!/bin/bash
-#SBATCH --array=1-{n_slides}
-#SBATCH --cpus-per-task=4
-#SBATCH --mem=16G
-#SBATCH --time=4:00:00
-#SBATCH --output=logs/slide_%A_%a.out
-
-# Get slide path for this array task
-SLIDE_PATH=$(sed -n "${{SLURM_ARRAY_TASK_ID}}p" slide_list.txt)
-
-# Run processing
-python process_slide.py --slide_path $SLIDE_PATH
-""".format(n_slides=len(slide_paths))
-
-with open('submit_jobs.sh', 'w') as f:
- f.write(slurm_script)
-
-# Submit: sbatch submit_jobs.sh
```
-```python
-# process_slide.py
-import argparse
-from pathml.core import SlideData
-from pathml.preprocessing import Pipeline
-
-parser = argparse.ArgumentParser()
-parser.add_argument('--slide_path', type=str, required=True)
-args = parser.parse_args()
-
-# Load and process
-wsi = SlideData.from_slide(args.slide_path)
-wsi.generate_tiles(level=1, tile_size=256, stride=256)
-
-pipeline = Pipeline([...])
-pipeline.run(wsi)
-
-# Save
-output_path = args.slide_path.replace('raw_slides', 'processed').replace('.svs', '.h5')
-wsi.to_hdf5(output_path)
-
-print(f"Processed: {args.slide_path}")
-```
+- 7,901 256-pixel patches, 19 tissue types, five nucleus categories plus
+ background.
+- `download=False` is the safe default.
+- `download=True` downloads three ZIPs from Warwick and extracts them.
+- `split` must be 1, 2, 3, or `None`; each integer rotates the three published
+ folds across train/validation/test.
+- `split=None` exposes the whole dataset; do not use it for performance
+ estimation.
-## Feature Extraction and Storage
+Published folds are not a substitute for verifying patient/source-slide
+independence for the intended claim.
-### Extracting Features
+### DeepFocus
```python
-from pathml.core import SlideData
-import torch
-import numpy as np
-
-# Load pre-trained model for feature extraction
-model = torch.load('models/feature_extractor.pth')
-model.eval()
-device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
-model = model.to(device)
-
-# Load processed slide
-wsi = SlideData.from_hdf5('processed/slide001.h5')
-
-# Extract features for each tile
-features = []
-coords = []
-
-for tile in wsi.tiles:
- # Preprocess tile
- tile_tensor = torch.from_numpy(tile.image).permute(2, 0, 1).unsqueeze(0).float()
- tile_tensor = tile_tensor.to(device)
-
- # Extract features
- with torch.no_grad():
- feature_vec = model(tile_tensor).cpu().numpy().flatten()
-
- features.append(feature_vec)
- coords.append(tile.coords)
-
-features = np.array(features) # Shape: (n_tiles, feature_dim)
-coords = np.array(coords) # Shape: (n_tiles, 2)
+deepfocus = DeepFocusDataModule(
+ data_dir="approved_data/deepfocus",
+ download=False,
+ shuffle=True,
+ batch_size=8,
+)
```
-### Storing Features in HDF5
+- focus classification patches derived from four slides/patients and four stains;
+- `download=True` contacts Zenodo;
+- stable code checks the downloaded HDF5 file against a fixed MD5 value.
-```python
-import h5py
-
-# Save features
-with h5py.File('features/slide001_features.h5', 'w') as f:
- f.create_dataset('features', data=features, compression='gzip')
- f.create_dataset('coords', data=coords)
- f.attrs['feature_dim'] = features.shape[1]
- f.attrs['num_tiles'] = features.shape[0]
- f.attrs['model'] = 'resnet50'
-
-# Load features
-with h5py.File('features/slide001_features.h5', 'r') as f:
- features = f['features'][:]
- coords = f['coords'][:]
- feature_dim = f.attrs['feature_dim']
-```
+MD5 here is an upstream integrity check, not a modern provenance guarantee.
+Record a SHA-256 and dataset license/source separately.
-### Feature Database for Multiple Slides
+PathML 3.0.5 does **not** export `TCGADataModule`. Use a separately governed data
+acquisition process for TCGA/GDC and document its API/version/consent terms.
-```python
-# Create consolidated feature database
-import h5py
-import glob
-
-feature_files = glob.glob('features/*_features.h5')
-
-with h5py.File('features/all_features.h5', 'w') as out_f:
- for i, feature_file in enumerate(feature_files):
- slide_name = feature_file.split('/')[-1].replace('_features.h5', '')
-
- with h5py.File(feature_file, 'r') as in_f:
- features = in_f['features'][:]
- coords = in_f['coords'][:]
-
- # Store in consolidated file
- grp = out_f.create_group(f'slide_{i}')
- grp.create_dataset('features', data=features, compression='gzip')
- grp.create_dataset('coords', data=coords)
- grp.attrs['slide_name'] = slide_name
-
-# Query features from all slides
-with h5py.File('features/all_features.h5', 'r') as f:
- for slide_key in f.keys():
- slide_name = f[slide_key].attrs['slide_name']
- features = f[f'{slide_key}/features'][:]
- # Process...
-```
+## Download consent
-## Data Versioning
+Before changing any `download` flag to `True`, tell the user:
-### Version Control with DVC
+- exact host and expected dataset;
+- approximate size (stable docs report PanNuke ~37.33 GB and DeepFocus ~10 GB);
+- destination and available disk;
+- dataset license/terms and citation;
+- whether the environment logs outbound IP/account metadata; and
+- that no local slide or clinical data will be uploaded.
-Use Data Version Control (DVC) for large dataset management:
+Require explicit opt-in. Never place downloaded archives inside the repository.
-```bash
-# Initialize DVC
-dvc init
+## Graph datasets and unsafe `.pt` files
-# Add data directory
-dvc add raw_slides/
-dvc add processed/
+`pathml.datasets.EntityDataset` assembles cell graphs, tissue graphs, and
+assignment matrices. Stable source opens `.pt` files using PyTorch object
+deserialization with unrestricted object loading.
-# Commit to git
-git add raw_slides.dvc processed.dvc .gitignore
-git commit -m "Add raw and processed slides"
+Consequences:
-# Push data to remote storage (S3, GCS, etc.)
-dvc remote add -d storage s3://my-bucket/pathml-data
-dvc push
+- only load artifacts created by the trusted project;
+- never load an emailed/downloaded `.pt` file merely to inspect it;
+- verify SHA-256, producer, code revision, PyTorch/PyG versions, and schema;
+- prefer non-executable interchange formats for exchange;
+- run legacy artifacts in a disposable, network-disabled environment if review is
+ unavoidable.
-# Pull data on another machine
-git pull
-dvc pull
-```
+The bundled inference planner and graph validator never load `.pt`, `.pth`,
+`.ckpt`, pickle, ONNX, or other model/graph binaries.
-### Checksums and Validation
+## Split design and leakage
-Validate data integrity:
+Create the split column once, before tiling:
-```python
-import hashlib
-import pandas as pd
-
-def compute_checksum(file_path):
- """Compute MD5 checksum of file."""
- hash_md5 = hashlib.md5()
- with open(file_path, 'rb') as f:
- for chunk in iter(lambda: f.read(4096), b""):
- hash_md5.update(chunk)
- return hash_md5.hexdigest()
-
-# Create checksum manifest
-slide_paths = glob.glob('raw_slides/**/*.svs', recursive=True)
-checksums = []
-
-for slide_path in slide_paths:
- checksum = compute_checksum(slide_path)
- checksums.append({
- 'path': slide_path,
- 'checksum': checksum,
- 'size_mb': os.path.getsize(slide_path) / 1e6
- })
-
-checksum_df = pd.DataFrame(checksums)
-checksum_df.to_csv('metadata/checksums.csv', index=False)
-
-# Validate files
-def validate_files(manifest_path):
- manifest = pd.read_csv(manifest_path)
- for _, row in manifest.iterrows():
- current_checksum = compute_checksum(row['path'])
- if current_checksum != row['checksum']:
- print(f"ERROR: Checksum mismatch for {row['path']}")
- else:
- print(f"OK: {row['path']}")
-
-validate_files('metadata/checksums.csv')
+```text
+patient → specimen/block → slide/rescan/serial section → region → tile
```
-## Performance Optimization
-
-### Compression Settings
-
-Optimize HDF5 compression for speed vs. size:
-
-```python
-import h5py
-
-# Fast compression (less CPU, larger files)
-with h5py.File('output.h5', 'w') as f:
- f.create_dataset(
- 'images',
- data=images,
- compression='gzip',
- compression_opts=1 # Level 1-9, lower = faster
- )
-
-# Maximum compression (more CPU, smaller files)
-with h5py.File('output.h5', 'w') as f:
- f.create_dataset(
- 'images',
- data=images,
- compression='gzip',
- compression_opts=9
- )
-
-# Balanced (recommended)
-with h5py.File('output.h5', 'w') as f:
- f.create_dataset(
- 'images',
- data=images,
- compression='gzip',
- compression_opts=4,
- chunks=True # Enable chunking for better I/O
- )
+Everything below a patient follows the patient's split unless the scientific
+design explicitly requires a stricter grouping.
+
+Common leakage paths:
+
+- overlapping tiles from one slide in different splits;
+- serial sections or rescans assigned separately;
+- stain reference fitted on all slides;
+- QC threshold chosen after viewing test failures;
+- normalization/scaling fit before split;
+- graph neighborhoods crossing a split boundary;
+- duplicated public patches;
+- institution/scanner confounding;
+- selecting a checkpoint on the test metric.
+
+The manifest validator reports patient and slide leakage, but it cannot discover
+unknown biological relatedness. Document grouping assumptions.
+
+## Provenance sidecar
+
+Recommended strict JSON fields:
+
+```json
+{
+ "schema_version": "1.0",
+ "pathml_version": "3.0.5",
+ "source_sha256": "hex-digest",
+ "slide_id": "slide-001",
+ "patient_id": "patient-001",
+ "split": "train",
+ "backend": "openslide",
+ "level": 0,
+ "downsample": 1.0,
+ "mpp_x": null,
+ "mpp_y": null,
+ "tile_size_ij": [512, 512],
+ "tile_stride_ij": [512, 512],
+ "tile_pad": false,
+ "pipeline_id": "he-v1",
+ "code_revision": "project-commit",
+ "created_utc": "RFC3339 timestamp"
+}
```
-### Chunking Strategy
+Do not put a direct identifier in these fields. Add:
-Optimize chunked storage for access patterns:
+- ordered transform parameters and fitted stain arrays;
+- mask/label schema;
+- QC counts and exclusion reasons;
+- dependency lock hash;
+- model artifact SHA-256 and license;
+- random seed manifest;
+- coordinate units and conversion;
+- output hashes and software/hardware details.
-```python
-# For tile-based access (access one tile at a time)
-with h5py.File('tiles.h5', 'w') as f:
- f.create_dataset(
- 'tiles',
- shape=(n_tiles, 256, 256, 3),
- dtype='uint8',
- chunks=(1, 256, 256, 3), # One tile per chunk
- compression='gzip'
- )
-
-# For channel-based access (access all tiles for one channel)
-with h5py.File('tiles.h5', 'w') as f:
- f.create_dataset(
- 'tiles',
- shape=(n_tiles, 256, 256, 3),
- dtype='uint8',
- chunks=(n_tiles, 256, 256, 1), # All tiles for one channel
- compression='gzip'
- )
-```
-
-### Memory-Mapped Arrays
-
-Use memory mapping for large arrays:
+Use SHA-256 for provenance:
```python
-import numpy as np
-
-# Save as memory-mapped file
-features_mmap = np.memmap(
- 'features/features.mmap',
- dtype='float32',
- mode='w+',
- shape=(n_tiles, feature_dim)
-)
-
-# Populate
-for i, tile in enumerate(wsi.tiles):
- features_mmap[i] = extract_features(tile)
-
-# Flush to disk
-features_mmap.flush()
-
-# Load without reading into memory
-features_mmap = np.memmap(
- 'features/features.mmap',
- dtype='float32',
- mode='r',
- shape=(n_tiles, feature_dim)
-)
-
-# Access subset efficiently
-subset = features_mmap[1000:2000] # Only loads requested rows
+import hashlib
+from pathlib import Path
+
+def sha256_file(path: Path, chunk_bytes: int = 1024 * 1024) -> str:
+ digest = hashlib.sha256()
+ with path.open("rb") as handle:
+ for chunk in iter(lambda: handle.read(chunk_bytes), b""):
+ digest.update(chunk)
+ return digest.hexdigest()
```
-## Best Practices
-
-1. **Use HDF5 for processed data:** Save preprocessed tiles and features to HDF5 for fast access
-
-2. **Separate raw and processed data:** Keep original slides separate from processed outputs
-
-3. **Maintain metadata:** Track slide provenance, processing parameters, and clinical annotations
-
-4. **Implement checksums:** Validate data integrity, especially after transfers
-
-5. **Version datasets:** Use DVC or similar tools to version large datasets
-
-6. **Optimize storage:** Balance compression level with I/O performance
-
-7. **Organize by cohort:** Structure directories by study cohort for clarity
-
-8. **Regular backups:** Back up both data and metadata to remote storage
-
-9. **Document processing:** Keep logs of processing steps, parameters, and versions
-
-10. **Monitor disk usage:** Track storage consumption as datasets grow
-
-## Common Issues and Solutions
-
-**Issue: HDF5 files very large**
-- Increase compression level: `compression_opts=9`
-- Store only necessary data (avoid redundant copies)
-- Use appropriate data types (uint8 for images vs. float64)
-
-**Issue: Slow HDF5 read/write**
-- Optimize chunk size for access pattern
-- Reduce compression level for faster I/O
-- Use SSD storage instead of HDD
-- Enable parallel HDF5 with MPI
-
-**Issue: Running out of disk space**
-- Delete intermediate files after processing
-- Compress inactive datasets
-- Move old data to archival storage
-- Use cloud storage for less-accessed data
-
-**Issue: Data corruption or loss**
-- Implement regular backups
-- Use RAID for redundancy
-- Validate checksums after transfers
-- Use version control (DVC)
-
-## Additional Resources
-
-- **HDF5 Documentation:** https://www.hdfgroup.org/solutions/hdf5/
-- **h5py:** https://docs.h5py.org/
-- **DVC (Data Version Control):** https://dvc.org/
-- **Dask:** https://docs.dask.org/
-- **PathML Data Management API:** https://pathml.readthedocs.io/en/latest/api_data_reference.html
+Hash only authorized local files and expect full-slide hashing to be I/O-heavy.
+Do not print paths containing identifiers.
+
+## Storage and lifecycle checklist
+
+- Estimate raw, temporary, `.h5path`, mask, count, graph, and model storage.
+- Write to a same-filesystem temporary destination, validate, then atomically
+ rename where possible.
+- Do not overwrite source slides.
+- Use private permissions and encrypted storage/backups.
+- Verify output counts, shapes, dtypes, coordinates, and hashes.
+- Record partial failures and retry policy.
+- Test disaster recovery and retention/deletion.
+- Do not commit slide data, model binaries, linkage files, or manifests with PHI.
+
+## Sources, accessed 2026-07-23
+
+- Stable h5path guide:
+ https://pathml.readthedocs.io/en/stable/h5path.html
+- Stable datasets guide:
+ https://pathml.readthedocs.io/en/stable/datasets.html
+- Stable datasets API:
+ https://pathml.readthedocs.io/en/stable/api_datasets_reference.html
+- Stable `TileDataset`/`EntityDataset` source:
+ https://github.com/Dana-Farber-AIOS/pathml/blob/v3.0.5/pathml/datasets/datasets.py
+- Stable PanNuke source:
+ https://github.com/Dana-Farber-AIOS/pathml/blob/v3.0.5/pathml/datasets/pannuke.py
+- Stable DeepFocus source:
+ https://github.com/Dana-Farber-AIOS/pathml/blob/v3.0.5/pathml/datasets/deepfocus.py
+- PanNuke extension paper: https://arxiv.org/abs/2003.10778
+- DeepFocus paper: https://doi.org/10.1371/journal.pone.0205387
diff --git a/skills/pathml/references/graphs.md b/skills/pathml/references/graphs.md
index d50617f5..56133fd1 100644
--- a/skills/pathml/references/graphs.md
+++ b/skills/pathml/references/graphs.md
@@ -1,653 +1,335 @@
-# Graph Construction & Spatial Analysis
+# Graph construction and spatial schema
-## Overview
+This reference targets **PathML 3.0.5 stable**. The stable graph API is based on
+graph builders and PyTorch Geometric data objects; it does not contain the
+`CellGraph.from_instance_map()` abstraction found in older generated examples.
-PathML provides tools for constructing spatial graphs from tissue images to represent cellular and tissue-level relationships. Graph-based representations enable sophisticated spatial analysis, including neighborhood analysis, cell-cell interaction studies, and graph neural network applications. These graphs capture both morphological features and spatial topology for downstream computational analysis.
+## Stable public exports
-## Graph Types
-
-PathML supports construction of multiple graph types:
-
-### Cell Graphs
-- Nodes represent individual cells
-- Edges represent spatial proximity or biological interactions
-- Node features include morphology, marker expression, cell type
-- Suitable for single-cell spatial analysis
-
-### Tissue Graphs
-- Nodes represent tissue regions or superpixels
-- Edges represent spatial adjacency
-- Node features include tissue composition, texture features
-- Suitable for tissue-level spatial patterns
-
-### Spatial Transcriptomics Graphs
-- Nodes represent spatial spots or cells
-- Edges encode spatial relationships
-- Node features include gene expression profiles
-- Suitable for spatial omics analysis
-
-## Graph Construction Workflow
-
-### From Segmentation to Graphs
-
-Convert nucleus or cell segmentation results into spatial graphs:
-
-```python
-from pathml.graph import CellGraph
-from pathml.preprocessing import Pipeline, SegmentMIF
-import numpy as np
-
-# 1. Perform cell segmentation
-pipeline = Pipeline([
- SegmentMIF(
- nuclear_channel='DAPI',
- cytoplasm_channel='CD45',
- model='mesmer'
- )
-])
-pipeline.run(slide)
-
-# 2. Extract instance segmentation mask
-inst_map = slide.masks['cell_segmentation']
-
-# 3. Build cell graph
-cell_graph = CellGraph.from_instance_map(
- inst_map,
- image=slide.image, # Optional: for extracting visual features
- connectivity='delaunay', # 'knn', 'radius', or 'delaunay'
- k=5, # For knn: number of neighbors
- radius=50 # For radius: distance threshold in pixels
-)
-
-# 4. Access graph components
-nodes = cell_graph.nodes # Node features
-edges = cell_graph.edges # Edge list
-adjacency = cell_graph.adjacency_matrix # Adjacency matrix
-```
-
-### Connectivity Methods
-
-**K-Nearest Neighbors (KNN):**
-```python
-# Connect each cell to its k nearest neighbors
-graph = CellGraph.from_instance_map(
- inst_map,
- connectivity='knn',
- k=5 # Number of neighbors
-)
-```
-- Fixed degree per node
-- Captures local neighborhoods
-- Simple and interpretable
-
-**Radius-based:**
-```python
-# Connect cells within a distance threshold
-graph = CellGraph.from_instance_map(
- inst_map,
- connectivity='radius',
- radius=100, # Maximum distance in pixels
- distance_metric='euclidean' # or 'manhattan', 'chebyshev'
-)
-```
-- Variable degree based on density
-- Biologically motivated (interaction range)
-- Captures physical proximity
-
-**Delaunay Triangulation:**
```python
-# Connect cells using Delaunay triangulation
-graph = CellGraph.from_instance_map(
- inst_map,
- connectivity='delaunay'
+from pathml.graph import (
+ ColorMergedSuperpixelExtractor,
+ Graph,
+ HACTPairData,
+ KNNGraphBuilder,
+ RAGGraphBuilder,
+ build_assignment_matrix,
+ get_full_instance_map,
)
```
-- Creates connected graph from spatial positions
-- No isolated nodes (in convex hull)
-- Captures spatial tessellation
-**Contact-based:**
-```python
-# Connect cells with touching boundaries
-graph = CellGraph.from_instance_map(
- inst_map,
- connectivity='contact',
- dilation=2 # Dilate boundaries to capture near-contacts
-)
-```
-- Physical cell-cell contacts
-- Most biologically direct
-- Sparse edges for separated cells
+Other classes documented under `pathml.graph.preprocessing` may be internal or
+not re-exported. Prefer the public names above and pin the PathML version.
-## Node Features
+## Inputs and coordinate contract
-### Morphological Features
+A cell/tissue graph starts with:
-Extract shape and size features for each cell:
+1. an instance map `(height, width)`, where 0 is background and each object has a
+ positive integer label;
+2. one feature row per object;
+3. optional node annotation rows and a graph target; and
+4. explicit coordinate units and image level.
-```python
-from pathml.graph import extract_morphology_features
-
-# Compute morphological features
-morphology_features = extract_morphology_features(
- inst_map,
- features=[
- 'area', # Cell area in pixels
- 'perimeter', # Cell perimeter
- 'eccentricity', # Shape elongation
- 'solidity', # Convexity measure
- 'major_axis_length',
- 'minor_axis_length',
- 'orientation' # Cell orientation angle
- ]
-)
+For stable builders, make labels contiguous `1..N`. Both graph topology and
+feature alignment assume a deterministic object order. Build and persist a table:
-# Add to graph
-cell_graph.add_node_features(morphology_features, feature_names=['area', 'perimeter', ...])
+```text
+node_index,instance_label,centroid_x,centroid_y,feature_row
+0,1,120.5,88.0,0
+1,2,175.0,92.5,1
```
-**Available morphological features:**
-- **Area** - Number of pixels
-- **Perimeter** - Boundary length
-- **Eccentricity** - 0 (circle) to 1 (line)
-- **Solidity** - Area / convex hull area
-- **Circularity** - 4π × area / perimeter²
-- **Major/Minor axis** - Lengths of fitted ellipse axes
-- **Orientation** - Angle of major axis
-- **Extent** - Area / bounding box area
-
-### Intensity Features
+PathML computes centroids from `skimage.measure.regionprops` and stores them as
+`(x, y)` after integer rounding. This differs from tile `(i, j)` order.
-Extract marker expression or intensity statistics:
+If the instance map comes from level `L`, KNN distances and centroids are in
+level-`L` pixels:
-```python
-from pathml.graph import extract_intensity_features
-
-# Extract mean marker intensities per cell
-intensity_features = extract_intensity_features(
- inst_map,
- image=multichannel_image, # Shape: (H, W, C)
- channel_names=['DAPI', 'CD3', 'CD4', 'CD8', 'CD20'],
- statistics=['mean', 'std', 'median', 'max']
-)
-
-# Add to graph
-cell_graph.add_node_features(
- intensity_features,
- feature_names=['DAPI_mean', 'CD3_mean', ...]
-)
+```text
+x_um = x_L * downsample_L * mpp_x
+y_um = y_L * downsample_L * mpp_y
```
-**Available statistics:**
-- **mean** - Average intensity
-- **median** - Median intensity
-- **std** - Standard deviation
-- **max** - Maximum intensity
-- **min** - Minimum intensity
-- **quantile_25/75** - Quartiles
+Never describe a radius/threshold as biological distance unless it has been
+converted to a physical unit.
-### Texture Features
+## Avoid full-slide reconstruction by default
-Compute texture descriptors for each cell region:
+`get_full_instance_map(wsi, patch_size, mask_name="cell")` reconstructs a dense
+image and instance map large enough to cover the slide. On a gigapixel WSI this
+can exhaust RAM and duplicate tile-overlap objects.
-```python
-from pathml.graph import extract_texture_features
-
-# Haralick texture features
-texture_features = extract_texture_features(
- inst_map,
- image=grayscale_image,
- features='haralick', # or 'lbp', 'gabor'
- distance=1,
- angles=[0, np.pi/4, np.pi/2, 3*np.pi/4]
-)
+Use it only for a bounded ROI or small image after estimating memory. For large
+slides:
-cell_graph.add_node_features(texture_features)
-```
+- construct graphs per nonoverlapping region;
+- reconcile boundary objects with stable global IDs;
+- optionally join regional graphs with a documented edge policy; and
+- use sparse coordinates/features rather than a dense whole-slide canvas.
-### Cell Type Annotations
+Do not use padded zero regions as tissue. Record crop origin so local coordinates
+can be mapped to the slide.
-Add cell type labels from classification:
+## KNN graph
```python
-# From ML model predictions
-cell_types = hovernet_type_predictions # Array of cell type IDs
+import numpy as np
+from pathml.graph import KNNGraphBuilder
-cell_graph.add_node_features(
- cell_types,
- feature_names=['cell_type']
-)
+# instance_map labels are 0 background, then contiguous 1..N.
+n_nodes = int(instance_map.max())
+features = np.ones((n_nodes, 1), dtype=np.float32)
-# One-hot encode cell types
-cell_type_onehot = one_hot_encode(cell_types, num_classes=5)
-cell_graph.add_node_features(
- cell_type_onehot,
- feature_names=['type_epithelial', 'type_inflammatory', ...]
+builder = KNNGraphBuilder(
+ k=5,
+ thresh=80, # selected-level pixels
+ add_loc_feats=True,
+ return_networkx=False,
)
-```
-
-## Edge Features
-
-### Spatial Distance
-
-Compute edge features based on spatial relationships:
-
-```python
-from pathml.graph import compute_edge_distances
-
-# Add pairwise distances as edge features
-distances = compute_edge_distances(
- cell_graph,
- metric='euclidean' # or 'manhattan', 'chebyshev'
+graph = builder.process(
+ instance_map,
+ features=features,
+ annotation=None,
+ target=None,
)
-
-cell_graph.add_edge_features(distances, feature_names=['distance'])
```
-### Interaction Features
-
-Model biological interactions between cell types:
+Stable behavior:
-```python
-from pathml.graph import compute_interaction_features
-
-# Cell type co-occurrence along edges
-interaction_features = compute_interaction_features(
- cell_graph,
- cell_types=cell_type_labels,
- interaction_type='categorical' # or 'numerical'
-)
-
-cell_graph.add_edge_features(interaction_features)
-```
+- `k` nearest neighbors are computed from centroids.
+- `thresh=None` keeps all KNN edges; otherwise edges longer than `thresh` are
+ removed.
+- `k` must be smaller than the available node count.
+- adjacency generated by nearest-neighbor queries may be directed; do not assume
+ every reverse edge exists.
+- `add_loc_feats=True` appends centroids normalized by image width/height.
+- `return_networkx` is a **builder constructor** option, not an argument to
+ `process()`.
-## Graph-Level Features
+In v3.0.5 source, `BaseGraphBuilder.process()` reads `features.shape` before its
+nominal `features=None` branch. Pass an explicit `(N, F)` feature array.
-Aggregate features for entire graph:
+## Region adjacency graph
```python
-from pathml.graph import compute_graph_features
-
-# Topological features
-graph_features = compute_graph_features(
- cell_graph,
- features=[
- 'num_nodes',
- 'num_edges',
- 'average_degree',
- 'clustering_coefficient',
- 'average_path_length',
- 'diameter'
- ]
-)
+from pathml.graph import RAGGraphBuilder
-# Cell composition features
-composition = cell_graph.compute_cell_type_composition(
- cell_type_labels,
- normalize=True # Proportions
+builder = RAGGraphBuilder(
+ kernel_size=3,
+ hops=1,
+ add_loc_feats=False,
+ return_networkx=False,
)
+graph = builder.process(instance_map, features=features)
```
-## Spatial Analysis
+`RAGGraphBuilder` dilates each labeled instance and connects labels encountered at
+the boundary. `hops>1` expands neighborhoods. Stable implementation assumes
+contiguous positive instance IDs; relabel and validate first.
-### Neighborhood Analysis
+Choose RAG for contact/near-contact topology and KNN for centroid proximity. A
+RAG edge is still an image-processing construct, not proof of biological
+interaction.
-Analyze cell neighborhoods and microenvironments:
+## Tissue superpixels
-```python
-from pathml.graph import analyze_neighborhoods
-
-# Characterize neighborhoods around each cell
-neighborhoods = analyze_neighborhoods(
- cell_graph,
- cell_types=cell_type_labels,
- radius=100, # Neighborhood radius
- metrics=['diversity', 'density', 'composition']
-)
+`ColorMergedSuperpixelExtractor` performs SLIC superpixels followed by
+color-based hierarchical merging. Its output depends on image color space,
+downsampling, blur, target superpixel size/count, merge threshold, and optional
+tissue mask.
-# Neighborhood diversity (Shannon entropy)
-diversity = neighborhoods['diversity']
+Fit/tune these choices on training slides only. Verify:
-# Cell type composition in each neighborhood
-composition = neighborhoods['composition'] # (n_cells, n_cell_types)
-```
+- every retained superpixel overlaps tissue as intended;
+- object labels are contiguous;
+- tiny/huge regions and holes are handled;
+- downsampled boundaries map correctly to the source level;
+- stain normalization did not erase discriminative structure.
-### Spatial Clustering
+The extractor is influenced by histocartography/HACT implementations. Review
+license obligations when redistributing derived code or artifacts.
-Identify spatial clusters of cell types:
+## Output schema
-```python
-from pathml.graph import spatial_clustering
-import matplotlib.pyplot as plt
-
-# Detect spatial clusters
-clusters = spatial_clustering(
- cell_graph,
- cell_positions,
- method='dbscan', # or 'kmeans', 'hierarchical'
- eps=50, # DBSCAN: neighborhood radius
- min_samples=10 # DBSCAN: minimum cluster size
-)
+Stable `pathml.graph.Graph` is a PyTorch Geometric `Data` subclass with:
-# Visualize clusters
-plt.scatter(
- cell_positions[:, 0],
- cell_positions[:, 1],
- c=clusters,
- cmap='tab20'
-)
-plt.title('Spatial Clusters')
-plt.show()
+```text
+node_centroids # tensor [N, 2], (x, y)
+node_features # tensor [N, F] or None
+edge_index # tensor [2, E]
+edge_features # tensor/array or None
+node_labels # tensor/array or None
+target # graph target or None
```
-### Cell-Cell Interaction Analysis
-
-Test for enrichment or depletion of cell type interactions:
+It does not automatically expose canonical PyG `x`, `pos`, `edge_attr`, and `y`
+aliases. Adapt explicitly:
```python
-from pathml.graph import cell_interaction_analysis
-
-# Test for significant interactions
-interaction_results = cell_interaction_analysis(
- cell_graph,
- cell_types=cell_type_labels,
- method='permutation', # or 'expected'
- n_permutations=1000,
- significance_level=0.05
-)
+from torch_geometric.data import Data
-# Interaction scores (positive = attraction, negative = avoidance)
-interaction_matrix = interaction_results['scores']
-
-# Visualize with heatmap
-import seaborn as sns
-sns.heatmap(
- interaction_matrix,
- cmap='RdBu_r',
- center=0,
- xticklabels=cell_type_names,
- yticklabels=cell_type_names
+pyg_graph = Data(
+ x=graph.node_features,
+ pos=graph.node_centroids,
+ edge_index=graph.edge_index,
+ edge_attr=graph.edge_features,
+ y=graph.target,
)
-plt.title('Cell-Cell Interaction Scores')
-plt.show()
```
-### Spatial Statistics
-
-Compute spatial statistics and patterns:
+Validate shapes before training:
```python
-from pathml.graph import spatial_statistics
-
-# Ripley's K function for spatial point patterns
-ripleys_k = spatial_statistics(
- cell_positions,
- cell_types=cell_type_labels,
- statistic='ripleys_k',
- radii=np.linspace(0, 200, 50)
-)
-
-# Nearest neighbor distances
-nn_distances = spatial_statistics(
- cell_positions,
- statistic='nearest_neighbor',
- by_cell_type=True
-)
+assert graph.node_centroids.ndim == 2
+assert graph.node_centroids.shape[1] == 2
+assert graph.node_features.shape[0] == graph.node_centroids.shape[0]
+assert graph.edge_index.shape[0] == 2
+assert int(graph.edge_index.min()) >= 0
+assert int(graph.edge_index.max()) < graph.node_centroids.shape[0]
```
-## Integration with Graph Neural Networks
-
-### Convert to PyTorch Geometric Format
-
-```python
-from pathml.graph import to_pyg
-import torch
-from torch_geometric.data import Data
-
-# Convert to PyTorch Geometric Data object
-pyg_data = cell_graph.to_pyg()
-
-# Access components
-x = pyg_data.x # Node features (n_nodes, n_features)
-edge_index = pyg_data.edge_index # Edge connectivity (2, n_edges)
-edge_attr = pyg_data.edge_attr # Edge features (n_edges, n_edge_features)
-y = pyg_data.y # Graph-level label
-pos = pyg_data.pos # Node positions (n_nodes, 2)
-
-# Use with PyTorch Geometric
-from torch_geometric.nn import GCNConv
-
-class GNN(torch.nn.Module):
- def __init__(self, in_channels, hidden_channels, out_channels):
- super().__init__()
- self.conv1 = GCNConv(in_channels, hidden_channels)
- self.conv2 = GCNConv(hidden_channels, out_channels)
-
- def forward(self, data):
- x, edge_index = data.x, data.edge_index
- x = self.conv1(x, edge_index).relu()
- x = self.conv2(x, edge_index)
- return x
-
-model = GNN(in_channels=pyg_data.num_features, hidden_channels=64, out_channels=5)
-output = model(pyg_data)
+Handle empty/no-edge graphs before `min()`/`max()`. Check finite values,
+self-loops, duplicates, connected components, degree distribution, and edge
+direction.
+
+## Exchange schema and validator
+
+For safer exchange, use bounded JSON rather than a pickled `.pt` object:
+
+```json
+{
+ "schema_version": "1.0",
+ "slide_id": "slide-001",
+ "coordinate_unit": "um",
+ "nodes": [
+ {"id": "cell-1", "x": 12.5, "y": 30.0, "features": [0.2, 1.3]},
+ {"id": "cell-2", "x": 15.0, "y": 32.0, "features": [0.4, 1.1]}
+ ],
+ "edges": [
+ {"source": "cell-1", "target": "cell-2"}
+ ]
+}
```
-### Graph Dataset for Multiple Slides
+Validate:
-```python
-from pathml.graph import GraphDataset
-from torch_geometric.loader import DataLoader
-
-# Create dataset of graphs from multiple slides
-graphs = []
-for slide in slides:
- # Build graph for each slide
- cell_graph = CellGraph.from_instance_map(slide.inst_map, ...)
- pyg_graph = cell_graph.to_pyg()
- graphs.append(pyg_graph)
-
-# Create DataLoader
-loader = DataLoader(graphs, batch_size=32, shuffle=True)
-
-# Train GNN
-for batch in loader:
- output = model(batch)
- loss = criterion(output, batch.y)
- loss.backward()
- optimizer.step()
+```bash
+python scripts/validate_spatial_schema.py graph \
+ --input derived/graph.json \
+ --root . \
+ --max-nodes 100000 \
+ --max-edges 1000000
```
-## Visualization
+The validator checks strict JSON, bounded counts, unique node IDs, finite
+coordinates/features, explicit units, valid edge endpoints, self-loops, and
+duplicate edges. It never imports Torch or loads `.pt`.
-### Graph Visualization
+## HACT cell-to-tissue graphs
-```python
-import matplotlib.pyplot as plt
-import networkx as nx
-
-# Convert to NetworkX
-nx_graph = cell_graph.to_networkx()
-
-# Draw graph with cell positions as layout
-pos = {i: cell_graph.positions[i] for i in range(len(cell_graph.nodes))}
-
-plt.figure(figsize=(12, 12))
-nx.draw_networkx(
- nx_graph,
- pos=pos,
- node_color=cell_type_labels,
- node_size=50,
- cmap='tab10',
- with_labels=False,
- alpha=0.8
-)
-plt.axis('equal')
-plt.title('Cell Graph')
-plt.show()
-```
-
-### Overlay on Tissue Image
+HACT represents:
-```python
-from pathml.graph import visualize_graph_on_image
-
-# Visualize graph overlaid on tissue
-fig, ax = plt.subplots(figsize=(15, 15))
-ax.imshow(tissue_image)
-
-# Draw edges
-for edge in cell_graph.edges:
- node1, node2 = edge
- pos1 = cell_graph.positions[node1]
- pos2 = cell_graph.positions[node2]
- ax.plot([pos1[0], pos2[0]], [pos1[1], pos2[1]], 'b-', alpha=0.3, linewidth=0.5)
-
-# Draw nodes colored by type
-for cell_type in np.unique(cell_type_labels):
- mask = cell_type_labels == cell_type
- positions = cell_graph.positions[mask]
- ax.scatter(positions[:, 0], positions[:, 1], label=f'Type {cell_type}', s=20)
-
-ax.legend()
-ax.axis('off')
-plt.title('Cell Graph on Tissue')
-plt.show()
-```
+- a cell graph;
+- a tissue/superpixel graph; and
+- an assignment from each cell to a tissue node.
-## Complete Workflow Example
+Stable helper:
```python
-from pathml.core import SlideData, CODEXSlide
-from pathml.preprocessing import Pipeline, CollapseRunsCODEX, SegmentMIF
-from pathml.graph import CellGraph, extract_morphology_features, extract_intensity_features
-import matplotlib.pyplot as plt
-
-# 1. Load and preprocess slide
-slide = CODEXSlide('path/to/codex', stain='IF')
-
-pipeline = Pipeline([
- CollapseRunsCODEX(z_slice=2),
- SegmentMIF(
- nuclear_channel='DAPI',
- cytoplasm_channel='CD45',
- model='mesmer'
- )
-])
-pipeline.run(slide)
-
-# 2. Build cell graph
-inst_map = slide.masks['cell_segmentation']
-cell_graph = CellGraph.from_instance_map(
- inst_map,
- image=slide.image,
- connectivity='knn',
- k=6
-)
+from pathml.graph import build_assignment_matrix
-# 3. Extract features
-# Morphological features
-morph_features = extract_morphology_features(
- inst_map,
- features=['area', 'perimeter', 'eccentricity', 'solidity']
-)
-cell_graph.add_node_features(morph_features)
-
-# Intensity features (marker expression)
-intensity_features = extract_intensity_features(
- inst_map,
- image=slide.image,
- channel_names=['DAPI', 'CD3', 'CD4', 'CD8', 'CD20'],
- statistics=['mean', 'std']
+assignment_sparse = build_assignment_matrix(
+ low_level_centroids=cell_centroids_xy,
+ high_level_map=tissue_instance_map,
+ matrix=False,
)
-cell_graph.add_node_features(intensity_features)
+```
-# 4. Spatial analysis
-from pathml.graph import analyze_neighborhoods
+Inputs must share the same origin, level, orientation, and units.
+`cell_centroids_xy` is `(x, y)`; the helper indexes the image as `[y, x]`.
+Tissue labels should be contiguous positive IDs. Cells on background or outside
+the map require an explicit policy before calling the helper.
-neighborhoods = analyze_neighborhoods(
- cell_graph,
- cell_types=cell_type_predictions,
- radius=100,
- metrics=['diversity', 'composition']
-)
+`HACTPairData` stores:
-# 5. Export for GNN
-pyg_data = cell_graph.to_pyg()
-
-# 6. Visualize
-plt.figure(figsize=(15, 15))
-plt.imshow(slide.image)
-
-# Overlay graph
-nx_graph = cell_graph.to_networkx()
-pos = {i: cell_graph.positions[i] for i in range(cell_graph.num_nodes)}
-nx.draw_networkx(
- nx_graph,
- pos=pos,
- node_color=cell_type_predictions,
- cmap='tab10',
- node_size=30,
- with_labels=False
-)
-plt.axis('off')
-plt.title('Cell Graph with Spatial Neighborhood')
-plt.show()
+```text
+x_cell, edge_index_cell,
+x_tissue, edge_index_tissue,
+assignment, target
```
-## Performance Considerations
+PathML's `EntityDataset` can assemble these from `.pt` files, but stable source
+uses unrestricted PyTorch object loading. Never use it on untrusted artifacts.
-**Large tissue sections:**
-- Build graphs tile-by-tile, then merge
-- Use sparse adjacency matrices
-- Leverage GPU for feature extraction
+## Graph feature extraction
-**Memory efficiency:**
-- Store only necessary edge features
-- Use int32/float32 instead of int64/float64
-- Batch process multiple slides
+Node features may include:
-**Computational efficiency:**
-- Parallelize feature extraction across cells
-- Use KNN for faster neighbor queries
-- Cache computed features
+- morphology from the instance mask;
+- marker intensities from a validated channel manifest;
+- learned image embeddings from a trusted local model;
+- cell-type probabilities rather than hard labels; and
+- normalized position, when scientifically justified.
-## Best Practices
+Keep a schema with feature name, unit, transform, missing policy, and training-only
+fit provenance. PathML graph builders do not provide the broad fabricated helper
+catalog (`extract_morphology_features`, `extract_intensity_features`,
+`analyze_neighborhoods`, and similar) shown in older references. Use
+scikit-image/pandas or a reviewed feature package explicitly.
-1. **Choose appropriate connectivity:** KNN for uniform analysis, radius for physical interactions, contact for direct cell-cell communication
+Graph-level topology features can be extracted with
+`pathml.graph.preprocessing.GraphFeatureExtractor`, but disconnected graphs may
+make diameter/radius undefined and some centrality algorithms may not converge.
+Validate topology and handle exceptions rather than dropping graphs silently.
-2. **Normalize features:** Scale morphological and intensity features for GNN compatibility
+## Boundary and overlap policy
-3. **Handle edge effects:** Exclude boundary cells or use tissue masks to define valid regions
+Overlapping tiles can create duplicate cells and duplicated edges. Choose one:
-4. **Validate graph construction:** Visualize graphs on small regions before large-scale processing
+- keep only each tile's central crop;
+- reconcile objects by global coordinates and mask overlap;
+- run segmentation on a larger context but emit a nonoverlapping center;
+- construct per-region graphs and join only verified boundary nodes.
-5. **Combine multiple feature types:** Morphology + intensity + texture provides rich representations
+Record:
-6. **Consider tissue context:** Tissue type affects appropriate graph parameters (connectivity, radius)
+- context and emission windows;
+- global instance ID scheme;
+- duplicate matching threshold;
+- edge creation across boundaries;
+- excluded border-object count; and
+- stitching/reconciliation software version.
-## Common Issues and Solutions
+## Leakage and evaluation
-**Issue: Too many/few edges**
-- Adjust k (KNN) or radius (radius-based) parameters
-- Verify pixel-to-micron conversion for biological relevance
+Graph construction must happen after patient/slide splits. Keep all subgraphs from
+one slide in one split. Fit feature scalers, dimensionality reduction,
+neighborhood thresholds, graph augmentations, and class balancing on training
+graphs only.
-**Issue: Memory errors with large graphs**
-- Process tiles separately and merge graphs
-- Use sparse matrix representations
-- Reduce edge features to essential ones
+Report:
-**Issue: Missing cells at tissue boundaries**
-- Apply edge_correction parameter
-- Use tissue masks to exclude invalid regions
+- patient and slide counts, not only graph counts;
+- node/edge distributions by split;
+- site/scanner/stain balance;
+- isolated/disconnected graph handling;
+- external-slide/site validation where relevant;
+- uncertainty and confidence intervals at the patient/slide unit.
-**Issue: Inconsistent feature scales**
-- Normalize features: `(x - mean) / std`
-- Use robust scaling for outliers
+Do not treat thousands of correlated nodes or tiles as independent patients.
-## Additional Resources
+## Sources, accessed 2026-07-23
-- **PathML Graph API:** https://pathml.readthedocs.io/en/latest/api_graph_reference.html
-- **PyTorch Geometric:** https://pytorch-geometric.readthedocs.io/
-- **NetworkX:** https://networkx.org/
-- **Spatial Statistics:** Baddeley et al., "Spatial Point Patterns: Methodology and Applications with R"
+- Stable graph guide:
+ https://pathml.readthedocs.io/en/stable/graphs.html
+- Stable graph API:
+ https://pathml.readthedocs.io/en/stable/api_graph_reference.html
+- Stable graph builder source:
+ https://github.com/Dana-Farber-AIOS/pathml/blob/v3.0.5/pathml/graph/preprocessing.py
+- Stable graph schema/helpers:
+ https://github.com/Dana-Farber-AIOS/pathml/blob/v3.0.5/pathml/graph/utils.py
+- Pati et al. (2022), HACT:
+ https://doi.org/10.1016/j.media.2021.102264
+- Jaume et al. (2021), histocartography:
+ https://proceedings.mlr.press/v156/jaume21a.html
diff --git a/skills/pathml/references/image_loading.md b/skills/pathml/references/image_loading.md
index fc3f3368..13b9d7dd 100644
--- a/skills/pathml/references/image_loading.md
+++ b/skills/pathml/references/image_loading.md
@@ -1,448 +1,301 @@
-# Image Loading & Formats
+# Image loading, formats, levels, and coordinates
-## Overview
+This reference targets the **PyPI-stable PathML 3.0.5 API**. All sources were
+checked on 2026-07-23 against the v3.0.5 tag and stable ReadTheDocs build.
-PathML provides comprehensive support for loading whole-slide images (WSI) from 160+ proprietary medical imaging formats. The framework abstracts vendor-specific complexities through unified slide classes and interfaces, enabling seamless access to image pyramids, metadata, and regions of interest across different file formats.
+## Start with a local, de-identified file
-## Supported Formats
+Never infer authorization from the fact that a file is readable. Whole-slide
+images and DICOM objects can carry identifiers in pixels, labels, filenames, and
+metadata. Keep the original on approved storage, use a pseudonymous working name,
+and do not print arbitrary metadata. The bundled inspector emits only an
+allowlist of technical fields:
-PathML supports the following slide formats:
-
-### Brightfield Microscopy Formats
-- **Aperio SVS** (`.svs`) - Leica Biosystems
-- **Hamamatsu NDPI** (`.ndpi`) - Hamamatsu Photonics
-- **Leica SCN** (`.scn`) - Leica Biosystems
-- **Zeiss ZVI** (`.zvi`) - Carl Zeiss
-- **3DHISTECH** (`.mrxs`) - 3DHISTECH Ltd.
-- **Ventana BIF** (`.bif`) - Roche Ventana
-- **Generic tiled TIFF** (`.tif`, `.tiff`)
-
-### Medical Imaging Standards
-- **DICOM** (`.dcm`) - Digital Imaging and Communications in Medicine
-- **OME-TIFF** (`.ome.tif`, `.ome.tiff`) - Open Microscopy Environment
-
-### Multiparametric Imaging
-- **CODEX** - Spatial proteomics imaging
-- **Vectra** (`.qptiff`) - Multiplex immunofluorescence
-- **MERFISH** - Multiplexed error-robust FISH
-
-PathML leverages OpenSlide and other specialized libraries to handle format-specific nuances automatically.
-
-## Core Classes for Loading Images
-
-### SlideData
-
-`SlideData` is the fundamental class for representing whole-slide images in PathML.
-
-**Loading from file:**
-```python
-from pathml.core import SlideData
-
-# Load a whole-slide image
-wsi = SlideData.from_slide("path/to/slide.svs")
-
-# Load with specific backend
-wsi = SlideData.from_slide("path/to/slide.svs", backend="openslide")
-
-# Load from OME-TIFF
-wsi = SlideData.from_slide("path/to/slide.ome.tiff", backend="bioformats")
-```
-
-**Key attributes:**
-- `wsi.slide` - Backend slide object (OpenSlide, BioFormats, etc.)
-- `wsi.tiles` - Collection of image tiles
-- `wsi.metadata` - Slide metadata dictionary
-- `wsi.level_dimensions` - Image pyramid level dimensions
-- `wsi.level_downsamples` - Downsample factors for each pyramid level
-
-**Methods:**
-- `wsi.generate_tiles()` - Generate tiles from the slide
-- `wsi.read_region()` - Read a specific region at a given level
-- `wsi.get_thumbnail()` - Get a thumbnail image
-
-### SlideType
-
-`SlideType` is an enumeration defining supported slide backends:
-
-```python
-from pathml.core import SlideType
-
-# Available backends
-SlideType.OPENSLIDE # For most WSI formats (SVS, NDPI, etc.)
-SlideType.BIOFORMATS # For OME-TIFF and other formats
-SlideType.DICOM # For DICOM WSI
-SlideType.VectraQPTIFF # For Vectra multiplex IF
+```bash
+python scripts/slide_manifest.py inspect \
+ --slide data/pseudonymous_slide.svs \
+ --root .
```
-### Specialized Slide Classes
+It rejects URLs and symlinks. PathML itself accepts paths more broadly, so validate
+before constructing a slide object.
-PathML provides specialized slide classes for specific imaging modalities:
+## Stable slide classes
-**CODEXSlide:**
```python
-from pathml.core import CODEXSlide
-
-# Load CODEX spatial proteomics data
-codex_slide = CODEXSlide(
- path="path/to/codex_dir",
- stain="IF", # Immunofluorescence
- backend="bioformats"
+from pathml.core import (
+ CODEXSlide,
+ HESlide,
+ IHCSlide,
+ MultiparametricSlide,
+ SlideData,
+ SlideDataset,
+ VectraSlide,
+ types,
)
```
-**VectraSlide:**
-```python
-from pathml.core import types
+Convenience classes pass a stable `SlideType`:
-# Load Vectra multiplex IF data
-vectra_slide = SlideData.from_slide(
- "path/to/vectra.qptiff",
- backend=SlideType.VectraQPTIFF
-)
-```
+- `HESlide(...)` → `types.HE`
+- `IHCSlide(...)` → `types.IHC`
+- `MultiparametricSlide(...)` → `types.IF`, Bio-Formats by default
+- `VectraSlide(...)` → `types.Vectra`, Bio-Formats by default
+- `CODEXSlide(...)` → `types.CODEX`, Bio-Formats by default
-**MultiparametricSlide:**
-```python
-from pathml.core import MultiparametricSlide
-
-# Generic multiparametric imaging
-mp_slide = MultiparametricSlide(path="path/to/multiparametric_data")
-```
-
-## Loading Strategies
-
-### Tile-Based Loading
-
-For large WSI files, tile-based loading enables memory-efficient processing:
+The generic constructor is:
```python
-from pathml.core import SlideData
-
-# Load slide
-wsi = SlideData.from_slide("path/to/slide.svs")
-
-# Generate tiles at specific magnification level
-wsi.generate_tiles(
- level=0, # Pyramid level (0 = highest resolution)
- tile_size=256, # Tile dimensions in pixels
- stride=256, # Spacing between tiles (256 = no overlap)
- pad=False # Whether to pad edge tiles
-)
-
-# Iterate over tiles
-for tile in wsi.tiles:
- image = tile.image # numpy array
- coords = tile.coords # (x, y) coordinates
- # Process tile...
-```
-
-**Overlapping tiles:**
-```python
-# Generate tiles with 50% overlap
-wsi.generate_tiles(
- level=0,
- tile_size=256,
- stride=128 # 50% overlap
+slide = SlideData(
+ "data/pseudonymous_slide.svs",
+ name="slide-001",
+ backend="openslide",
+ slide_type=types.HE,
)
```
-### Region-Based Loading
+`SlideData.from_slide()`, `read_region()`, `level_dimensions`, and
+`level_downsamples` are not stable `SlideData` APIs. Use the constructor,
+`extract_region()`, `shape`, and backend-specific objects where necessary.
-Extract specific regions of interest directly:
+For a local cohort, instantiate slides first:
```python
-# Read region at specific location and level
-region = wsi.read_region(
- location=(10000, 15000), # (x, y) in level 0 coordinates
- level=1, # Pyramid level
- size=(512, 512) # Width, height in pixels
-)
+from pathlib import Path
+from pathml.core import HESlide, SlideDataset
-# Returns numpy array
+root = Path("data/slides")
+paths = sorted(root.glob("*.svs"))
+slides = [HESlide(path, backend="openslide", name=path.stem) for path in paths]
+dataset = SlideDataset(slides)
```
-### Pyramid Level Selection
+Do not recursively accept arbitrary user-controlled paths. Validate a manifest,
+freeze the patient split, and then build this list.
-Whole-slide images are stored in multi-resolution pyramids. Select the appropriate level based on desired magnification:
+## Backends and file types
-```python
-# Inspect available levels
-print(wsi.level_dimensions) # [(width0, height0), (width1, height1), ...]
-print(wsi.level_downsamples) # [1.0, 4.0, 16.0, ...]
+### OpenSlide
-# Load at lower resolution for faster processing
-wsi.generate_tiles(level=2, tile_size=256) # Use level 2 (16x downsampled)
-```
+Use `backend="openslide"` for common brightfield pyramid formats. Stable PathML
+lists:
-**Common pyramid levels:**
-- Level 0: Full resolution (e.g., 40x magnification)
-- Level 1: 4x downsampled (e.g., 10x magnification)
-- Level 2: 16x downsampled (e.g., 2.5x magnification)
-- Level 3: 64x downsampled (thumbnail)
+`.svs`, `.tif`, `.tiff`, `.bif`, `.ndpi`, `.vms`, `.vmu`, `.scn`, `.mrxs`,
+and `.svslide`.
-### Thumbnail Loading
+The complete capability depends on the installed OpenSlide build and the vendor
+subtype, not only the suffix. Some generic TIFFs are not valid WSIs, and some
+files with a supported suffix use unsupported compression.
-Generate low-resolution thumbnails for visualization and quality control:
+Native OpenSlide is required. Official PathML guidance uses
+`openslide-tools` on Debian/Ubuntu, Homebrew `openslide` on macOS, and vcpkg or
+official prebuilt binaries on Windows.
-```python
-# Get thumbnail
-thumbnail = wsi.get_thumbnail(size=(1024, 1024))
-
-# Display with matplotlib
-import matplotlib.pyplot as plt
-plt.imshow(thumbnail)
-plt.axis('off')
-plt.show()
-```
+### Bio-Formats
-## Batch Loading with SlideDataset
+Use `backend="bioformats"` for multidimensional microscopy, OME-TIFF, QPTIFF, and
+formats OpenSlide cannot read. Bio-Formats supports a large catalogue (the
+upstream examples describe 160+ formats), including `.ome.tif`, `.ome.tiff`,
+`.qptiff`, `.czi`, `.vsi`, `.zvi`, and many laboratory formats.
-Process multiple slides efficiently using `SlideDataset`:
+This backend requires Java, `python-bioformats`, and `python-javabridge`. It
+starts a JVM and stable source configures a large maximum heap, so isolate and
+resource-limit untrusted images. Java has an approximately 2 GB array limit in
+the backend. A listed extension is not proof that every variant loads.
-```python
-from pathml.core import SlideDataset
-import glob
-
-# Create dataset from multiple slides
-slide_paths = glob.glob("data/*.svs")
-dataset = SlideDataset(
- slide_paths,
- tile_size=256,
- stride=256,
- level=0
-)
+Bio-Formats returns five-dimensional arrays in PathML order:
-# Iterate over all tiles from all slides
-for tile in dataset:
- image = tile.image
- slide_id = tile.slide_id
- # Process tile...
-```
+`(i, j, z, channel, time)` = `(row, column, z, c, t)`.
-**With preprocessing pipeline:**
-```python
-from pathml.preprocessing import Pipeline, StainNormalizationHE
+Even singleton `z` and `time` dimensions are retained until a transform such as
+`CollapseRunsCODEX` or `CollapseRunsVectra` changes the layout.
-# Create pipeline
-pipeline = Pipeline([
- StainNormalizationHE(target='normalize')
-])
+### DICOM
-# Apply to entire dataset
-dataset = SlideDataset(slide_paths)
-dataset.run(pipeline, distributed=True, n_workers=8)
-```
+Use `backend="dicom"` for `.dcm` or `.dicom`. Stable PathML treats DICOM frames as
+tiles. DICOM metadata is especially likely to contain PHI; de-identify with an
+approved DICOM process before PathML, preserve required UIDs consistently, and
+never dump the full dataset to logs.
-## Metadata Access
+### h5path
-Extract slide metadata including acquisition parameters, magnification, and vendor-specific information:
+`.h5` and `.h5path` inputs are inferred as PathML's processed HDF5 format:
```python
-# Access metadata
-metadata = wsi.metadata
-
-# Common metadata fields
-print(metadata.get('openslide.objective-power')) # Magnification
-print(metadata.get('openslide.mpp-x')) # Microns per pixel X
-print(metadata.get('openslide.mpp-y')) # Microns per pixel Y
-print(metadata.get('openslide.vendor')) # Scanner vendor
+from pathml.core import SlideData
-# Slide dimensions
-print(wsi.level_dimensions[0]) # (width, height) at level 0
+processed = SlideData("derived/slide-001.h5path")
```
-## Working with DICOM Slides
+There is no stable `from_hdf5()` constructor. See `data_management.md`.
-PathML supports DICOM WSI through specialized handling:
+## Backend inference versus explicit selection
-```python
-from pathml.core import SlideData, SlideType
-
-# Load DICOM WSI
-dicom_slide = SlideData.from_slide(
- "path/to/slide.dcm",
- backend=SlideType.DICOM
-)
-
-# DICOM-specific metadata
-print(dicom_slide.metadata.get('PatientID'))
-print(dicom_slide.metadata.get('StudyDate'))
-```
-
-## Working with OME-TIFF
-
-OME-TIFF provides an open standard for multi-dimensional imaging:
+If `backend=None`, PathML infers a backend from the suffix. Prefer an explicit
+backend in reproducible work:
```python
-from pathml.core import SlideData
-
-# Load OME-TIFF
-ome_slide = SlideData.from_slide(
- "path/to/slide.ome.tiff",
- backend="bioformats"
-)
+from pathml.core import HESlide
-# Access channel information for multi-channel images
-n_channels = ome_slide.shape[2] # Number of channels
+slide = HESlide("data/slide-001.svs", backend="openslide")
```
-## Performance Considerations
+Reasons to be explicit:
-### Memory Management
+- `.tif` can mean a brightfield pyramid, OME-TIFF, or a plain raster.
+- Bio-Formats is broader but slower and starts Java.
+- Backend metadata and pyramid interpretation differ.
+- A file renamed to a recognized suffix is not thereby valid.
-For large WSI files (often >1GB), use tile-based loading to avoid memory exhaustion:
+## Shape, regions, and tile generation
-```python
-# Efficient: Tile-based processing
-wsi.generate_tiles(level=1, tile_size=256)
-for tile in wsi.tiles:
- process_tile(tile) # Process one tile at a time
-
-# Inefficient: Loading entire slide into memory
-full_image = wsi.read_region((0, 0), level=0, wsi.level_dimensions[0]) # May crash
-```
-
-### Distributed Processing
-
-Use Dask for parallel processing across multiple workers:
+`slide.shape` returns `(height, width)` for the backend's default level.
```python
-from pathml.core import SlideDataset
-from dask.distributed import Client
+height, width = slide.shape
-# Start Dask client
-client = Client(n_workers=8, threads_per_worker=2)
+region = slide.extract_region(
+ location=(2_000, 3_000), # (i, j) = (row, column)
+ size=(512, 768), # (height, width)
+ level=1,
+)
-# Process dataset in parallel
-dataset = SlideDataset(slide_paths)
-dataset.run(pipeline, distributed=True, client=client)
+tiles = slide.generate_tiles(
+ shape=(512, 512),
+ stride=(256, 256),
+ pad=False,
+ level=1,
+)
```
-### Level Selection
+`generate_tiles()` is lazy. Do not materialize all tiles just to count them.
+Use the bounded planner first:
-Balance resolution and performance by selecting appropriate pyramid levels:
-
-- **Level 0:** Use for final analysis requiring maximum detail
-- **Level 1-2:** Use for most preprocessing and model training
-- **Level 3+:** Use for thumbnails, quality control, and rapid exploration
-
-## Common Issues and Solutions
-
-**Issue: Slide fails to load**
-- Verify file format is supported
-- Check file permissions and path
-- Try different backend: `backend="bioformats"` or `backend="openslide"`
-
-**Issue: Out of memory errors**
-- Use tile-based loading instead of full-slide loading
-- Process at lower pyramid level (e.g., level=1 or level=2)
-- Reduce tile_size parameter
-- Enable distributed processing with Dask
+```bash
+python scripts/plan_pipeline.py \
+ --width 100000 --height 80000 \
+ --tile-size 512 --stride 256 \
+ --level-downsample 4
+```
-**Issue: Color inconsistencies across slides**
-- Apply stain normalization preprocessing (see `preprocessing.md`)
-- Check scanner metadata for calibration information
-- Use `StainNormalizationHE` transform in preprocessing pipeline
+`SlideData.run()` uses different parameter names: `tile_size`, `tile_stride`,
+`tile_pad`, and `level`.
-**Issue: Metadata missing or incorrect**
-- Different vendors store metadata in different locations
-- Use `wsi.metadata` to inspect available fields
-- Some formats may have limited metadata support
+## Coordinate convention
-## Best Practices
+PathML's `Tile.coords` is the top-left `(i, j)`:
-1. **Always inspect pyramid structure** before processing: Check `level_dimensions` and `level_downsamples` to understand available resolutions
+- `i`: row / vertical / image `y`
+- `j`: column / horizontal / image `x`
+- origin: top-left pixel `(0, 0)`
+- units: pixels at the **selected pyramid level**
-2. **Use appropriate pyramid levels**: Process at level 1-2 for most tasks; reserve level 0 for final high-resolution analysis
+For OpenSlide, stable PathML multiplies `(i, j)` by that level's downsample and
+swaps the order before calling OpenSlide's level-0 `(x, y)` API. Therefore:
-3. **Tile with overlap** for segmentation tasks: Use stride < tile_size to avoid edge artifacts
+```text
+row_level0 = i_level * downsample_level
+col_level0 = j_level * downsample_level
+y_um = row_level0 * mpp_y
+x_um = col_level0 * mpp_x
+```
-4. **Verify magnification consistency**: Check `openslide.objective-power` metadata when combining slides from different sources
+Use scanner-provided level-0 MPP when reliable. Do not silently derive MPP from
+objective power. Record:
-5. **Handle vendor-specific formats**: Use specialized slide classes (CODEXSlide, VectraSlide) for multiparametric data
+- coordinate convention (`ij` or `xy`)
+- pyramid level and exact downsample
+- whether MPP is measured, metadata-derived, or unavailable
+- tile height/width, stride, and padding
-6. **Implement quality control**: Generate thumbnails and inspect for artifacts before processing
+`QuantifyMIF` later writes `obsm["spatial"]` in `(x, y)` order, so a conversion is
+required when joining it to `Tile.coords`.
-7. **Use distributed processing** for large datasets: Leverage Dask for parallel processing across multiple workers
+## Pyramid levels
-## Example Workflows
+For OpenSlide, level 0 is highest resolution. Later levels are downsampled, but
+the factors are slide-specific; do not assume `4x`, `16x`, or a particular
+magnification sequence.
-### Loading and Inspecting a New Slide
+Backend-level inspection:
```python
-from pathml.core import SlideData
-import matplotlib.pyplot as plt
-
-# Load slide
-wsi = SlideData.from_slide("path/to/slide.svs")
-
-# Inspect properties
-print(f"Dimensions: {wsi.level_dimensions}")
-print(f"Downsamples: {wsi.level_downsamples}")
-print(f"Magnification: {wsi.metadata.get('openslide.objective-power')}")
-
-# Generate thumbnail for QC
-thumbnail = wsi.get_thumbnail(size=(1024, 1024))
-plt.imshow(thumbnail)
-plt.title(f"Slide: {wsi.name}")
-plt.axis('off')
-plt.show()
-```
+level_count = slide.slide.level_count
+level0_shape = slide.slide.get_image_shape(level=0) # (height, width)
-### Processing Multiple Slides
-
-```python
-from pathml.core import SlideDataset
-from pathml.preprocessing import Pipeline, TissueDetectionHE
-import glob
-
-# Find all slides
-slide_paths = glob.glob("data/slides/*.svs")
-
-# Create pipeline
-pipeline = Pipeline([TissueDetectionHE()])
-
-# Process all slides
-dataset = SlideDataset(
- slide_paths,
- tile_size=512,
- stride=512,
- level=1
-)
+# OpenSlide-specific internals, not a backend-neutral PathML contract:
+downsamples = tuple(slide.slide.slide.level_downsamples)
+dimensions_xy = tuple(slide.slide.slide.level_dimensions)
+```
-# Run pipeline with distributed processing
-dataset.run(pipeline, distributed=True, n_workers=8)
+Guard backend-specific access and record it as such. Bio-Formats maps image series
+to levels; those series are not necessarily an optical pyramid.
-# Save processed data
-dataset.to_hdf5("processed_dataset.h5")
-```
+## Tile count and edge behavior
-### Loading CODEX Multiparametric Data
+For one dimension `D`, tile extent `T`, and stride `S`, `pad=False` yields:
-```python
-from pathml.core import CODEXSlide
-from pathml.preprocessing import Pipeline, CollapseRunsCODEX, SegmentMIF
-
-# Load CODEX slide
-codex = CODEXSlide("path/to/codex_dir", stain="IF")
-
-# Create CODEX-specific pipeline
-pipeline = Pipeline([
- CollapseRunsCODEX(z_slice=2), # Select z-slice
- SegmentMIF(
- nuclear_channel='DAPI',
- cytoplasm_channel='CD45',
- model='mesmer'
- )
-])
-
-# Process
-pipeline.run(codex)
+```text
+0 if D < T
+floor((D - T) / S) + 1 otherwise
```
-## Additional Resources
-
-- **PathML Documentation:** https://pathml.readthedocs.io/
-- **OpenSlide:** https://openslide.org/ (underlying library for WSI formats)
-- **Bio-Formats:** https://www.openmicroscopy.org/bio-formats/ (alternative backend)
-- **DICOM Standard:** https://www.dicomstandard.org/
+With `pad=True`, stable PathML follows its backend implementation, which is not
+identical to a generic `ceil(D / S)` rule for every overlapping configuration.
+Use the bundled planner and verify a small synthetic case. Padded pixels are zero,
+which can bias tissue/stain/QC transforms.
+
+Important stable limitation: `SlideData.generate_tiles()` does not slice
+slide-level masks into padded tiles. Do not combine a slide-level mask with
+`pad=True` without an explicit, tested padding policy.
+
+## Technical metadata without PHI leakage
+
+PathML 3.0.5 has no backend-neutral `slide.metadata` mapping. Technical metadata
+is backend-specific:
+
+- OpenSlide properties are under the wrapped OpenSlide object.
+- Bio-Formats stores OME-XML in its backend `metadata`.
+- DICOM contains a full clinical metadata model.
+
+Default to a strict allowlist such as:
+
+- dimensions and level count
+- level downsamples
+- MPP X/Y
+- objective power
+- scanner vendor/model
+- pixel dtype, channels, Z, and time dimensions
+
+Do not emit patient name/ID, accession, dates, institution, free text, UIDs, or
+file paths. Even technical fields can be identifying in a small cohort; minimize
+what is retained.
+
+## Loading/QC checklist
+
+Before large-scale processing:
+
+1. Validate suffix, regular-file status, symlinks, size, and manifest uniqueness.
+2. Confirm backend and native dependencies with a non-sensitive test slide.
+3. Read a thumbnail or a few bounded regions, not the full level-0 image.
+4. Confirm color/channel order, dtype, level count, dimensions, and MPP.
+5. Check orientation, blank areas, focus, folds, pen, bubbles, coverslip edges,
+ clipping, and scanner artifacts.
+6. Confirm tile coordinates by overlaying a few sampled tiles on a thumbnail.
+7. Record failures instead of silently dropping slides.
+
+## Sources, accessed 2026-07-23
+
+- Stable loading guide:
+ https://pathml.readthedocs.io/en/stable/loading_slides.html
+- Stable core API:
+ https://pathml.readthedocs.io/en/stable/api_core_reference.html
+- Stable source (`slide_data.py`):
+ https://github.com/Dana-Farber-AIOS/pathml/blob/v3.0.5/pathml/core/slide_data.py
+- Stable source (`slide_backends.py`):
+ https://github.com/Dana-Farber-AIOS/pathml/blob/v3.0.5/pathml/core/slide_backends.py
+- Stable source (`tile.py`):
+ https://github.com/Dana-Farber-AIOS/pathml/blob/v3.0.5/pathml/core/tile.py
+- OpenSlide formats: https://openslide.org/formats/
+- Bio-Formats supported formats:
+ https://docs.openmicroscopy.org/bio-formats/latest/supported-formats.html
diff --git a/skills/pathml/references/machine_learning.md b/skills/pathml/references/machine_learning.md
index 003cb328..6dc6d3b3 100644
--- a/skills/pathml/references/machine_learning.md
+++ b/skills/pathml/references/machine_learning.md
@@ -1,725 +1,408 @@
-# Machine Learning
+# Machine learning, inference batching, and model trust
-## Overview
+This reference targets **PathML 3.0.5 from PyPI**. GitHub v3.0.7 changes Torch
+dependencies and ONNX export behavior but is not published on PyPI as of
+2026-07-23; do not mix v3.0.7 source instructions into a 3.0.5 environment.
-PathML provides comprehensive machine learning capabilities for computational pathology, including pre-built models for nucleus detection and segmentation, PyTorch-integrated training workflows, public dataset access, and ONNX-based inference deployment. The framework seamlessly bridges image preprocessing with deep learning to enable end-to-end pathology ML pipelines.
+## Stable ML exports
-## Pre-Built Models
-
-PathML includes state-of-the-art pre-trained models for nucleus analysis:
-
-### HoVer-Net
-
-**HoVer-Net** (Horizontal and Vertical Network) performs simultaneous nucleus instance segmentation and classification.
-
-**Architecture:**
-- Encoder-decoder structure with three prediction branches:
- - **Nuclear Pixel (NP)** - Binary segmentation of nuclear regions
- - **Horizontal-Vertical (HV)** - Distance maps to nucleus centroids
- - **Classification (NC)** - Nucleus type classification
-
-**Nucleus types:**
-1. Epithelial
-2. Inflammatory
-3. Connective/Soft tissue
-4. Dead/Necrotic
-5. Background
-
-**Usage:**
```python
-from pathml.ml import HoVerNet
-import torch
-
-# Load pre-trained model
-model = HoVerNet(
- num_types=5, # Number of nucleus types
- mode='fast', # 'fast' or 'original'
- pretrained=True # Load pre-trained weights
+from pathml.ml import (
+ GNNLayer,
+ HACTNet,
+ HoVerNet,
+ TileDataset,
+ loss_hovernet,
+ post_process_batch_hovernet,
)
-
-# Move to GPU if available
-device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
-model = model.to(device)
-
-# Inference on tile
-tile_image = torch.from_numpy(tile.image).permute(2, 0, 1).unsqueeze(0).float()
-tile_image = tile_image.to(device)
-
-with torch.no_grad():
- output = model(tile_image)
-
-# Output contains:
-# - output['np']: Nuclear pixel predictions
-# - output['hv']: Horizontal-vertical maps
-# - output['nc']: Classification predictions
```
-**Post-processing:**
-```python
-from pathml.ml import hovernet_postprocess
-
-# Convert model outputs to instance segmentation
-instance_map, type_map = hovernet_postprocess(
- np_pred=output['np'],
- hv_pred=output['hv'],
- nc_pred=output['nc']
-)
-
-# instance_map: Each nucleus has unique ID
-# type_map: Each nucleus assigned a type (1-5)
-```
-
-### HACTNet
-
-**HACTNet** (Hierarchical Cell-Type Network) performs hierarchical nucleus classification with uncertainty quantification.
-
-**Features:**
-- Hierarchical classification (coarse to fine-grained types)
-- Uncertainty estimation for predictions
-- Improved performance on imbalanced datasets
+The documented dataset import is usually:
```python
-from pathml.ml import HACTNet
-
-# Load model
-model = HACTNet(
- num_classes_coarse=3,
- num_classes_fine=8,
- pretrained=True
-)
-
-# Inference
-output = model(tile_image)
-coarse_pred = output['coarse'] # Broad categories
-fine_pred = output['fine'] # Specific cell types
-uncertainty = output['uncertainty'] # Prediction confidence
+from pathml.datasets import TileDataset
```
-## Training Workflows
+PathML provides model architectures and helpers. Stable constructors do not
+accept `pretrained=True`, do not expose `mode="fast"`, and do not download
+official HoVer-Net/HACTNet checkpoints automatically.
-### Dataset Preparation
+## HoVer-Net
-PathML provides PyTorch-compatible dataset classes:
+Stable constructor:
-**TileDataset:**
```python
-from pathml.ml import TileDataset
-from pathml.core import SlideDataset
-
-# Create dataset from processed slides
-tile_dataset = TileDataset(
- slide_dataset,
- tile_size=256,
- transform=None # Optional augmentation transforms
-)
+from pathml.ml import HoVerNet
-# Access tiles
-image, label = tile_dataset[0]
+model = HoVerNet(n_classes=6)
```
-**DataModule Integration:**
-```python
-from pathml.ml import PathMLDataModule
-
-# Create train/val/test splits
-data_module = PathMLDataModule(
- train_dataset=train_tile_dataset,
- val_dataset=val_tile_dataset,
- test_dataset=test_tile_dataset,
- batch_size=32,
- num_workers=4
-)
-
-# Use with PyTorch Lightning
-trainer = pl.Trainer(max_epochs=100)
-trainer.fit(model, data_module)
-```
+- `n_classes=None` creates nucleus-pixel (NP) and horizontal/vertical (HV)
+ branches for segmentation.
+- An integer adds a nucleus-classification (NC) branch.
+- Forward output is a list `[np_logits, hv]` or
+ `[np_logits, hv, nc_logits]`.
+- The architecture initializes weights; it is not a pretrained model loader.
-### Training HoVer-Net
+Use the class count and label order from the exact dataset schema. PanNuke's
+stable PathML representation can use five nucleus categories plus background;
+do not silently map labels from another implementation.
-Complete workflow for training HoVer-Net on custom data:
+Training helpers:
```python
-import torch
-import torch.nn as nn
-from torch.utils.data import DataLoader
-from pathml.ml import HoVerNet
-from pathml.ml.datasets import PanNukeDataModule
+from pathml.ml import loss_hovernet, post_process_batch_hovernet
-# 1. Prepare data
-data_module = PanNukeDataModule(
- data_dir='path/to/pannuke',
- batch_size=8,
- num_workers=4,
- tissue_types=['Breast', 'Colon'] # Specific tissue types
+outputs = model(images)
+loss = loss_hovernet(
+ outputs=outputs,
+ ground_truth=[nucleus_mask, horizontal_vertical_map],
+ n_classes=6,
)
-# 2. Initialize model
-model = HoVerNet(
- num_types=5,
- mode='fast',
- pretrained=False # Train from scratch or use pretrained=True for fine-tuning
+instances, classified_instances = post_process_batch_hovernet(
+ outputs=outputs,
+ n_classes=6,
+ small_obj_size_thresh=10,
+ kernel_size=21,
+ h=0.5,
+ k=0.5,
)
+```
-# 3. Define loss function
-class HoVerNetLoss(nn.Module):
- def __init__(self):
- super().__init__()
- self.mse_loss = nn.MSELoss()
- self.bce_loss = nn.BCEWithLogitsLoss()
- self.ce_loss = nn.CrossEntropyLoss()
+Verify tensor shapes from the stable API:
- def forward(self, output, target):
- # Nuclear pixel branch loss
- np_loss = self.bce_loss(output['np'], target['np'])
+```text
+NP logits: (batch, 2, height, width)
+HV maps: (batch, 2, height, width)
+NC logits: (batch, n_classes, height, width)
+```
- # Horizontal-vertical branch loss
- hv_loss = self.mse_loss(output['hv'], target['hv'])
+`post_process_batch_hovernet` returns instance maps with 0 as background and
+positive object IDs. The classification output uses one channel per class with
+instance IDs in the selected class channel.
- # Classification branch loss
- nc_loss = self.ce_loss(output['nc'], target['nc'])
+## Evaluation mode is not dynamic evaluation
- # Combined loss
- total_loss = np_loss + hv_loss + 2.0 * nc_loss
- return total_loss, {'np': np_loss, 'hv': hv_loss, 'nc': nc_loss}
+PyTorch's `model.eval()` method switches module behavior such as dropout and
+batch normalization to evaluation mode. It is **not** Python's dangerous built-in
+expression evaluator and does not execute a string.
-criterion = HoVerNetLoss()
+To avoid ambiguity in executable examples, the equivalent explicit form is:
-# 4. Configure optimizer
-optimizer = torch.optim.Adam(
- model.parameters(),
- lr=1e-4,
- weight_decay=1e-5
-)
-
-scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(
- optimizer,
- mode='min',
- factor=0.5,
- patience=10
-)
+```python
+import torch
-# 5. Training loop
-device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
-model = model.to(device)
-
-num_epochs = 100
-for epoch in range(num_epochs):
- model.train()
- train_loss = 0.0
-
- for batch in data_module.train_dataloader():
- images = batch['image'].to(device)
- targets = {
- 'np': batch['np_map'].to(device),
- 'hv': batch['hv_map'].to(device),
- 'nc': batch['type_map'].to(device)
- }
-
- optimizer.zero_grad()
- outputs = model(images)
- loss, loss_dict = criterion(outputs, targets)
-
- loss.backward()
- optimizer.step()
-
- train_loss += loss.item()
-
- # Validation
- model.eval()
- val_loss = 0.0
- with torch.no_grad():
- for batch in data_module.val_dataloader():
- images = batch['image'].to(device)
- targets = {
- 'np': batch['np_map'].to(device),
- 'hv': batch['hv_map'].to(device),
- 'nc': batch['type_map'].to(device)
- }
- outputs = model(images)
- loss, _ = criterion(outputs, targets)
- val_loss += loss.item()
-
- scheduler.step(val_loss)
-
- print(f"Epoch {epoch+1}/{num_epochs}")
- print(f" Train Loss: {train_loss/len(data_module.train_dataloader()):.4f}")
- print(f" Val Loss: {val_loss/len(data_module.val_dataloader()):.4f}")
-
- # Save checkpoint
- if (epoch + 1) % 10 == 0:
- torch.save({
- 'epoch': epoch,
- 'model_state_dict': model.state_dict(),
- 'optimizer_state_dict': optimizer.state_dict(),
- 'loss': val_loss,
- }, f'hovernet_checkpoint_epoch_{epoch+1}.pth')
+model.train(False)
+with torch.inference_mode():
+ outputs = model(images)
```
-### PyTorch Lightning Integration
+Never use Python dynamic evaluation or execution to load a model, transform,
+configuration, metric, or class name. Use an allowlist and normal constructors.
-PathML models integrate with PyTorch Lightning for streamlined training:
+## PanNuke training data
```python
-import pytorch_lightning as pl
-from pathml.ml import HoVerNet
-from pathml.ml.datasets import PanNukeDataModule
-
-class HoVerNetModule(pl.LightningModule):
- def __init__(self, num_types=5, lr=1e-4):
- super().__init__()
- self.model = HoVerNet(num_types=num_types, pretrained=True)
- self.lr = lr
- self.criterion = HoVerNetLoss()
-
- def forward(self, x):
- return self.model(x)
-
- def training_step(self, batch, batch_idx):
- images = batch['image']
- targets = {
- 'np': batch['np_map'],
- 'hv': batch['hv_map'],
- 'nc': batch['type_map']
- }
- outputs = self(images)
- loss, loss_dict = self.criterion(outputs, targets)
-
- # Log metrics
- self.log('train_loss', loss, prog_bar=True)
- for key, val in loss_dict.items():
- self.log(f'train_{key}_loss', val)
-
- return loss
-
- def validation_step(self, batch, batch_idx):
- images = batch['image']
- targets = {
- 'np': batch['np_map'],
- 'hv': batch['hv_map'],
- 'nc': batch['type_map']
- }
- outputs = self(images)
- loss, loss_dict = self.criterion(outputs, targets)
-
- self.log('val_loss', loss, prog_bar=True)
- for key, val in loss_dict.items():
- self.log(f'val_{key}_loss', val)
-
- return loss
-
- def configure_optimizers(self):
- optimizer = torch.optim.Adam(self.parameters(), lr=self.lr)
- scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(
- optimizer, mode='min', factor=0.5, patience=10
- )
- return {
- 'optimizer': optimizer,
- 'lr_scheduler': {
- 'scheduler': scheduler,
- 'monitor': 'val_loss'
- }
- }
-
-# Train with PyTorch Lightning
-data_module = PanNukeDataModule(data_dir='path/to/pannuke', batch_size=8)
-model = HoVerNetModule(num_types=5, lr=1e-4)
-
-trainer = pl.Trainer(
- max_epochs=100,
- accelerator='gpu',
- devices=1,
- callbacks=[
- pl.callbacks.ModelCheckpoint(monitor='val_loss', mode='min'),
- pl.callbacks.EarlyStopping(monitor='val_loss', patience=20)
- ]
+from pathml.datasets import PanNukeDataModule
+
+data = PanNukeDataModule(
+ data_dir="approved_data/pannuke",
+ download=False,
+ shuffle=True,
+ nucleus_type_labels=True,
+ split=1,
+ batch_size=8,
+ hovernet_preprocess=True,
)
-trainer.fit(model, data_module)
+train_loader = data.train_dataloader
+validation_loader = data.valid_dataloader
+test_loader = data.test_dataloader
```
-## Public Datasets
+The dataloaders are properties, not methods. `hovernet_preprocess=True` adds the
+HV target. Set `download=True` only after explicit consent to the Warwick
+download, storage estimate, license review, and endpoint disclosure.
-PathML provides convenient access to public pathology datasets:
+Do not assume the published folds satisfy every patient/source-slide grouping
+claim. Audit the dataset's provenance and duplicates for the intended study.
-### PanNuke Dataset
+## HACTNet
-**PanNuke** contains 7,901 histology image patches from 19 tissue types with nucleus annotations for 5 cell types.
+Stable signature:
```python
-from pathml.ml.datasets import PanNukeDataModule
-
-# Load PanNuke dataset
-pannuke = PanNukeDataModule(
- data_dir='path/to/pannuke',
- batch_size=16,
- num_workers=4,
- tissue_types=None, # Use all tissue types, or specify list
- fold='all' # 'fold1', 'fold2', 'fold3', or 'all'
-)
+from pathml.ml import HACTNet
-# Access dataloaders
-train_loader = pannuke.train_dataloader()
-val_loader = pannuke.val_dataloader()
-test_loader = pannuke.test_dataloader()
-
-# Batch structure
-for batch in train_loader:
- images = batch['image'] # Shape: (B, 3, 256, 256)
- inst_map = batch['inst_map'] # Instance segmentation map
- type_map = batch['type_map'] # Cell type map
- np_map = batch['np_map'] # Nuclear pixel map
- hv_map = batch['hv_map'] # Horizontal-vertical distance maps
- tissue_type = batch['tissue_type'] # Tissue category
+model = HACTNet(
+ cell_params=cell_gnn_parameters,
+ tissue_params=tissue_gnn_parameters,
+ classifier_params=classifier_parameters,
+)
```
-**Tissue types available:**
-Breast, Colon, Prostate, Lung, Kidney, Stomach, Bladder, Esophagus, Cervix, Liver, Thyroid, Head & Neck, Testis, Adrenal, Pancreas, Bile Duct, Ovary, Skin, Uterus
+HACTNet consumes a batched `HACTPairData` object with cell and tissue features,
+their edge indices, a cell-to-tissue assignment, and a target. Parameter
+dictionaries configure PathML `GNNLayer` and its classifier; use the v3.0.5
+tutorial/API rather than copying a configuration from another PyG release.
-### TCGA Datasets
+Before training, validate:
-Access The Cancer Genome Atlas datasets:
+- feature dimensions match each dictionary;
+- assignment indices are valid tissue-node indices;
+- graph batches carry the expected `x_cell_batch`/`x_tissue_batch`;
+- targets are slide/patient-level as intended;
+- all graphs from a patient remain in one split.
-```python
-from pathml.ml.datasets import TCGADataModule
-
-# Load TCGA dataset
-tcga = TCGADataModule(
- data_dir='path/to/tcga',
- cancer_type='BRCA', # Breast cancer
- batch_size=32,
- tile_size=224
-)
-```
-
-### Custom Dataset Integration
+`pathml.datasets.EntityDataset` loads `.pt` graph objects with unrestricted
+PyTorch deserialization. Use it only for trusted project-generated artifacts.
-Create custom datasets for PathML workflows:
-
-```python
-from torch.utils.data import Dataset
-import numpy as np
-from pathlib import Path
-
-class CustomPathologyDataset(Dataset):
- def __init__(self, data_dir, transform=None):
- self.data_dir = Path(data_dir)
- self.image_paths = list(self.data_dir.glob('images/*.png'))
- self.transform = transform
-
- def __len__(self):
- return len(self.image_paths)
-
- def __getitem__(self, idx):
- # Load image
- image_path = self.image_paths[idx]
- image = np.array(Image.open(image_path))
-
- # Load corresponding annotation
- annot_path = self.data_dir / 'annotations' / f'{image_path.stem}.npy'
- annotation = np.load(annot_path)
-
- # Apply transforms
- if self.transform:
- image = self.transform(image)
-
- return {
- 'image': torch.from_numpy(image).permute(2, 0, 1).float(),
- 'annotation': torch.from_numpy(annotation).long(),
- 'path': str(image_path)
- }
-
-# Use in PathML workflow
-dataset = CustomPathologyDataset('path/to/data')
-dataloader = DataLoader(dataset, batch_size=16, shuffle=True, num_workers=4)
-```
+## Checkpoint trust
-## Data Augmentation
+Never load an untrusted `.pt`, `.pth`, `.ckpt`, pickle, joblib, or saved pipeline.
+Such formats can execute code during deserialization.
-Apply augmentations to improve model generalization:
+For a trusted checkpoint:
-```python
-import albumentations as A
-from albumentations.pytorch import ToTensorV2
-
-# Define augmentation pipeline
-train_transform = A.Compose([
- A.RandomRotate90(p=0.5),
- A.Flip(p=0.5),
- A.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2, hue=0.1, p=0.5),
- A.GaussianBlur(blur_limit=(3, 7), p=0.3),
- A.ElasticTransform(alpha=1, sigma=50, alpha_affine=50, p=0.3),
- A.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
- ToTensorV2()
-])
-
-val_transform = A.Compose([
- A.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
- ToTensorV2()
-])
-
-# Apply to dataset
-train_dataset = TileDataset(slide_dataset, transform=train_transform)
-val_dataset = TileDataset(val_slide_dataset, transform=val_transform)
-```
+1. obtain it from the model owner or an approved registry;
+2. verify exact SHA-256/signature before opening;
+3. record architecture source revision, dependency lock, license, training data,
+ preprocessing, class order, and expected tensor schema;
+4. inspect in a disposable network-disabled environment;
+5. load only the minimal weights-only representation when the producing PyTorch
+ version supports it;
+6. enforce file, tensor, RAM, time, and device limits; and
+7. validate on synthetic tensors before any pathology data.
-## Model Evaluation
+The bundled planner refuses checkpoint/model extensions and never imports Torch,
+ONNX, PathML, or a model class.
-### Metrics
+## Local ONNX inference
-Evaluate model performance with pathology-specific metrics:
+Stable exports:
```python
-from pathml.ml.metrics import (
- dice_coefficient,
- aggregated_jaccard_index,
- panoptic_quality
+from pathml.inference import (
+ HaloAIInference,
+ Inference,
+ check_onnx_clean,
+ convert_pytorch_onnx,
+ remove_initializer_from_input,
)
-
-# Dice coefficient for segmentation
-dice = dice_coefficient(pred_mask, true_mask)
-
-# Aggregated Jaccard Index (AJI) for instance segmentation
-aji = aggregated_jaccard_index(pred_inst, true_inst)
-
-# Panoptic Quality (PQ) for joint segmentation and classification
-pq, sq, rq = panoptic_quality(pred_inst, true_inst, pred_types, true_types)
-
-print(f"Dice: {dice:.4f}")
-print(f"AJI: {aji:.4f}")
-print(f"PQ: {pq:.4f}, SQ: {sq:.4f}, RQ: {rq:.4f}")
```
-### Evaluation Loop
+For a reviewed local model:
```python
-from pathml.ml.metrics import evaluate_hovernet
-
-# Comprehensive HoVer-Net evaluation
-model.eval()
-all_preds = []
-all_targets = []
-
-with torch.no_grad():
- for batch in test_loader:
- images = batch['image'].to(device)
- outputs = model(images)
-
- # Post-process predictions
- for i in range(len(images)):
- inst_pred, type_pred = hovernet_postprocess(
- outputs['np'][i],
- outputs['hv'][i],
- outputs['nc'][i]
- )
- all_preds.append({'inst': inst_pred, 'type': type_pred})
- all_targets.append({
- 'inst': batch['inst_map'][i],
- 'type': batch['type_map'][i]
- })
-
-# Compute metrics
-results = evaluate_hovernet(all_preds, all_targets)
-
-print(f"Detection F1: {results['detection_f1']:.4f}")
-print(f"Classification Accuracy: {results['classification_acc']:.4f}")
-print(f"Panoptic Quality: {results['pq']:.4f}")
-```
-
-## ONNX Inference
-
-Deploy models using ONNX for production inference:
-
-### Export to ONNX
+from pathml.core import SlideData
+from pathml.inference import Inference
+from pathml.preprocessing import Pipeline
-```python
-import torch
-from pathml.ml import HoVerNet
+inference = Inference(
+ model_path="models/reviewed_model.onnx",
+ input_name="data",
+ num_classes=4,
+ model_type="segmentation",
+ local=True,
+)
+pipeline = Pipeline([inference])
-# Load trained model
-model = HoVerNet(num_types=5, pretrained=True)
-model.eval()
-
-# Create dummy input
-dummy_input = torch.randn(1, 3, 256, 256)
-
-# Export to ONNX
-torch.onnx.export(
- model,
- dummy_input,
- 'hovernet_model.onnx',
- export_params=True,
- opset_version=11,
- input_names=['input'],
- output_names=['np_output', 'hv_output', 'nc_output'],
- dynamic_axes={
- 'input': {0: 'batch_size'},
- 'np_output': {0: 'batch_size'},
- 'hv_output': {0: 'batch_size'},
- 'nc_output': {0: 'batch_size'}
- }
+slide = SlideData(
+ "data/slide-001.ome.tiff",
+ backend="bioformats",
+ stain="Fluor",
+)
+slide.run(
+ pipeline,
+ distributed=False,
+ tile_size=256,
+ tile_stride=256,
+ level=0,
)
```
-### ONNX Runtime Inference
+Stable `Inference.apply()` replaces `tile.image` with model output. If the raw
+image must be preserved, write a custom reviewed transform that stores
+predictions separately or use a separate inference loop.
-```python
-import onnxruntime as ort
-import numpy as np
+`Inference`:
-# Load ONNX model
-session = ort.InferenceSession('hovernet_model.onnx')
+- checks a local ONNX model for initializers also exposed as inputs;
+- verifies the model with ONNX;
+- creates an ONNX Runtime session;
+- expects input name/shape to match;
+- reshapes 3-D HWC to a batch of NCHW;
+- concatenates multiple same-spatial-size outputs along channels.
-# Prepare input
-input_name = session.get_inputs()[0].name
-tile_image = preprocess_tile(tile) # Normalize, transpose to (1, 3, H, W)
+`remove_initializer_from_input(source, destination)` rewrites the model. Do not
+overwrite the original; verify the destination hash and outputs. ONNX parsing is
+not a guarantee of safety—malformed models can exploit parser/runtime bugs or
+request excessive resources.
-# Run inference
-outputs = session.run(None, {input_name: tile_image})
-np_output, hv_output, nc_output = outputs
+## Source-only ONNX difference after 3.0.5
-# Post-process
-inst_map, type_map = hovernet_postprocess(np_output, hv_output, nc_output)
-```
+GitHub v3.0.7 release notes report:
-### Batch Inference Pipeline
+- Torch 2.12.0;
+- TorchVision 0.27.0;
+- torch-geometric 2.8.0;
+- `onnxscript==0.7.1`; and
+- adjustments to the ONNX export method.
-```python
-from pathml.core import SlideData
-from pathml.preprocessing import Pipeline
-import onnxruntime as ort
+PyPI `pathml==3.0.5` instead declares Torch 2.8.0, torch-geometric 2.3.1,
+ONNX 1.17.0, and ONNX Runtime `>=1.17,<1.18`. An ONNX file exported with newer
+source may use operators unsupported by the stable runtime. Validate opset and
+runtime compatibility explicitly.
-def run_onnx_inference_pipeline(slide_path, onnx_model_path):
- # Load slide
- wsi = SlideData.from_slide(slide_path)
- wsi.generate_tiles(level=1, tile_size=256, stride=256)
+## Remote model classes
- # Load ONNX model
- session = ort.InferenceSession(onnx_model_path)
- input_name = session.get_inputs()[0].name
+Do not instantiate without explicit network consent:
- # Inference on all tiles
- results = []
- for tile in wsi.tiles:
- # Preprocess
- tile_array = preprocess_tile(tile.image)
+- `RemoteMesmer` / `SegmentMIFRemote` downloads
+ `https://huggingface.co/pathml/test/resolve/main/mesmer.onnx`.
+- `RemoteTestHoverNet` downloads
+ `https://huggingface.co/pathml/test/resolve/main/hovernet_fast_tiatoolbox_fixed.onnx`.
- # Inference
- outputs = session.run(None, {input_name: tile_array})
+Stable code downloads model bytes and performs inference locally; it does not
+upload slide pixels. The GET still discloses connection metadata and lacks a
+built-in checksum/size/timeout policy. Prefer approved local artifacts.
- # Post-process
- inst_map, type_map = hovernet_postprocess(*outputs)
+See `multiparametric.md` for the full consent template.
- results.append({
- 'coords': tile.coords,
- 'instance_map': inst_map,
- 'type_map': type_map
- })
+## Bounded inference planning
- return results
+Plan without opening a model:
-# Run on slide
-results = run_onnx_inference_pipeline('slide.svs', 'hovernet_model.onnx')
+```bash
+python scripts/plan_inference.py \
+ --tile-count 4000 \
+ --batch-size 16 \
+ --channels 3 \
+ --height 256 \
+ --width 256 \
+ --dtype float32 \
+ --activation-multiplier 8 \
+ --max-memory-mib 4096
```
-## Transfer Learning
-
-Fine-tune pre-trained models on custom datasets:
-
-```python
-from pathml.ml import HoVerNet
+Or supply a bounded strict JSON model card containing only metadata:
+
+```json
+{
+ "schema_version": "1.0",
+ "model_id": "reviewed-hovernet",
+ "artifact_sha256": "hex-digest",
+ "input_shape": [3, 256, 256],
+ "dtype": "float32",
+ "output_elements_per_tile": 589824,
+ "activation_multiplier": 8.0
+}
+```
-# Load pre-trained model
-model = HoVerNet(num_types=5, pretrained=True)
+```bash
+python scripts/plan_inference.py \
+ --model-card models/reviewed_model_card.json \
+ --root . \
+ --tile-count 4000 \
+ --batch-size 16
+```
-# Freeze encoder layers for initial training
-for name, param in model.named_parameters():
- if 'encoder' in name:
- param.requires_grad = False
+The estimate is a planning bound, not a GPU profiler. Include model parameters,
+runtime workspace, framework caches, graph memory, postprocessing, and stitching
+headroom. Pilot at a smaller batch and monitor actual peak memory.
-# Fine-tune only decoder and classification heads
-optimizer = torch.optim.Adam(
- filter(lambda p: p.requires_grad, model.parameters()),
- lr=1e-4
-)
+## Batch execution
-# Train for a few epochs
-train_for_n_epochs(model, train_loader, optimizer, num_epochs=10)
+For local PyTorch architecture code:
-# Unfreeze all layers for full fine-tuning
-for param in model.parameters():
- param.requires_grad = True
+```python
+import torch
-# Continue training with lower learning rate
-optimizer = torch.optim.Adam(model.parameters(), lr=1e-5)
-train_for_n_epochs(model, train_loader, optimizer, num_epochs=50)
+model.train(False)
+for tile_images, tile_masks, tile_labels, slide_labels in loader:
+ inputs = tile_images.to(device, non_blocking=True)
+ with torch.inference_mode():
+ outputs = model(inputs)
+ # Move bounded outputs to CPU and attach the original slide/tile coordinates.
```
-## Best Practices
-
-1. **Use pre-trained models when available:**
- - Start with pretrained=True for better initialization
- - Fine-tune on domain-specific data
-
-2. **Apply appropriate data augmentation:**
- - Rotate, flip for orientation invariance
- - Color jitter to handle staining variations
- - Elastic deformation for biological variability
-
-3. **Monitor multiple metrics:**
- - Track detection, segmentation, and classification separately
- - Use domain-specific metrics (AJI, PQ) beyond standard accuracy
-
-4. **Handle class imbalance:**
- - Weighted loss functions for rare cell types
- - Oversampling minority classes
- - Focal loss for hard examples
-
-5. **Validate on diverse tissue types:**
- - Ensure generalization across different tissues
- - Test on held-out anatomical sites
-
-6. **Optimize for inference:**
- - Export to ONNX for faster deployment
- - Batch tiles for efficient GPU utilization
- - Use mixed precision (FP16) when possible
-
-7. **Save checkpoints regularly:**
- - Keep best model based on validation metrics
- - Save optimizer state for training resumption
-
-## Common Issues and Solutions
-
-**Issue: Poor segmentation at nucleus boundaries**
-- Use HV maps (horizontal-vertical) to separate touching nuclei
-- Increase weight of HV loss term
-- Apply morphological post-processing
-
-**Issue: Misclassification of similar cell types**
-- Increase classification loss weight
-- Add hierarchical classification (HACTNet)
-- Augment training data for confused classes
-
-**Issue: Training unstable or not converging**
-- Reduce learning rate
-- Use gradient clipping: `torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)`
-- Check for data preprocessing issues
-
-**Issue: Out of memory during training**
-- Reduce batch size
-- Use gradient accumulation
-- Enable mixed precision training: `torch.cuda.amp`
-
-**Issue: Model overfits to training data**
-- Increase data augmentation
-- Add dropout layers
-- Reduce model capacity
-- Use early stopping based on validation loss
-
-## Additional Resources
-
-- **PathML ML API:** https://pathml.readthedocs.io/en/latest/api_ml_reference.html
-- **HoVer-Net Paper:** Graham et al., "HoVer-Net: Simultaneous Segmentation and Classification of Nuclei in Multi-Tissue Histology Images," Medical Image Analysis, 2019
-- **PanNuke Dataset:** https://warwick.ac.uk/fac/cross_fac/tia/data/pannuke
-- **PyTorch Lightning:** https://www.pytorchlightning.ai/
-- **ONNX Runtime:** https://onnxruntime.ai/
+PathML's label dictionaries may need a custom `collate_fn`; never lose coordinate
+keys. Avoid collecting all prediction maps in RAM. Stream bounded batches to a
+structured local output and flush per slide.
+
+For ONNX, stable `Inference` operates one PathML tile at a time because its
+reshape method adds a batch dimension. For true batch inference, build a separate
+reviewed ONNX Runtime loop around `TileDataset`, validate the model's dynamic or
+fixed batch axis, and retain coordinates.
+
+## Overlap and stitching
+
+For dense outputs:
+
+- use context overlap to reduce edge artifacts;
+- emit only a central crop, or blend with a documented weight window;
+- map every output pixel to selected-level and level-0 coordinates;
+- account for padding;
+- avoid counting an object more than once;
+- record output stride/resolution and interpolation;
+- test a synthetic object crossing tile boundaries.
+
+PathML includes tile-stitching utilities, but verify their stable signature and
+output semantics for the exact task rather than assuming `average`, `max`, or
+weighted options from unrelated examples.
+
+## Evaluation
+
+PathML 3.0.5 does not export the broad
+`pathml.ml.metrics.dice_coefficient`/`panoptic_quality` API shown in older
+references. Implement or import metrics from a pinned, validated package and
+record the exact definition.
+
+For segmentation/classification:
+
+- Dice/IoU for semantic masks;
+- detection precision/recall/F1 with a fixed matching rule;
+- AJI/PQ for instances with explicit implementation/version;
+- per-class confusion, calibration, and uncertainty;
+- slide/patient-level bootstrap or hierarchical confidence intervals;
+- external site/scanner/stain evaluation.
+
+Choose thresholds on training/validation only. Keep the test set sealed until the
+analysis plan is frozen. Do not treat tiles/nuclei as independent patients.
+
+## Model provenance card
+
+Record:
+
+- model ID, architecture, code revision, and framework versions;
+- artifact SHA-256/signature, size, license, and source URL/owner;
+- training/validation cohorts and patient-level split;
+- stain, scanner, MPP, level, tile/context size, normalization, channel order;
+- class names/order, output schema, postprocessing, and thresholds;
+- expected dtype/range and batch support;
+- hardware/runtime, deterministic settings, seeds, and known limitations;
+- subgroup/site performance and intended research use;
+- statement that the model is not for diagnostic use.
+
+Never include direct patient identifiers or sensitive example tiles in a model
+card.
+
+## Sources, accessed 2026-07-23
+
+- Stable ML API:
+ https://pathml.readthedocs.io/en/stable/api_ml_reference.html
+- Stable inference API:
+ https://pathml.readthedocs.io/en/stable/api_inference_reference.html
+- Stable HoVer-Net source:
+ https://github.com/Dana-Farber-AIOS/pathml/blob/v3.0.5/pathml/ml/models/hovernet.py
+- Stable HACTNet source:
+ https://github.com/Dana-Farber-AIOS/pathml/blob/v3.0.5/pathml/ml/models/hactnet.py
+- Stable inference source:
+ https://github.com/Dana-Farber-AIOS/pathml/blob/v3.0.5/pathml/inference/inference.py
+- GitHub v3.0.7 release:
+ https://github.com/Dana-Farber-AIOS/pathml/releases/tag/v3.0.7
+- Graham et al. (2019), HoVer-Net:
+ https://doi.org/10.1016/j.media.2019.101563
+- Pati et al. (2022), HACT:
+ https://doi.org/10.1016/j.media.2021.102264
diff --git a/skills/pathml/references/multiparametric.md b/skills/pathml/references/multiparametric.md
index 842b9055..3eacb7dd 100644
--- a/skills/pathml/references/multiparametric.md
+++ b/skills/pathml/references/multiparametric.md
@@ -1,686 +1,352 @@
-# Multiparametric Imaging
+# Multiparametric imaging, spatial data, and Mesmer integration
-## Overview
+This reference targets **PathML 3.0.5 stable**. It distinguishes generic loading
+support from a dedicated analysis implementation and corrects older examples that
+invented MERFISH decoders, spectral unmixing options, named-channel arguments, or
+a DeepCell cloud prediction endpoint.
-PathML provides specialized support for multiparametric imaging technologies that simultaneously measure multiple markers at single-cell resolution. These techniques include CODEX, Vectra multiplex immunofluorescence, MERFISH, and other spatial proteomics and transcriptomics platforms. PathML handles the unique data structures, processing requirements, and quantification workflows specific to each technology.
-
-## Supported Technologies
-
-### CODEX (CO-Detection by indEXing)
-- Cyclic immunofluorescence imaging
-- 40+ protein markers simultaneously
-- Single-cell spatial proteomics
-- Multi-cycle acquisition with antibody barcoding
-
-### Vectra Polaris
-- Multispectral multiplex immunofluorescence
-- 6-8 markers per slide
-- Spectral unmixing
-- Whole-slide scanning
-
-### MERFISH (Multiplexed Error-Robust FISH)
-- Spatial transcriptomics
-- 100s-1000s of genes
-- Single-molecule resolution
-- Error-correcting barcodes
-
-### Other Platforms
-- CycIF (Cyclic Immunofluorescence)
-- IMC (Imaging Mass Cytometry)
-- MIBI (Multiplexed Ion Beam Imaging)
-
-## CODEX Workflows
-
-### Loading CODEX Data
-
-CODEX data is typically organized in multi-channel image stacks from multiple acquisition cycles:
+## Stable slide types and array order
```python
-from pathml.core import CODEXSlide
+from pathml.core import CODEXSlide, MultiparametricSlide, VectraSlide
-# Load CODEX dataset
-codex_slide = CODEXSlide(
- path='path/to/codex_directory',
- stain='IF', # Immunofluorescence
- backend='bioformats'
+codex = CODEXSlide(
+ "data/codex_region.tif",
+ name="slide-001",
+ backend="bioformats",
)
-
-# Inspect channels and cycles
-print(f"Number of channels: {codex_slide.num_channels}")
-print(f"Channel names: {codex_slide.channel_names}")
-print(f"Number of cycles: {codex_slide.num_cycles}")
-print(f"Image shape: {codex_slide.shape}")
-```
-
-**CODEX directory structure:**
-```
-codex_directory/
-├── cyc001_reg001/
-│ ├── 1_00001_Z001_CH1.tif
-│ ├── 1_00001_Z001_CH2.tif
-│ └── ...
-├── cyc002_reg001/
-│ └── ...
-└── channelnames.txt
-```
-
-### CODEX Preprocessing Pipeline
-
-Complete pipeline for CODEX data processing:
-
-```python
-from pathml.preprocessing import Pipeline, CollapseRunsCODEX, SegmentMIF, QuantifyMIF
-
-# Create CODEX-specific pipeline
-codex_pipeline = Pipeline([
- # 1. Collapse multi-cycle data
- CollapseRunsCODEX(
- z_slice=2, # Select focal plane from z-stack
- run_order=None, # Automatic cycle ordering, or specify [0, 1, 2, ...]
- method='max' # 'max', 'mean', or 'median' across cycles
- ),
-
- # 2. Cell segmentation using Mesmer
- SegmentMIF(
- nuclear_channel='DAPI',
- cytoplasm_channel='CD45', # Or other membrane/cytoplasm marker
- model='mesmer',
- image_resolution=0.377, # Microns per pixel
- compartment='whole-cell' # 'nuclear', 'cytoplasm', or 'whole-cell'
- ),
-
- # 3. Quantify marker expression per cell
- QuantifyMIF(
- segmentation_mask_name='cell_segmentation',
- markers=[
- 'DAPI', 'CD3', 'CD4', 'CD8', 'CD20', 'CD45',
- 'CD68', 'PD1', 'PDL1', 'Ki67', 'panCK'
- ],
- output_format='anndata'
- )
-])
-
-# Run pipeline
-codex_pipeline.run(codex_slide)
-
-# Access results
-segmentation_mask = codex_slide.masks['cell_segmentation']
-cell_data = codex_slide.cell_data # AnnData object
-```
-
-### CollapseRunsCODEX
-
-Consolidates multi-cycle CODEX acquisitions into a single multi-channel image:
-
-```python
-from pathml.preprocessing import CollapseRunsCODEX
-
-transform = CollapseRunsCODEX(
- z_slice=2, # Select which z-plane (0-indexed)
- run_order=[0, 1, 2, 3], # Order of acquisition cycles
- method='max', # Aggregation method across cycles
- background_subtract=True, # Subtract background fluorescence
- channel_mapping=None # Optional: remap channel order
+vectra = VectraSlide(
+ "data/vectra_component_data.tif",
+ name="slide-002",
+)
+generic = MultiparametricSlide(
+ "data/multiplex.ome.tiff",
+ name="slide-003",
)
```
-**Parameters:**
-- `z_slice`: Which focal plane to extract from z-stacks (typically middle slice)
-- `run_order`: Order of cycles; None for automatic detection
-- `method`: How to combine channels from multiple cycles ('max', 'mean', 'median')
-- `background_subtract`: Whether to subtract background fluorescence
-
-**Output:** Single multi-channel image with all markers (H, W, C)
-
-### Cell Segmentation with Mesmer
-
-DeepCell Mesmer provides accurate cell segmentation for multiparametric imaging:
+Bio-Formats returns PathML arrays as:
-```python
-from pathml.preprocessing import SegmentMIF
-
-transform = SegmentMIF(
- nuclear_channel='DAPI', # Nuclear marker (required)
- cytoplasm_channel='CD45', # Cytoplasm/membrane marker (required)
- model='mesmer', # DeepCell Mesmer model
- image_resolution=0.377, # Microns per pixel (important for accuracy)
- compartment='whole-cell', # Segmentation output
- min_cell_size=50, # Minimum cell size in pixels
- max_cell_size=1000 # Maximum cell size in pixels
-)
+```text
+(i, j, z, c, t) = (row, column, z-plane, channel, time/cycle)
```
-**Choosing cytoplasm channel:**
-- **CD45**: Pan-leukocyte marker (good for immune-rich tissues)
-- **panCK**: Pan-cytokeratin (good for epithelial tissues)
-- **CD298/b2m**: Universal membrane marker
-- **Combination**: Average multiple membrane markers
+Generic Bio-Formats support means a format may be readable. It does not mean
+PathML implements registration, decoding, spectral unmixing, compensation,
+autofluorescence correction, cell phenotyping, or platform-specific QC for that
+format.
-**Compartment options:**
-- `'whole-cell'`: Full cell segmentation (nucleus + cytoplasm)
-- `'nuclear'`: Nuclear segmentation only
-- `'cytoplasm'`: Cytoplasmic compartment only
+Stable PathML has convenience classes for CODEX and Vectra. It can load examples
+of MERFISH/Visium-like image data through generic backends, but it has no
+`MERFISHSlide`, `DecodeMERFISH`, or `AssignTranscripts` stable API.
-### Remote Segmentation
+## Channel manifest
-Use DeepCell cloud API for segmentation without local GPU:
+Create a local, versioned channel manifest before processing:
-```python
-from pathml.preprocessing import SegmentMIFRemote
-
-transform = SegmentMIFRemote(
- nuclear_channel='DAPI',
- cytoplasm_channel='CD45',
- model='mesmer',
- api_url='https://deepcell.org/api/predict',
- timeout=300 # Timeout in seconds
-)
+```text
+channel_index,channel_name,marker,cycle,z_plane,role,exposure,batch
+0,DAPI,DAPI,0,2,nuclear,100,run-01
+1,CD45,CD45,0,2,membrane,150,run-01
+2,CD3,CD3,1,2,measurement,200,run-01
```
-### Marker Quantification
-
-Extract single-cell marker expression from segmented images:
+Validate:
-```python
-from pathml.preprocessing import QuantifyMIF
-
-transform = QuantifyMIF(
- segmentation_mask_name='cell_segmentation',
- markers=['DAPI', 'CD3', 'CD4', 'CD8', 'CD20', 'CD68', 'panCK'],
- output_format='anndata', # or 'dataframe'
- statistics=['mean', 'median', 'std', 'total'], # Aggregation methods
- compartments=['whole-cell', 'nuclear', 'cytoplasm'] # If multiple masks
-)
-```
+- channel index is zero-based, unique, and matches array order;
+- DAPI/nuclear and membrane/cytoplasm choices are biologically and technically
+ appropriate;
+- cycle and Z-plane mappings are documented;
+- blank, autofluorescence, isotype, and positive controls are identified;
+- saturation, clipping, hot pixels, bleed-through, exposure, registration, and
+ missing channels are assessed;
+- marker names are not inferred from position alone.
-**Output:** AnnData object with:
-- `adata.X`: Marker expression matrix (cells × markers)
-- `adata.obs`: Cell metadata (cell ID, coordinates, area, etc.)
-- `adata.var`: Marker metadata
-- `adata.obsm['spatial']`: Cell centroid coordinates
+Do not include patient names, accession numbers, or other direct identifiers.
-### Integration with AnnData
+## CODEX collapse
-Process multiple CODEX slides into unified AnnData object:
+Stable signature:
```python
-from pathml.core import SlideDataset
-import anndata as ad
-
-# Process multiple slides
-slide_paths = ['slide1', 'slide2', 'slide3']
-dataset = SlideDataset(
- [CODEXSlide(p, stain='IF') for p in slide_paths]
-)
-
-# Run pipeline on all slides
-dataset.run(codex_pipeline, distributed=True, n_workers=8)
-
-# Combine into single AnnData
-adatas = []
-for slide in dataset:
- adata = slide.cell_data
- adata.obs['slide_id'] = slide.name
- adatas.append(adata)
-
-# Concatenate
-combined_adata = ad.concat(adatas, join='outer', label='batch', keys=slide_paths)
+from pathml.preprocessing import CollapseRunsCODEX, Pipeline
-# Save for downstream analysis
-combined_adata.write('codex_dataset.h5ad')
+pipeline = Pipeline([CollapseRunsCODEX(z=2)])
```
-## Vectra Workflows
+`CollapseRunsCODEX(z)` expects `(i, j, z, c, t)`, combines `c` and `t` into one
+channel axis, selects the zero-based Z-plane, and produces `(i, j, c*t)`.
-### Loading Vectra Data
+It does **not**:
-Vectra stores data in proprietary `.qptiff` format:
+- register cycles;
+- choose a focal plane automatically;
+- subtract background;
+- reorder markers from a manifest;
+- aggregate with max/mean/median; or
+- correct illumination or bleed-through.
-```python
-from pathml.core import SlideData, SlideType
-
-# Load Vectra slide
-vectra_slide = SlideData.from_slide(
- 'path/to/slide.qptiff',
- backend=SlideType.VectraQPTIFF
-)
+Perform and validate those operations upstream with a protocol appropriate to the
+acquisition system. Record the exact flattened `(cycle, channel) → output index`
+mapping.
-# Access spectral channels
-print(f"Channels: {vectra_slide.channel_names}")
-```
+## Vectra collapse
-### Vectra Preprocessing
+Stable signature:
```python
-from pathml.preprocessing import Pipeline, CollapseRunsVectra, SegmentMIF, QuantifyMIF
-
-vectra_pipeline = Pipeline([
- # 1. Process Vectra multi-channel data
- CollapseRunsVectra(
- wavelengths=[520, 540, 570, 620, 670, 780], # Emission wavelengths
- unmix=True, # Apply spectral unmixing
- autofluorescence_correction=True
- ),
-
- # 2. Cell segmentation
- SegmentMIF(
- nuclear_channel='DAPI',
- cytoplasm_channel='FITC',
- model='mesmer',
- image_resolution=0.5
- ),
-
- # 3. Quantification
- QuantifyMIF(
- segmentation_mask_name='cell_segmentation',
- markers=['DAPI', 'CD3', 'CD8', 'PD1', 'PDL1', 'panCK'],
- output_format='anndata'
- )
-])
-
-vectra_pipeline.run(vectra_slide)
-```
-
-## Downstream Analysis
+from pathml.preprocessing import CollapseRunsVectra
-### Cell Type Annotation
-
-Annotate cells based on marker expression:
-
-```python
-import anndata as ad
-import numpy as np
-
-# Load quantified data
-adata = ad.read_h5ad('codex_dataset.h5ad')
-
-# Define cell types by marker thresholds
-def annotate_cell_types(adata, thresholds):
- cell_types = np.full(adata.n_obs, 'Unknown', dtype=object)
-
- # T cells: CD3+
- cd3_pos = adata[:, 'CD3'].X.flatten() > thresholds['CD3']
- cell_types[cd3_pos] = 'T cell'
-
- # CD4 T cells: CD3+ CD4+ CD8-
- cd4_tcells = (
- (adata[:, 'CD3'].X.flatten() > thresholds['CD3']) &
- (adata[:, 'CD4'].X.flatten() > thresholds['CD4']) &
- (adata[:, 'CD8'].X.flatten() < thresholds['CD8'])
- )
- cell_types[cd4_tcells] = 'CD4 T cell'
-
- # CD8 T cells: CD3+ CD8+ CD4-
- cd8_tcells = (
- (adata[:, 'CD3'].X.flatten() > thresholds['CD3']) &
- (adata[:, 'CD8'].X.flatten() > thresholds['CD8']) &
- (adata[:, 'CD4'].X.flatten() < thresholds['CD4'])
- )
- cell_types[cd8_tcells] = 'CD8 T cell'
-
- # B cells: CD20+
- b_cells = adata[:, 'CD20'].X.flatten() > thresholds['CD20']
- cell_types[b_cells] = 'B cell'
-
- # Macrophages: CD68+
- macrophages = adata[:, 'CD68'].X.flatten() > thresholds['CD68']
- cell_types[macrophages] = 'Macrophage'
-
- # Tumor cells: panCK+
- tumor = adata[:, 'panCK'].X.flatten() > thresholds['panCK']
- cell_types[tumor] = 'Tumor'
-
- return cell_types
-
-# Apply annotation
-thresholds = {
- 'CD3': 0.5,
- 'CD4': 0.4,
- 'CD8': 0.4,
- 'CD20': 0.3,
- 'CD68': 0.3,
- 'panCK': 0.5
-}
-
-adata.obs['cell_type'] = annotate_cell_types(adata, thresholds)
-
-# Visualize cell type composition
-import matplotlib.pyplot as plt
-cell_type_counts = adata.obs['cell_type'].value_counts()
-plt.figure(figsize=(10, 6))
-cell_type_counts.plot(kind='bar')
-plt.xlabel('Cell Type')
-plt.ylabel('Count')
-plt.title('Cell Type Composition')
-plt.xticks(rotation=45)
-plt.tight_layout()
-plt.show()
+collapse = CollapseRunsVectra()
```
-### Clustering
+It applies `numpy.squeeze` to coerce the image toward `(i, j, c)`. It does not
+accept wavelengths and does not perform spectral unmixing or autofluorescence
+correction. Supply already unmixed component data or perform those steps with
+validated upstream software. Verify that squeezing singleton axes did not remove
+an axis whose semantics must be retained.
-Unsupervised clustering to identify cell populations:
-
-```python
-import scanpy as sc
+## Segmentation choices
-# Preprocessing for clustering
-sc.pp.normalize_total(adata, target_sum=1e4)
-sc.pp.log1p(adata)
-sc.pp.scale(adata, max_value=10)
+### Preferred no-network posture
-# PCA
-sc.tl.pca(adata, n_comps=50)
+For sensitive images, use an institution-approved local segmenter with a
+reviewed, checksummed local model and network disabled. PathML's generic local
+ONNX `Inference` can run compatible models, but Mesmer-specific pre/postprocessing
+must match the model card exactly.
-# Neighborhood graph
-sc.pp.neighbors(adata, n_neighbors=15, n_pcs=30)
+PathML 3.0.5 has no fully offline, nondeprecated Mesmer convenience class that
+accepts a pre-provisioned model without trying a network download. Plan this
+constraint before choosing PathML's Mesmer wrapper.
-# UMAP embedding
-sc.tl.umap(adata)
+### `SegmentMIFRemote`: local inference after a model download
-# Leiden clustering
-sc.tl.leiden(adata, resolution=0.5)
+Stable signature:
-# Visualize
-sc.pl.umap(adata, color=['leiden', 'CD3', 'CD8', 'CD20', 'panCK'])
+```text
+SegmentMIFRemote(
+ model_path="temp.onnx",
+ nuclear_channel=<integer index>,
+ cytoplasm_channel=<integer index>,
+ image_resolution=0.5,
+ preprocess_kwargs=None,
+ postprocess_kwargs_nuclear=None,
+ postprocess_kwargs_whole_cell=None,
+)
```
-### Spatial Visualization
-
-Visualize cells in spatial context:
+Despite the name, v3.0.5 does not send images to a DeepCell prediction service.
+At construction it performs an HTTP GET from:
-```python
-import matplotlib.pyplot as plt
-
-# Spatial scatter plot
-fig, ax = plt.subplots(figsize=(15, 15))
-
-# Color by cell type
-cell_types = adata.obs['cell_type'].unique()
-colors = plt.cm.tab10(np.linspace(0, 1, len(cell_types)))
-
-for i, cell_type in enumerate(cell_types):
- mask = adata.obs['cell_type'] == cell_type
- coords = adata.obsm['spatial'][mask]
- ax.scatter(
- coords[:, 0],
- coords[:, 1],
- c=[colors[i]],
- label=cell_type,
- s=5,
- alpha=0.7
- )
-
-ax.legend(markerscale=2)
-ax.set_xlabel('X (pixels)')
-ax.set_ylabel('Y (pixels)')
-ax.set_title('Spatial Cell Type Distribution')
-ax.axis('equal')
-plt.tight_layout()
-plt.show()
+```text
+https://huggingface.co/pathml/test/resolve/main/mesmer.onnx
```
-### Spatial Neighborhood Analysis
-
-Analyze cell neighborhoods and interactions:
-
-```python
-import squidpy as sq
-
-# Calculate spatial neighborhood enrichment
-sq.gr.spatial_neighbors(adata, coord_type='generic', spatial_key='spatial')
-
-# Neighborhood enrichment test
-sq.gr.nhood_enrichment(adata, cluster_key='cell_type')
-
-# Visualize interaction matrix
-sq.pl.nhood_enrichment(adata, cluster_key='cell_type')
-
-# Co-occurrence score
-sq.gr.co_occurrence(adata, cluster_key='cell_type')
-sq.pl.co_occurrence(
- adata,
- cluster_key='cell_type',
- clusters=['CD8 T cell', 'Tumor'],
- figsize=(8, 8)
-)
+It writes the response to `model_path`, loads that ONNX model, and runs pixels
+locally with ONNX Runtime. The outbound request discloses ordinary connection
+metadata (for example IP address and request headers) to Hugging Face; image
+pixels, channel data, and PathML metadata are not uploaded by this stable source.
+
+Security and reproducibility limitations:
+
+- construction has a network side effect;
+- there is no built-in checksum, signature, offline flag, timeout, or size cap;
+- the default filename is shared and easy to overwrite;
+- the model supports 256×256 input and 0.5 µm/pixel in stable code;
+- `nuclear_channel` and `cytoplasm_channel` are integer indices, not names.
+
+Do not instantiate it until the user explicitly consents to that endpoint and
+download. Do not use it in a network-disabled workflow.
+
+### Deprecated `SegmentMIF`
+
+`SegmentMIF` imports `deepcell.applications.Mesmer` and calls its prediction API
+locally. PathML emits a deprecation warning directing users to
+`SegmentMIFRemote`. `deepcell` is not a PathML extra and is not declared in
+PathML's PyPI dependencies. Depending on the DeepCell version/cache, model
+initialization may fetch weights.
+
+Do not silently install an unpinned DeepCell stack or assume compatibility with
+PathML's pinned Python/TensorFlow ecosystem. If legacy replication requires it,
+lock the complete environment, pre-provision and verify artifacts, test with
+synthetic data, disable network during sensitive runs, and document the
+deprecation.
+
+## Explicit network consent template
+
+Before any download or hosted inference, present:
+
+```text
+Action: download model | download public dataset | upload image for prediction
+Destination: exact HTTPS host and path
+Outbound data: exact pixels/channels/metadata/identifiers, or "none; GET only"
+Inbound artifact: name, expected bytes, version, SHA-256/signature
+Local destination: approved path
+Retention/logging: vendor and institutional policy
+Authorization: data-use agreement/consent/waiver and user approval
+Alternative: local, network-disabled method
```
-### Spatial Autocorrelation
+Only proceed after explicit opt-in. A future hosted endpoint that receives image
+data needs a new disclosure; do not infer permission from consent to download a
+model. Never upload PHI by default.
+
+## Quantification
-Test for spatial clustering of markers:
+Stable transform:
```python
-# Moran's I spatial autocorrelation
-sq.gr.spatial_autocorr(
- adata,
- mode='moran',
- genes=['CD3', 'CD8', 'PD1', 'PDL1', 'panCK']
-)
+from pathml.preprocessing import QuantifyMIF
-# Visualize
-results = adata.uns['moranI']
-print(results.head())
+quantify = QuantifyMIF(segmentation_mask="cell_segmentation")
```
-## MERFISH Workflows
+Input requirements:
-### Loading MERFISH Data
+- tile image `(i, j, channels)`;
+- instance segmentation `(i, j)` or `(i, j, 1)`;
+- 0 is background and each object has a unique positive integer;
+- tile slide type has fluorescence stain;
+- `tile.coords` is present.
-```python
-from pathml.core import MERFISHSlide
+`QuantifyMIF.apply(tile)` writes an `AnnData` object to `tile.counts`.
+Stable output contains:
-# Load MERFISH dataset
-merfish_slide = MERFISHSlide(
- path='path/to/merfish_data',
- fov_size=2048, # Field of view size
- microns_per_pixel=0.108
-)
-```
+- `X`: per-object mean intensity for each channel;
+- `layers["min_intensity"]` and `layers["max_intensity"]`;
+- `obs["label"]`, `filled_area`, `euler_number`, `x`, and `y`;
+- `obsm["spatial"]`: `(x, y)` centroids.
-### MERFISH Processing
+Channel variables are generated from numeric positions. Assign marker names only
+after matching the validated channel manifest:
```python
-from pathml.preprocessing import Pipeline, DecodeMERFISH, SegmentMIF
-
-merfish_pipeline = Pipeline([
- # 1. Decode barcodes to genes
- DecodeMERFISH(
- codebook='path/to/codebook.csv',
- error_correction=True,
- distance_threshold=0.5
- ),
-
- # 2. Cell segmentation
- SegmentMIF(
- nuclear_channel='DAPI',
- cytoplasm_channel='polyT', # poly(T) stain for cell boundaries
- model='mesmer'
- ),
-
- # 3. Assign transcripts to cells
- AssignTranscripts(
- segmentation_mask_name='cell_segmentation',
- transcript_coords='decoded_spots'
- )
-])
-
-merfish_pipeline.run(merfish_slide)
-
-# Output: AnnData with gene counts per cell
-gene_expression = merfish_slide.cell_data
+counts = tile.counts
+assert counts.n_vars == len(channel_names)
+counts.var_names = channel_names
```
-## Quality Control
+Do not interpret raw intensity as abundance without validated background,
+normalization, exposure, compensation/unmixing, segmentation, and batch policies.
-### Segmentation Quality
+## Coordinate conversion
-```python
-from pathml.utils import assess_segmentation_quality
+`Tile.coords` uses selected-level `(i, j)`. `QuantifyMIF` adds tile offsets to
+region centroids, then stores:
-# Check segmentation quality metrics
-qc_metrics = assess_segmentation_quality(
- segmentation_mask,
- image,
- metrics=['cell_count', 'mean_cell_size', 'size_distribution']
-)
+- `obs["y"]`: row coordinate;
+- `obs["x"]`: column coordinate;
+- `obsm["spatial"]`: `[x, y]`.
-print(f"Total cells: {qc_metrics['cell_count']}")
-print(f"Mean cell size: {qc_metrics['mean_cell_size']:.1f} pixels")
+Convert selected-level pixels to level-0 and physical units:
-# Visualize
-import matplotlib.pyplot as plt
-plt.hist(qc_metrics['cell_sizes'], bins=50)
-plt.xlabel('Cell Size (pixels)')
-plt.ylabel('Frequency')
-plt.title('Cell Size Distribution')
-plt.show()
+```text
+x_um = x_selected_level * level_downsample * mpp_x
+y_um = y_selected_level * level_downsample * mpp_y
```
-### Marker Expression QC
-
-```python
-import scanpy as sc
-
-# Load AnnData
-adata = ad.read_h5ad('codex_dataset.h5ad')
+Record whether coordinates are pixel centers, integer-rounded centroids, or
+continuous region centroids. Preserve source level and MPP. Do not combine slides
+with different resolutions in a shared coordinate space without conversion.
-# Calculate QC metrics
-adata.obs['total_intensity'] = adata.X.sum(axis=1)
-adata.obs['n_markers_detected'] = (adata.X > 0).sum(axis=1)
+## Spatial/multiplex schema
-# Filter low-quality cells
-adata = adata[adata.obs['total_intensity'] > 100, :]
-adata = adata[adata.obs['n_markers_detected'] >= 3, :]
+For exchange, use one row per cell:
-# Visualize
-sc.pl.violin(adata, ['total_intensity', 'n_markers_detected'], multi_panel=True)
+```text
+cell_id,patient_id,slide_id,tile_i,tile_j,x,y,coordinate_unit,level,
+segmentation_label,area,marker:DAPI,marker:CD3,marker:CD8,...
```
-## Batch Processing
-
-Process large multiparametric datasets efficiently:
-
-```python
-from pathml.core import SlideDataset
-from pathml.preprocessing import Pipeline
-from dask.distributed import Client
-import glob
-
-# Start Dask cluster
-client = Client(n_workers=16, threads_per_worker=2, memory_limit='8GB')
-
-# Find all CODEX slides
-slide_dirs = glob.glob('data/codex_slides/*/')
-
-# Create dataset
-codex_slides = [CODEXSlide(d, stain='IF') for d in slide_dirs]
-dataset = SlideDataset(codex_slides)
-
-# Run pipeline in parallel
-dataset.run(
- codex_pipeline,
- distributed=True,
- client=client,
- scheduler='distributed'
-)
-
-# Save processed data
-for i, slide in enumerate(dataset):
- slide.cell_data.write(f'processed/slide_{i}.h5ad')
+Required invariants:
-client.close()
-```
+- `(slide_id, cell_id)` is unique;
+- coordinates are finite and nonnegative;
+- `coordinate_unit` is explicit (`level_pixels`, `level0_pixels`, or `um`);
+- all rows for a slide agree on level/unit/channel schema;
+- marker values are finite or use one documented missing-value policy;
+- instance IDs do not collide when tiles are merged;
+- overlapping-tile duplicate cells are reconciled before counts;
+- patient/slide split is included or joinable without PHI.
-## Integration with Other Tools
+Validate bounded local CSV:
-### Export to Spatial Analysis Tools
-
-```python
-# Export to Giotto
-def export_to_giotto(adata, output_dir):
- import os
- os.makedirs(output_dir, exist_ok=True)
-
- # Expression matrix
- pd.DataFrame(
- adata.X.T,
- index=adata.var_names,
- columns=adata.obs_names
- ).to_csv(f'{output_dir}/expression.csv')
-
- # Cell coordinates
- pd.DataFrame(
- adata.obsm['spatial'],
- columns=['x', 'y'],
- index=adata.obs_names
- ).to_csv(f'{output_dir}/spatial_locs.csv')
-
-# Export to Seurat
-def export_to_seurat(adata, output_file):
- adata.write_h5ad(output_file)
- # Read in R with: library(Seurat); ReadH5AD(output_file)
+```bash
+python scripts/validate_spatial_schema.py multiplex \
+ --input derived/cells.csv \
+ --root . \
+ --marker-columns marker:DAPI,marker:CD3,marker:CD8
```
-## Best Practices
-
-1. **Channel selection for segmentation:**
- - Use brightest, most consistent nuclear marker (usually DAPI)
- - Choose membrane/cytoplasm marker based on tissue type
- - Test multiple options to optimize segmentation
-
-2. **Background subtraction:**
- - Apply before quantification to reduce autofluorescence
- - Use blank/control images to model background
-
-3. **Quality control:**
- - Visualize segmentation on sample regions
- - Check cell size distributions for outliers
- - Validate marker expression ranges
-
-4. **Cell type annotation:**
- - Start with canonical markers (CD3, CD20, panCK)
- - Use multiple markers for robust classification
- - Consider unsupervised clustering to discover populations
-
-5. **Spatial analysis:**
- - Account for tissue architecture (epithelium, stroma, etc.)
- - Consider local density when interpreting interactions
- - Use permutation tests for statistical significance
-
-6. **Batch effects:**
- - Include batch information in AnnData.obs
- - Apply batch correction if combining multiple experiments
- - Visualize batch effects with UMAP colored by batch
-
-## Common Issues and Solutions
-
-**Issue: Poor segmentation quality**
-- Verify nuclear and cytoplasm channels are correctly specified
-- Adjust image_resolution parameter to match actual resolution
-- Try different cytoplasm markers
-- Manually tune min/max cell size parameters
-
-**Issue: Low marker intensity**
-- Check for background subtraction artifacts
-- Verify channel names match actual channels
-- Inspect raw images for technical issues (focus, exposure)
-
-**Issue: Cell type annotations don't match expectations**
-- Adjust marker thresholds (too high/low)
-- Visualize marker distributions to set data-driven thresholds
-- Check for antibody specificity issues
-
-**Issue: Spatial analysis shows no significant interactions**
-- Increase neighborhood radius
-- Check for sufficient cell numbers per type
-- Verify spatial coordinates are correctly scaled
-
-## Additional Resources
-
-- **PathML Multiparametric API:** https://pathml.readthedocs.io/en/latest/api_multiparametric_reference.html
-- **CODEX:** https://www.akoyabio.com/codex/
-- **Vectra:** https://www.akoyabio.com/vectra/
-- **DeepCell Mesmer:** https://www.deepcell.org/
-- **Scanpy:** https://scanpy.readthedocs.io/ (single-cell analysis)
-- **Squidpy:** https://squidpy.readthedocs.io/ (spatial omics analysis)
+## Segmentation and marker QC
+
+Review representative training regions:
+
+- nuclear and whole-cell overlays;
+- object count, area, eccentricity, border-touching fraction, holes/fragments;
+- merge/split errors and compartment consistency;
+- negative/blank controls and background distributions;
+- per-channel saturation and dynamic range;
+- spatial striping, illumination, cycle registration, and tissue folds;
+- cell density by tissue compartment and slide;
+- marker distributions by batch/site/scanner;
+- effects of image resolution and channel choice.
+
+Freeze QC thresholds before the test set. Report exclusions and sensitivity
+analyses rather than hiding failed tiles.
+
+## Combining AnnData safely
+
+Before concatenation:
+
+- make `obs_names` globally unique with pseudonymous slide and cell IDs;
+- store `patient_id`, `slide_id`, `site`, `batch`, and `split` in `obs`;
+- enforce identical marker identity/order or perform an explicit outer join;
+- record raw versus transformed layers;
+- preserve coordinate unit/level per slide;
+- never batch-correct using held-out test data;
+- keep spatial neighbors within slides unless a cross-slide graph is scientifically
+ defined.
+
+Threshold cell typing from markers is a research annotation procedure, not a
+diagnosis. Use controls and domain review, and report ambiguous/unassigned cells.
+
+## Stable versus absent APIs
+
+Present in stable:
+
+- `MultiparametricSlide`, `VectraSlide`, `CODEXSlide`
+- `CollapseRunsCODEX(z)`
+- `CollapseRunsVectra()`
+- `SegmentMIFRemote(...)`
+- deprecated `SegmentMIF(...)`
+- `QuantifyMIF(segmentation_mask)`
+
+Not present as stable APIs:
+
+- named-channel arguments such as `"DAPI"` or `"CD45"` for segmentation;
+- `CollapseRunsCODEX(method=..., background_subtract=...)`;
+- `CollapseRunsVectra(wavelengths=..., unmix=True)`;
+- `MERFISHSlide`, `DecodeMERFISH`, or `AssignTranscripts`;
+- a DeepCell image-upload URL in PathML;
+- automatic marker names in `QuantifyMIF`;
+- automatic cell-type annotation.
+
+## Sources, accessed 2026-07-23
+
+- Stable loading guide:
+ https://pathml.readthedocs.io/en/stable/loading_slides.html
+- Stable preprocessing API:
+ https://pathml.readthedocs.io/en/stable/api_preprocessing_reference.html
+- Stable transforms source:
+ https://github.com/Dana-Farber-AIOS/pathml/blob/v3.0.5/pathml/preprocessing/transforms.py
+- Stable inference source:
+ https://github.com/Dana-Farber-AIOS/pathml/blob/v3.0.5/pathml/inference/inference.py
+- Stable multiplex tutorial:
+ https://pathml.readthedocs.io/en/stable/examples/link_multiplex_if.html
+- Stable CODEX tutorial:
+ https://pathml.readthedocs.io/en/stable/examples/link_codex.html
+- Greenwald et al. (2022), Mesmer:
+ https://doi.org/10.1038/s41587-021-01094-0
+- Omar et al. (2025), antibody-based multiplex workflows:
+ https://doi.org/10.1016/j.labinv.2025.104220
diff --git a/skills/pathml/references/preprocessing.md b/skills/pathml/references/preprocessing.md
index 5e8c21fd..eb723a70 100644
--- a/skills/pathml/references/preprocessing.md
+++ b/skills/pathml/references/preprocessing.md
@@ -1,722 +1,371 @@
-# Preprocessing Pipelines & Transforms
+# Preprocessing pipelines, masks, stain handling, and QC
-## Overview
+This reference describes **PathML 3.0.5 stable**. It corrects older examples that
+called nonexistent `Pipeline.run()`, omitted required mask/label names, or passed
+unsupported transform arguments.
-PathML provides a modular preprocessing architecture based on composable transforms organized into pipelines. Transforms are individual operations that modify images, create masks, or extract features. Pipelines chain transforms together to create reproducible, scalable preprocessing workflows for computational pathology.
+## Pipeline execution model
-## Pipeline Architecture
+A `Pipeline` is an ordered list of `Transform` objects. `Pipeline.apply(tile)`
+modifies one `Tile` in place and returns it. A slide or dataset owns execution:
-### Pipeline Class
-
-The `Pipeline` class composes a sequence of transforms applied consecutively:
-
-```python
-from pathml.preprocessing import Pipeline, Transform1, Transform2
-
-# Create pipeline
-pipeline = Pipeline([
- Transform1(param1=value1),
- Transform2(param2=value2),
- # ... more transforms
-])
-
-# Run on a single slide
-pipeline.run(slide_data)
-
-# Run on a dataset
-pipeline.run(dataset, distributed=True, n_workers=8)
-```
-
-**Key features:**
-- Sequential execution of transforms
-- Automatic handling of tiles and masks
-- Distributed processing support with Dask
-- Reproducible workflows with serializable configuration
-
-### Transform Base Class
-
-All transforms inherit from the `Transform` base class and implement:
-- `apply()` - Core transformation logic
-- `input_type` - Expected input (tile, mask, etc.)
-- `output_type` - Produced output
-
-## Transform Categories
-
-PathML provides transforms in six major categories:
-
-1. **Image Modification** - Blur, rescale, histogram equalization
-2. **Mask Creation** - Tissue detection, nucleus detection, thresholding
-3. **Mask Modification** - Morphological operations on masks
-4. **Stain Processing** - H&E stain normalization and separation
-5. **Quality Control** - Artifact detection, white space labeling
-6. **Specialized** - Multiparametric imaging, cell segmentation
-
-## Image Modification Transforms
-
-### Blur Operations
-
-Apply various blurring kernels for noise reduction:
-
-**MedianBlur:**
-```python
-from pathml.preprocessing import MedianBlur
-
-# Apply median filter
-transform = MedianBlur(kernel_size=5)
-```
-- Effective for salt-and-pepper noise
-- Preserves edges better than Gaussian blur
-
-**GaussianBlur:**
-```python
-from pathml.preprocessing import GaussianBlur
-
-# Apply Gaussian blur
-transform = GaussianBlur(kernel_size=5, sigma=1.0)
-```
-- Smooth noise reduction
-- Adjustable sigma controls blur strength
-
-**BoxBlur:**
```python
-from pathml.preprocessing import BoxBlur
+from pathml.core import HESlide
+from pathml.preprocessing import BoxBlur, Pipeline, TissueDetectionHE
-# Apply box filter
-transform = BoxBlur(kernel_size=5)
-```
-- Fastest blur operation
-- Uniform averaging within kernel
-
-### Intensity Adjustments
-
-**RescaleIntensity:**
-```python
-from pathml.preprocessing import RescaleIntensity
+slide = HESlide("data/slide-001.svs", backend="openslide")
+pipeline = Pipeline(
+ [
+ BoxBlur(kernel_size=5),
+ TissueDetectionHE(mask_name="tissue"),
+ ]
+)
-# Rescale intensity to [0, 255]
-transform = RescaleIntensity(
- in_range=(0, 1.0),
- out_range=(0, 255)
+slide.run(
+ pipeline,
+ distributed=False,
+ tile_size=512,
+ tile_stride=512,
+ level=0,
+ tile_pad=False,
)
```
-**HistogramEqualization:**
-```python
-from pathml.preprocessing import HistogramEqualization
-
-# Global histogram equalization
-transform = HistogramEqualization()
-```
-- Enhances global contrast
-- Spreads out intensity distribution
+Stable facts:
-**AdaptiveHistogramEqualization (CLAHE):**
-```python
-from pathml.preprocessing import AdaptiveHistogramEqualization
+- `Pipeline(transform_sequence=None)` and `Pipeline.apply(tile)` are public.
+- `Pipeline` has no `run()` method.
+- `SlideData.run()` and `SlideDataset.run()` apply pipelines.
+- `distributed=True` is the default and may create a local Dask cluster using
+ available cores. Start with `distributed=False`.
+- Existing tiles are protected unless `overwrite_existing_tiles=True`.
+- `write_dir` causes a `<slide.name>.h5path` write after processing.
+- `Pipeline.save()` writes a pickle. A pickle is executable on load; never use a
+ pipeline file from an untrusted source.
-# Contrast Limited Adaptive Histogram Equalization
-transform = AdaptiveHistogramEqualization(
- clip_limit=0.03,
- tile_grid_size=(8, 8)
-)
-```
-- Enhances local contrast
-- Prevents over-amplification with clip_limit
-- Better for images with varying local contrast
+## Stable transform imports
-### Superpixel Processing
-
-**SuperpixelInterpolation:**
```python
-from pathml.preprocessing import SuperpixelInterpolation
-
-# Divide into superpixels using SLIC
-transform = SuperpixelInterpolation(
- n_segments=100,
- compactness=10.0
+from pathml.preprocessing import (
+ AdaptiveHistogramEqualization,
+ BinaryThreshold,
+ BoxBlur,
+ CollapseRunsCODEX,
+ CollapseRunsVectra,
+ ForegroundDetection,
+ GaussianBlur,
+ HistogramEqualization,
+ LabelArtifactTileHE,
+ LabelWhiteSpaceHE,
+ MedianBlur,
+ MorphClose,
+ MorphOpen,
+ NucleusDetectionHE,
+ Pipeline,
+ QuantifyMIF,
+ RescaleIntensity,
+ SegmentMIF,
+ SegmentMIFRemote,
+ StainNormalizationHE,
+ SuperpixelInterpolation,
+ TissueDetectionHE,
)
```
-- Segments image into perceptually meaningful regions
-- Useful for feature extraction and segmentation
-## Mask Creation Transforms
+There is no stable `transform='...'` registry and no safe reason to construct
+transforms from arbitrary Python expressions. Parse a strict allowlisted config,
+then instantiate known classes explicitly.
-### H&E Tissue and Nucleus Detection
+## Tissue detection
-**TissueDetectionHE:**
```python
from pathml.preprocessing import TissueDetectionHE
-# Detect tissue regions in H&E slides
-transform = TissueDetectionHE(
- use_saturation=True, # Use HSV saturation channel
- threshold=10, # Intensity threshold
- min_region_size=500 # Minimum tissue region size in pixels
+tissue = TissueDetectionHE(
+ mask_name="tissue",
+ use_saturation=True,
+ blur_ksize=17,
+ threshold=None, # Otsu when None
+ morph_n_iter=3,
+ morph_k_size=7,
+ min_region_size=5000,
+ max_hole_size=1500,
+ outer_contours_only=False,
)
```
-- Creates binary tissue mask
-- Filters small regions and artifacts
-- Stores mask in `tile.masks['tissue']`
-**NucleusDetectionHE:**
-```python
-from pathml.preprocessing import NucleusDetectionHE
+The transform expects an H&E `uint8` tile. It:
-# Detect nuclei in H&E images
-transform = NucleusDetectionHE(
- stain='hematoxylin', # Use hematoxylin channel
- threshold=0.3,
- min_nucleus_size=10
-)
-```
-- Separates hematoxylin stain
-- Thresholds to create nucleus mask
-- Stores mask in `tile.masks['nucleus']`
+1. uses HSV saturation or greyscale;
+2. median-blurs;
+3. applies Otsu or the explicit threshold;
+4. performs morphological opening and closing;
+5. keeps foreground regions under the configured area/hole policy; and
+6. writes `tile.masks["tissue"]`.
-### Binary Thresholding
+`mask_name` is required in practice; `None` fails when `apply()` runs.
+`min_region_size`, `max_hole_size`, and morphology kernels are measured in pixels
+at the processing level. Re-tune if level or MPP changes.
-**BinaryThreshold:**
-```python
-from pathml.preprocessing import BinaryThreshold
+Tissue detection is tile-local. It can disagree at tile edges, and PathML does not
+automatically remove background tiles from the pipeline. Compute and record tissue
+coverage after the mask exists:
-# Threshold using Otsu's method
-transform = BinaryThreshold(
- method='otsu', # 'otsu' or manual threshold value
- invert=False
-)
-
-# Or specify manual threshold
-transform = BinaryThreshold(threshold=128)
-```
-
-### Foreground Detection
-
-**ForegroundDetection:**
```python
-from pathml.preprocessing import ForegroundDetection
-
-# Detect foreground regions
-transform = ForegroundDetection(
- threshold=0.5,
- min_region_size=1000, # Minimum size in pixels
- use_saturation=True
-)
+coverage = float((tile.masks["tissue"] > 0).mean())
+keep = coverage >= 0.50
```
-## Mask Modification Transforms
-
-Apply morphological operations to clean up masks:
+Choose the coverage rule on training data and preserve rejected-tile counts.
-**MorphOpen:**
-```python
-from pathml.preprocessing import MorphOpen
+## Whitespace and artifact QC
-# Remove small objects and noise
-transform = MorphOpen(
- kernel_size=5,
- mask_name='tissue' # Which mask to modify
-)
-```
-- Erosion followed by dilation
-- Removes small objects and noise
+These transforms write **tile labels**, not pixel masks:
-**MorphClose:**
```python
-from pathml.preprocessing import MorphClose
+from pathml.preprocessing import LabelArtifactTileHE, LabelWhiteSpaceHE
-# Fill small holes
-transform = MorphClose(
- kernel_size=5,
- mask_name='tissue'
+whitespace = LabelWhiteSpaceHE(
+ label_name="mostly_white",
+ greyscale_threshold=230,
+ proportion_threshold=0.5,
)
+artifact = LabelArtifactTileHE(label_name="artifact")
```
-- Dilation followed by erosion
-- Fills small holes in mask
-
-## Stain Normalization
-### StainNormalizationHE
+- `LabelWhiteSpaceHE` labels a tile when the proportion of greyscale pixels above
+ the threshold exceeds `proportion_threshold`.
+- `LabelArtifactTileHE` is a fixed rule-based HSI heuristic for whitespace,
+ dark regions, and pen-like colors. It exposes only `label_name`; older examples
+ with `pen_threshold` or `bubble_threshold` are invalid.
-Normalize H&E staining across slides to account for variations in staining procedure and scanners:
+Neither is a complete slide-quality system. Review representative overlays and
+track blur, folds, bubbles, pen, tissue coverage, clipping, color drift, missing
+channels, and focus separately. Do not convert a heuristic QC flag into a clinical
+quality judgment.
-```python
-from pathml.preprocessing import StainNormalizationHE
+The dependency-free helper provides a deliberately simple synthetic/local check,
+not a replacement for PathML:
-# Normalize to reference slide
-transform = StainNormalizationHE(
- target='normalize', # 'normalize', 'hematoxylin', or 'eosin'
- stain_estimation_method='macenko', # 'macenko' or 'vahadane'
- tissue_mask_name=None # Optional tissue mask for better estimation
-)
+```bash
+python scripts/image_qc.py synthetic --width 256 --height 256
+python scripts/image_qc.py inspect --image tests/fixtures/synthetic.ppm --root .
```
-**Target modes:**
-- `'normalize'` - Normalize both stains to reference
-- `'hematoxylin'` - Extract hematoxylin channel only
-- `'eosin'` - Extract eosin channel only
+It reports brightness/saturation and a coarse tissue-like mask using bounded
+pixels. PNG/JPEG/TIFF input needs Pillow, imported only after argument validation.
-**Stain estimation methods:**
-- `'macenko'` - Macenko et al. 2009 method (faster, more stable)
-- `'vahadane'` - Vahadane et al. 2016 method (more accurate, slower)
+## H&E stain normalization and separation
-**Advanced parameters:**
```python
-transform = StainNormalizationHE(
- target='normalize',
- stain_estimation_method='macenko',
- target_od=None, # Optical density matrix for reference (optional)
- target_concentrations=None, # Target stain concentrations (optional)
- regularizer=0.1, # Regularization for vahadane method
- background_intensity=240 # Background intensity level
-)
-```
-
-**Workflow:**
-1. Convert RGB to optical density (OD)
-2. Estimate stain matrix (H&E vectors)
-3. Decompose into stain concentrations
-4. Normalize to reference stain distribution
-5. Reconstruct normalized RGB image
+from pathml.preprocessing import StainNormalizationHE
-**Example with tissue mask:**
-```python
-from pathml.preprocessing import Pipeline, TissueDetectionHE, StainNormalizationHE
-
-pipeline = Pipeline([
- TissueDetectionHE(), # Create tissue mask first
- StainNormalizationHE(
- target='normalize',
- stain_estimation_method='macenko',
- tissue_mask_name='tissue' # Use tissue mask for better estimation
- )
-])
+normalizer = StainNormalizationHE(
+ target="normalize", # normalize | hematoxylin | eosin
+ stain_estimation_method="macenko", # macenko | vahadane
+ optical_density_threshold=0.15,
+ regularizer=0.1,
+ angular_percentile=0.01,
+ background_intensity=245,
+)
```
-## Quality Control Transforms
-
-### Artifact Detection
-
-**LabelArtifactTileHE:**
-```python
-from pathml.preprocessing import LabelArtifactTileHE
+Stable `StainNormalizationHE` does **not** accept `tissue_mask_name`,
+`target_od`, or `target_concentrations`. It accepts `stain_matrix_target_od` and
+`max_c_target`, and supplies fixed defaults.
-# Label tiles containing artifacts
-transform = LabelArtifactTileHE(
- pen_threshold=0.5, # Threshold for pen marking detection
- bubble_threshold=0.5 # Threshold for bubble detection
-)
-```
-- Detects pen markings, bubbles, and other artifacts
-- Labels affected tiles for filtering
+To fit a reference:
-**LabelWhiteSpaceHE:**
```python
-from pathml.preprocessing import LabelWhiteSpaceHE
-
-# Label tiles with excessive white space
-transform = LabelWhiteSpaceHE(
- threshold=0.9, # Fraction of white pixels
- mask_name='white_space'
-)
+normalizer.fit_to_reference(training_reference_rgb)
+normalized_rgb = normalizer.F(source_rgb)
```
-- Identifies tiles with mostly background
-- Useful for filtering uninformative tiles
-
-## Multiparametric Imaging Transforms
-### Cell Segmentation
+Leakage controls:
-**SegmentMIF:**
-```python
-from pathml.preprocessing import SegmentMIF
-
-# Segment cells using Mesmer deep learning model
-transform = SegmentMIF(
- nuclear_channel='DAPI', # Nuclear marker channel name
- cytoplasm_channel='CD45', # Cytoplasm marker channel name
- model='mesmer', # Deep learning segmentation model
- image_resolution=0.5, # Microns per pixel
- compartment='whole-cell' # 'nuclear', 'cytoplasm', or 'whole-cell'
-)
-```
-- Uses DeepCell Mesmer model for cell segmentation
-- Requires nuclear and cytoplasm channel specification
-- Produces instance segmentation masks
+- Select the reference and tune OD parameters using training slides only.
+- Freeze the fitted stain matrix and target concentration before validation/test.
+- Do not choose a reference because test performance looks better.
+- Record source slide pseudonym, region coordinates, level, MPP, method, and all
+ fitted arrays without direct identifiers.
+- Fit on tissue-rich, artifact-free RGB regions. Stable API does not consume a
+ tissue mask directly, so crop/filter the reference beforehand.
-**SegmentMIFRemote:**
-```python
-from pathml.preprocessing import SegmentMIFRemote
-
-# Remote inference using DeepCell API
-transform = SegmentMIFRemote(
- nuclear_channel='DAPI',
- cytoplasm_channel='CD45',
- model='mesmer',
- api_url='https://deepcell.org/api'
-)
-```
-- Same functionality as SegmentMIF but uses remote API
-- No local GPU required
-- Suitable for batch processing
+Macenko and Vahadane are model-based color standardization methods, not guarantees
+that biological staining becomes comparable. Preserve raw inputs and assess
+whether normalization removes task-relevant signal or amplifies artifacts.
-### Marker Quantification
+## Simple H&E nucleus mask
-**QuantifyMIF:**
```python
-from pathml.preprocessing import QuantifyMIF
+from pathml.preprocessing import NucleusDetectionHE
-# Quantify marker expression per cell
-transform = QuantifyMIF(
- segmentation_mask_name='cell_segmentation',
- markers=['CD3', 'CD4', 'CD8', 'CD20', 'CD45'],
- output_format='anndata' # or 'dataframe'
+nuclei = NucleusDetectionHE(
+ mask_name="nuclei",
+ stain_estimation_method="vahadane",
+ superpixel_region_size=10,
+ n_iter=30,
)
```
-- Extracts mean marker intensity per segmented cell
-- Computes morphological features (area, perimeter, etc.)
-- Outputs AnnData object for downstream single-cell analysis
-### CODEX/Vectra Specific
+This is a simple transform: hematoxylin separation, superpixel interpolation, and
+Otsu thresholding. It writes a binary tile mask. It is not HoVer-Net, does not
+assign nucleus classes, and should not be treated as a validated cell count.
+Inspect touching objects, fragments, necrosis, stain failure, and tile boundaries.
-**CollapseRunsCODEX:**
-```python
-from pathml.preprocessing import CollapseRunsCODEX
+## Binary and morphology building blocks
-# Consolidate multi-run CODEX data
-transform = CollapseRunsCODEX(
- z_slice=2, # Select specific z-slice
- run_order=[0, 1, 2] # Order of acquisition runs
-)
-```
-- Merges channels from multiple CODEX acquisition runs
-- Selects focal plane from z-stacks
+Useful stable signatures:
-**CollapseRunsVectra:**
```python
-from pathml.preprocessing import CollapseRunsVectra
+from pathml.preprocessing import BinaryThreshold, MorphClose, MorphOpen
-# Process Vectra multiplex IF data
-transform = CollapseRunsVectra(
- wavelengths=[520, 570, 620, 670, 780] # Emission wavelengths
+threshold = BinaryThreshold(
+ mask_name="foreground",
+ use_otsu=True,
+ threshold=0,
+ inverse=False,
)
+opened = MorphOpen(mask_name="foreground", kernel_size=5, n_iterations=1)
+closed = MorphClose(mask_name="foreground", kernel_size=5, n_iterations=1)
```
-## Building Comprehensive Pipelines
+`BinaryThreshold.apply()` creates a named mask. `MorphOpen` and `MorphClose`
+modify the named mask. Match dtype, polarity, and dimensions explicitly.
-### Basic H&E Preprocessing Pipeline
+## Recommended pilot pipeline
```python
from pathml.preprocessing import (
+ BoxBlur,
+ LabelArtifactTileHE,
+ LabelWhiteSpaceHE,
Pipeline,
- TissueDetectionHE,
StainNormalizationHE,
- NucleusDetectionHE,
- MedianBlur,
- LabelWhiteSpaceHE
-)
-
-pipeline = Pipeline([
- # 1. Quality control
- LabelWhiteSpaceHE(threshold=0.9),
-
- # 2. Noise reduction
- MedianBlur(kernel_size=3),
-
- # 3. Tissue detection
- TissueDetectionHE(min_region_size=500),
-
- # 4. Stain normalization
- StainNormalizationHE(
- target='normalize',
- stain_estimation_method='macenko',
- tissue_mask_name='tissue'
- ),
-
- # 5. Nucleus detection
- NucleusDetectionHE(threshold=0.3)
-])
-```
-
-### CODEX Multiparametric Pipeline
-
-```python
-from pathml.preprocessing import (
- Pipeline,
- CollapseRunsCODEX,
- SegmentMIF,
- QuantifyMIF
-)
-
-codex_pipeline = Pipeline([
- # 1. Consolidate multi-run data
- CollapseRunsCODEX(z_slice=2),
-
- # 2. Cell segmentation
- SegmentMIF(
- nuclear_channel='DAPI',
- cytoplasm_channel='CD45',
- model='mesmer',
- image_resolution=0.377
- ),
-
- # 3. Quantify markers
- QuantifyMIF(
- segmentation_mask_name='cell_segmentation',
- markers=['CD3', 'CD4', 'CD8', 'CD20', 'PD1', 'PDL1'],
- output_format='anndata'
- )
-])
-```
-
-### Advanced Pipeline with Quality Control
-
-```python
-from pathml.preprocessing import (
- Pipeline,
- LabelWhiteSpaceHE,
- LabelArtifactTileHE,
TissueDetectionHE,
- MorphOpen,
- MorphClose,
- StainNormalizationHE,
- AdaptiveHistogramEqualization
-)
-
-advanced_pipeline = Pipeline([
- # Stage 1: Quality control
- LabelWhiteSpaceHE(threshold=0.85),
- LabelArtifactTileHE(pen_threshold=0.5, bubble_threshold=0.5),
-
- # Stage 2: Tissue detection
- TissueDetectionHE(threshold=10, min_region_size=1000),
- MorphOpen(kernel_size=5, mask_name='tissue'),
- MorphClose(kernel_size=7, mask_name='tissue'),
-
- # Stage 3: Stain normalization
- StainNormalizationHE(
- target='normalize',
- stain_estimation_method='vahadane',
- tissue_mask_name='tissue'
- ),
-
- # Stage 4: Contrast enhancement
- AdaptiveHistogramEqualization(clip_limit=0.03, tile_grid_size=(8, 8))
-])
-```
-
-## Running Pipelines
-
-### Single Slide Processing
-
-```python
-from pathml.core import SlideData
-
-# Load slide
-wsi = SlideData.from_slide("slide.svs")
-
-# Generate tiles
-wsi.generate_tiles(level=1, tile_size=256, stride=256)
-
-# Run pipeline
-pipeline.run(wsi)
-
-# Access processed data
-for tile in wsi.tiles:
- normalized_image = tile.image
- tissue_mask = tile.masks.get('tissue')
- nucleus_mask = tile.masks.get('nucleus')
-```
-
-### Batch Processing with Distributed Execution
-
-```python
-from pathml.core import SlideDataset
-from dask.distributed import Client
-import glob
-
-# Start Dask client
-client = Client(n_workers=8, threads_per_worker=2, memory_limit='4GB')
-
-# Create dataset
-slide_paths = glob.glob("data/*.svs")
-dataset = SlideDataset(
- slide_paths,
- tile_size=512,
- stride=512,
- level=1
)
-# Run pipeline in parallel
-dataset.run(
- pipeline,
- distributed=True,
- client=client
+pipeline = Pipeline(
+ [
+ LabelWhiteSpaceHE(
+ label_name="mostly_white",
+ greyscale_threshold=230,
+ proportion_threshold=0.8,
+ ),
+ LabelArtifactTileHE(label_name="artifact"),
+ BoxBlur(kernel_size=3),
+ TissueDetectionHE(
+ mask_name="tissue",
+ min_region_size=5000,
+ outer_contours_only=False,
+ ),
+ StainNormalizationHE(
+ target="normalize",
+ stain_estimation_method="macenko",
+ ),
+ ]
)
-
-# Save results
-dataset.to_hdf5("processed_dataset.h5")
-
-client.close()
```
-### Conditional Pipeline Execution
-
-Execute transforms only on tiles meeting specific criteria:
-
-```python
-# Filter tiles before processing
-wsi.generate_tiles(level=1, tile_size=256)
-
-# Run pipeline only on tissue tiles
-for tile in wsi.tiles:
- if tile.masks.get('tissue') is not None:
- pipeline.run(tile)
-```
-
-## Performance Optimization
-
-### Memory Management
-
-```python
-# Process large datasets in batches
-batch_size = 100
-for i in range(0, len(slide_paths), batch_size):
- batch_paths = slide_paths[i:i+batch_size]
- batch_dataset = SlideDataset(batch_paths)
- batch_dataset.run(pipeline, distributed=True)
- batch_dataset.to_hdf5(f"batch_{i}.h5")
-```
+QC labels do not short-circuit later transforms. If expensive stages should run
+only on accepted tiles, write an explicit custom transform or bounded manual loop
+with a documented policy. Keep the logic deterministic and test it.
-### GPU Acceleration
+## Bounded dry run
-Certain transforms leverage GPU acceleration when available:
+PathML has no `max_tiles` argument. Use `islice` for a local pilot:
```python
-import torch
-
-# Check GPU availability
-print(f"CUDA available: {torch.cuda.is_available()}")
-
-# Transforms that benefit from GPU:
-# - SegmentMIF (Mesmer deep learning model)
-# - StainNormalizationHE (matrix operations)
-```
-
-### Parallel Workers Configuration
-
-```python
-from dask.distributed import Client
-
-# CPU-bound tasks (image processing)
-client = Client(
- n_workers=8,
- threads_per_worker=1, # Use processes, not threads
- memory_limit='8GB'
-)
-
-# GPU tasks (deep learning inference)
-client = Client(
- n_workers=2, # Fewer workers for GPU
- threads_per_worker=4,
- processes=True
-)
-```
-
-## Custom Transforms
+from itertools import islice
-Create custom preprocessing operations by subclassing `Transform`:
-
-```python
-from pathml.preprocessing.transforms import Transform
-import numpy as np
-
-class CustomTransform(Transform):
- def __init__(self, param1, param2):
- self.param1 = param1
- self.param2 = param2
-
- def apply(self, tile):
- # Access tile image
- image = tile.image
-
- # Apply custom operation
- processed = self.custom_operation(image, self.param1, self.param2)
-
- # Update tile
- tile.image = processed
-
- return tile
-
- def custom_operation(self, image, param1, param2):
- # Implement custom logic
- return processed_image
-
-# Use in pipeline
-pipeline = Pipeline([
- CustomTransform(param1=10, param2=0.5),
- # ... other transforms
-])
+sampled = []
+for tile in islice(
+ slide.generate_tiles(shape=512, stride=512, pad=False, level=0),
+ 16,
+):
+ pipeline.apply(tile)
+ sampled.append(
+ {
+ "coords_ij": tile.coords,
+ "shape": tuple(tile.image.shape),
+ "tissue_fraction": float((tile.masks["tissue"] > 0).mean()),
+ "mostly_white": bool(tile.labels["mostly_white"]),
+ "artifact": bool(tile.labels["artifact"]),
+ }
+ )
```
-## Best Practices
-
-1. **Order transforms appropriately:**
- - Quality control first (LabelWhiteSpace, LabelArtifact)
- - Noise reduction early (Blur)
- - Tissue detection before stain normalization
- - Stain normalization before color-dependent operations
-
-2. **Use tissue masks for stain normalization:**
- - Improves accuracy by excluding background
- - `TissueDetectionHE()` then `StainNormalizationHE(tissue_mask_name='tissue')`
-
-3. **Apply morphological operations to clean masks:**
- - `MorphOpen` to remove small false positives
- - `MorphClose` to fill small gaps
-
-4. **Leverage distributed processing for large datasets:**
- - Use Dask for parallel execution
- - Configure workers based on available resources
-
-5. **Save intermediate results:**
- - Store processed data to HDF5 for reuse
- - Avoid reprocessing computationally expensive transforms
-
-6. **Validate preprocessing on sample images:**
- - Visualize intermediate steps
- - Tune parameters on representative samples before batch processing
-
-7. **Handle edge cases:**
- - Check for empty masks before downstream operations
- - Validate tile quality before expensive computations
-
-## Common Issues and Solutions
-
-**Issue: Stain normalization produces artifacts**
-- Use tissue mask to exclude background
-- Try different stain estimation method (macenko vs. vahadane)
-- Verify optical density parameters match your images
-
-**Issue: Out of memory during pipeline execution**
-- Reduce number of Dask workers
-- Decrease tile size
-- Process images at lower pyramid level
-- Enable memory_limit parameter in Dask client
-
-**Issue: Tissue detection misses tissue regions**
-- Adjust threshold parameter
-- Use saturation channel: `use_saturation=True`
-- Reduce min_region_size to capture smaller tissue fragments
-
-**Issue: Nucleus detection is inaccurate**
-- Verify stain separation quality (visualize hematoxylin channel)
-- Adjust threshold parameter
-- Apply stain normalization before nucleus detection
-
-## Additional Resources
-
-- **PathML Preprocessing API:** https://pathml.readthedocs.io/en/latest/api_preprocessing_reference.html
-- **Stain Normalization Methods:**
- - Macenko et al. 2009: "A method for normalizing histology slides for quantitative analysis"
- - Vahadane et al. 2016: "Structure-Preserving Color Normalization and Sparse Stain Separation"
-- **DeepCell Mesmer:** https://www.deepcell.org/ (cell segmentation model)
+Plan first:
+
+```bash
+python scripts/plan_pipeline.py \
+ --width 100000 --height 80000 \
+ --tile-size 512 --stride 512 \
+ --pipeline TissueDetectionHE,LabelWhiteSpaceHE,StainNormalizationHE \
+ --max-tiles 1000000
+```
+
+The planner never opens the slide or imports PathML. Supply dimensions from a
+trusted technical metadata inspection.
+
+## Masks, labels, padding, and overlap
+
+- A tile mask's first two dimensions must match the tile image.
+- Use distinct semantic names (`tissue`, `nuclei`, `cell_segmentation`) and record
+ whether each mask is binary, semantic, or instance-labeled.
+- Instance masks use 0 for background and positive integer object IDs.
+- `tile_pad=True` introduces zeros. Document whether padded pixels are ignored in
+ QC, stain fitting, loss, and stitching.
+- Stable `SlideData.generate_tiles()` cannot slice slide-level masks into padded
+ tiles.
+- Overlap duplicates tissue/cells. Deduplicate by slide coordinates or use an
+ explicit blending/cropping policy before counting.
+- Keep masks at the same level as their coordinates. Resampling an instance mask
+ requires nearest-neighbor interpolation and relabel/QC.
+
+## Train/validation/test leakage checklist
+
+Do all splitting before:
+
+- choosing stain references;
+- estimating QC or tissue thresholds;
+- fitting feature scalers;
+- learning augmentations or color distributions;
+- selecting segmentation parameters;
+- extracting overlapping tiles;
+- constructing graphs; or
+- calibrating model thresholds.
+
+All tiles, regions, serial sections, and repeat scans from one patient belong to
+one split. If site/scanner generalization is the target, reserve entire sites or
+scanners as designed. Record exclusions before viewing test outcomes.
+
+## Reproducibility record
+
+For each run, retain:
+
+- PathML and dependency lock versions;
+- source SHA-256 and pseudonymous IDs;
+- backend, level, downsample, MPP, tile size/stride/pad;
+- ordered transform names and all constructor values;
+- fitted stain arrays and training-only reference provenance;
+- QC/mask definitions and per-slide accept/reject totals;
+- Dask configuration, worker count, CPU/GPU, and failure/retry policy;
+- code revision, random seeds, split manifest hash, and output hashes.
+
+## Sources, accessed 2026-07-23
+
+- Stable pipeline guide:
+ https://pathml.readthedocs.io/en/stable/creating_pipelines.html
+- Stable execution guide:
+ https://pathml.readthedocs.io/en/stable/running_pipelines.html
+- Stable preprocessing API:
+ https://pathml.readthedocs.io/en/stable/api_preprocessing_reference.html
+- Stable transforms source:
+ https://github.com/Dana-Farber-AIOS/pathml/blob/v3.0.5/pathml/preprocessing/transforms.py
+- Stable pipeline source:
+ https://github.com/Dana-Farber-AIOS/pathml/blob/v3.0.5/pathml/preprocessing/pipeline.py
+- Macenko et al. (2009):
+ https://doi.org/10.1109/ISBI.2009.5193250
+- Vahadane et al. (2016):
+ https://doi.org/10.1109/TMI.2016.2529665
diff --git a/skills/pathml/scripts/_common.py b/skills/pathml/scripts/_common.py
new file mode 100644
index 00000000..90e9c32c
--- /dev/null
+++ b/skills/pathml/scripts/_common.py
@@ -0,0 +1,385 @@
+#!/usr/bin/env python3
+"""Shared bounded-I/O helpers for the PathML skill CLIs."""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import math
+import os
+import stat
+import tempfile
+from collections.abc import Iterable, Mapping
+from pathlib import Path
+from typing import Any
+
+
+PATHML_VERSION = "3.0.5"
+PINNED_INSTALL = 'uv pip install "pathml==3.0.5"'
+MAX_JSON_BYTES = 16 * 1024 * 1024
+MAX_CSV_BYTES = 64 * 1024 * 1024
+MAX_IMAGE_BYTES = 256 * 1024 * 1024
+MAX_REPORT_BYTES = 8 * 1024 * 1024
+MAX_ROWS = 1_000_000
+MAX_PIXELS = 16_000_000
+MAX_DIMENSION = 1_000_000_000
+
+
+class CliError(ValueError):
+ """An expected, concise command-line validation error."""
+
+
+def _reject_constant(value: str) -> None:
+ raise CliError(f"non-standard JSON constant is not allowed: {value}")
+
+
+def _unique_object(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
+ result: dict[str, Any] = {}
+ for key, value in pairs:
+ if key in result:
+ raise CliError(f"duplicate JSON key is not allowed: {key!r}")
+ result[key] = value
+ return result
+
+
+def _reject_url(value: str) -> None:
+ lowered = value.strip().lower()
+ if "://" in lowered or lowered.startswith(
+ ("http:", "https:", "ftp:", "s3:", "gs:", "file:")
+ ):
+ raise CliError("URLs are not accepted; provide a bounded local path")
+ if "\x00" in value:
+ raise CliError("paths must not contain a NUL byte")
+
+
+def _absolute_lexical(path: Path) -> Path:
+ """Make a path absolute and collapse dot segments without following links."""
+
+ return Path(os.path.abspath(os.fspath(path)))
+
+
+def _reject_symlink_components(path: Path) -> None:
+ """Reject an existing symlink anywhere in an absolute path."""
+
+ absolute = _absolute_lexical(path)
+ current = Path(absolute.anchor)
+ for part in absolute.parts[1:]:
+ current /= part
+ try:
+ if current.is_symlink():
+ raise CliError(f"symlink paths are not accepted: {current.name}")
+ except OSError as exc:
+ raise CliError(f"cannot inspect path component {current.name}: {exc}") from exc
+
+
+def checked_root(value: str | os.PathLike[str]) -> Path:
+ """Return an existing non-symlink directory used as an I/O boundary."""
+
+ raw = os.fspath(value)
+ _reject_url(raw)
+ supplied = _absolute_lexical(Path(raw).expanduser())
+ if supplied.is_symlink():
+ raise CliError("root directory must not itself be a symlink")
+ try:
+ root = supplied.resolve(strict=True)
+ info = root.stat()
+ except OSError as exc:
+ raise CliError(f"cannot access root directory: {exc}") from exc
+ if not stat.S_ISDIR(info.st_mode):
+ raise CliError("root must be an existing directory")
+ _reject_symlink_components(root)
+ return root
+
+
+def _within_root(candidate: Path, root: Path) -> None:
+ try:
+ candidate.relative_to(root)
+ except ValueError as exc:
+ raise CliError("path escapes the declared root directory") from exc
+
+
+def _suffix_matches(path: Path, suffixes: Iterable[str]) -> bool:
+ name = path.name.lower()
+ return any(name.endswith(suffix.lower()) for suffix in suffixes)
+
+
+def checked_input_file(
+ value: str | os.PathLike[str],
+ *,
+ root: str | os.PathLike[str] = ".",
+ suffixes: Iterable[str] | None = None,
+ max_bytes: int,
+) -> Path:
+ """Return a bounded regular local file within root, rejecting symlinks."""
+
+ raw = os.fspath(value)
+ _reject_url(raw)
+ root_path = checked_root(root)
+ path = Path(raw).expanduser()
+ if not path.is_absolute():
+ path = root_path / path
+ path = _absolute_lexical(path)
+ if path.is_symlink():
+ raise CliError(f"input must not be a symlink: {path.name!r}")
+ try:
+ resolved = path.resolve(strict=True)
+ info = resolved.stat()
+ except OSError as exc:
+ raise CliError(f"cannot access input file {path.name!r}: {exc}") from exc
+ _within_root(resolved, root_path)
+ _reject_symlink_components(resolved)
+ if not stat.S_ISREG(info.st_mode):
+ raise CliError(f"input is not a regular file: {path.name!r}")
+ if info.st_size > max_bytes:
+ raise CliError(
+ f"input {path.name!r} is {info.st_size} bytes; limit is {max_bytes}"
+ )
+ if suffixes is not None and not _suffix_matches(path, suffixes):
+ allowed = ", ".join(sorted({suffix.lower() for suffix in suffixes}))
+ raise CliError(f"input suffix must be one of: {allowed}")
+ return resolved
+
+
+def checked_output_file(
+ value: str | os.PathLike[str],
+ *,
+ root: str | os.PathLike[str] = ".",
+ suffixes: Iterable[str],
+ force: bool = False,
+) -> Path:
+ """Return a local output path within root without following symlinks."""
+
+ raw = os.fspath(value)
+ _reject_url(raw)
+ root_path = checked_root(root)
+ path = Path(raw).expanduser()
+ if not path.is_absolute():
+ path = root_path / path
+ path = _absolute_lexical(path)
+ if path.name in {"", ".", ".."}:
+ raise CliError("output must name a file")
+ if not _suffix_matches(path, suffixes):
+ allowed = ", ".join(sorted({suffix.lower() for suffix in suffixes}))
+ raise CliError(f"output suffix must be one of: {allowed}")
+ if path.is_symlink():
+ raise CliError(f"output must not be a symlink: {path.name!r}")
+ if path.parent.is_symlink():
+ raise CliError("output parent must not be a symlink")
+ try:
+ resolved_parent = path.parent.resolve(strict=True)
+ parent_info = resolved_parent.stat()
+ except OSError as exc:
+ raise CliError(f"cannot access output parent: {exc}") from exc
+ _within_root(resolved_parent, root_path)
+ _reject_symlink_components(resolved_parent)
+ path = resolved_parent / path.name
+ if not stat.S_ISDIR(parent_info.st_mode):
+ raise CliError("output parent must be an existing directory")
+ if path.exists():
+ if not path.is_file():
+ raise CliError("output exists and is not a regular file")
+ if not force:
+ raise CliError(f"refusing to overwrite existing output: {path.name!r}")
+ return path
+
+
+def strict_json_bytes(document: Any) -> bytes:
+ """Serialize deterministic RFC-compatible JSON with a size cap."""
+
+ try:
+ payload = (
+ json.dumps(
+ document,
+ indent=2,
+ sort_keys=True,
+ ensure_ascii=False,
+ allow_nan=False,
+ )
+ + "\n"
+ ).encode("utf-8")
+ except (TypeError, ValueError) as exc:
+ raise CliError(f"report is not strict JSON: {exc}") from exc
+ if len(payload) > MAX_REPORT_BYTES:
+ raise CliError(
+ f"report is {len(payload)} bytes; limit is {MAX_REPORT_BYTES}"
+ )
+ return payload
+
+
+def atomic_write_bytes(
+ destination: Path,
+ payload: bytes,
+ *,
+ root: str | os.PathLike[str] = ".",
+ suffixes: Iterable[str],
+ force: bool = False,
+) -> Path:
+ """Atomically write a private file in an existing local directory."""
+
+ destination = checked_output_file(
+ destination, root=root, suffixes=suffixes, force=force
+ )
+ descriptor, temporary_name = tempfile.mkstemp(
+ prefix=f".{destination.name}.", suffix=".tmp", dir=destination.parent
+ )
+ temporary = Path(temporary_name)
+ try:
+ with os.fdopen(descriptor, "wb") as handle:
+ handle.write(payload)
+ handle.flush()
+ os.fsync(handle.fileno())
+ os.chmod(temporary, 0o600)
+ if destination.exists() and not force:
+ raise CliError(f"refusing to overwrite existing output: {destination.name!r}")
+ os.replace(temporary, destination)
+ finally:
+ temporary.unlink(missing_ok=True)
+ return destination
+
+
+def emit_json(
+ document: Any,
+ *,
+ output: str | os.PathLike[str] | None = None,
+ root: str | os.PathLike[str] = ".",
+ force: bool = False,
+) -> None:
+ """Print strict JSON or atomically write it with private permissions."""
+
+ payload = strict_json_bytes(document)
+ if output is None:
+ print(payload.decode("utf-8"), end="")
+ return
+ atomic_write_bytes(
+ Path(output),
+ payload,
+ root=root,
+ suffixes={".json"},
+ force=force,
+ )
+
+
+def load_json_object(
+ value: str | os.PathLike[str],
+ *,
+ root: str | os.PathLike[str] = ".",
+ max_bytes: int = MAX_JSON_BYTES,
+) -> dict[str, Any]:
+ """Load a bounded strict JSON object from a local regular file."""
+
+ path = checked_input_file(
+ value,
+ root=root,
+ suffixes={".json"},
+ max_bytes=max_bytes,
+ )
+ try:
+ with path.open("r", encoding="utf-8") as handle:
+ document = json.load(
+ handle,
+ parse_constant=_reject_constant,
+ object_pairs_hook=_unique_object,
+ )
+ except CliError:
+ raise
+ except (OSError, UnicodeError, json.JSONDecodeError) as exc:
+ raise CliError(f"cannot read valid JSON from {path.name!r}: {exc}") from exc
+ if not isinstance(document, dict):
+ raise CliError("JSON root must be an object")
+ return document
+
+
+def validate_keys(
+ value: Mapping[str, Any],
+ *,
+ allowed: Iterable[str],
+ required: Iterable[str] = (),
+ context: str,
+) -> None:
+ """Reject unknown keys and report required keys."""
+
+ allowed_set = set(allowed)
+ required_set = set(required)
+ unknown = sorted(set(value) - allowed_set)
+ missing = sorted(required_set - set(value))
+ if unknown:
+ raise CliError(f"{context} has unknown keys: {', '.join(unknown)}")
+ if missing:
+ raise CliError(f"{context} is missing keys: {', '.join(missing)}")
+
+
+def bounded_int(
+ value: Any,
+ *,
+ name: str,
+ minimum: int,
+ maximum: int,
+) -> int:
+ """Validate an integer, excluding booleans."""
+
+ if isinstance(value, bool) or not isinstance(value, int):
+ raise CliError(f"{name} must be an integer")
+ if not minimum <= value <= maximum:
+ raise CliError(f"{name} must be between {minimum} and {maximum}")
+ return value
+
+
+def finite_float(
+ value: Any,
+ *,
+ name: str,
+ minimum: float | None = None,
+ maximum: float | None = None,
+) -> float:
+ """Validate a finite real number, excluding booleans."""
+
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
+ raise CliError(f"{name} must be numeric")
+ number = float(value)
+ if not math.isfinite(number):
+ raise CliError(f"{name} must be finite")
+ if minimum is not None and number < minimum:
+ raise CliError(f"{name} must be at least {minimum}")
+ if maximum is not None and number > maximum:
+ raise CliError(f"{name} must be at most {maximum}")
+ return number
+
+
+def parse_name_list(value: str | None, *, name: str) -> list[str]:
+ """Parse a comma-separated list without empty or duplicate names."""
+
+ if value is None:
+ return []
+ names = [item.strip() for item in value.split(",")]
+ if not names or any(not item for item in names):
+ raise CliError(f"{name} must be a comma-separated list of nonempty names")
+ if len(names) != len(set(names)):
+ raise CliError(f"{name} must not contain duplicates")
+ return names
+
+
+def sha256_file(path: Path, *, max_bytes: int) -> str:
+ """Hash a bounded regular file using fixed-size streaming reads."""
+
+ size = path.stat().st_size
+ if size > max_bytes:
+ raise CliError(f"file is {size} bytes; hashing limit is {max_bytes}")
+ digest = hashlib.sha256()
+ with path.open("rb") as handle:
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
+ digest.update(chunk)
+ return digest.hexdigest()
+
+
+def run_cli(function: Any) -> int:
+ """Run a CLI body with concise expected-error handling."""
+
+ try:
+ function()
+ except CliError as exc:
+ print(f"error: {exc}", file=os.sys.stderr)
+ return 2
+ except KeyboardInterrupt:
+ print("error: interrupted", file=os.sys.stderr)
+ return 130
+ return 0
diff --git a/skills/pathml/scripts/image_qc.py b/skills/pathml/scripts/image_qc.py
new file mode 100644
index 00000000..8ca6e03b
--- /dev/null
+++ b/skills/pathml/scripts/image_qc.py
@@ -0,0 +1,325 @@
+#!/usr/bin/env python3
+"""Compute bounded synthetic/local image QC and a coarse tissue-like mask."""
+
+from __future__ import annotations
+
+import argparse
+import math
+from pathlib import Path
+from typing import Any
+
+from _common import (
+ CliError,
+ MAX_IMAGE_BYTES,
+ MAX_PIXELS,
+ atomic_write_bytes,
+ checked_input_file,
+ checked_root,
+ emit_json,
+ run_cli,
+)
+
+
+IMAGE_SUFFIXES = {".ppm", ".pgm", ".png", ".jpg", ".jpeg", ".tif", ".tiff"}
+WHITESPACE = b" \t\r\n\f\v"
+
+
+def _next_token(payload: bytes, offset: int) -> tuple[bytes, int]:
+ length = len(payload)
+ while offset < length:
+ if payload[offset] in WHITESPACE:
+ offset += 1
+ continue
+ if payload[offset] == ord("#"):
+ newline = payload.find(b"\n", offset)
+ if newline < 0:
+ raise CliError("unterminated PNM comment")
+ offset = newline + 1
+ continue
+ break
+ start = offset
+ while offset < length and payload[offset] not in WHITESPACE:
+ if payload[offset] == ord("#"):
+ break
+ offset += 1
+ if start == offset:
+ raise CliError("invalid PNM header")
+ return payload[start:offset], offset
+
+
+def _read_pnm(path: Path, max_pixels: int) -> tuple[int, int, bytes]:
+ payload = path.read_bytes()
+ magic, offset = _next_token(payload, 0)
+ width_token, offset = _next_token(payload, offset)
+ height_token, offset = _next_token(payload, offset)
+ maxval_token, offset = _next_token(payload, offset)
+ if magic not in {b"P5", b"P6"}:
+ raise CliError("only binary P5/P6 PNM images are supported without Pillow")
+ try:
+ width = int(width_token)
+ height = int(height_token)
+ maxval = int(maxval_token)
+ except ValueError as exc:
+ raise CliError("PNM dimensions and max value must be integers") from exc
+ if width <= 0 or height <= 0 or width * height > max_pixels:
+ raise CliError(f"PNM pixel count must be in [1, {max_pixels}]")
+ if not 1 <= maxval <= 255:
+ raise CliError("PNM max value must be between 1 and 255")
+ if offset >= len(payload) or payload[offset] not in WHITESPACE:
+ raise CliError("PNM header must end with whitespace")
+ if payload[offset : offset + 2] == b"\r\n":
+ offset += 2
+ else:
+ offset += 1
+ channels = 3 if magic == b"P6" else 1
+ expected = width * height * channels
+ pixels = payload[offset:]
+ if len(pixels) != expected:
+ raise CliError(
+ f"PNM pixel payload is {len(pixels)} bytes; expected {expected}"
+ )
+ if maxval != 255:
+ pixels = bytes(round(value * 255 / maxval) for value in pixels)
+ if channels == 1:
+ rgb = bytearray(width * height * 3)
+ for index, value in enumerate(pixels):
+ start = index * 3
+ rgb[start : start + 3] = bytes((value, value, value))
+ pixels = bytes(rgb)
+ return width, height, pixels
+
+
+def _read_with_pillow(path: Path, max_pixels: int) -> tuple[int, int, bytes]:
+ try:
+ from PIL import Image
+ except ModuleNotFoundError as exc:
+ raise CliError(
+ "Pillow is required for PNG/JPEG/TIFF input; use a P5/P6 PNM "
+ "file for dependency-free inspection"
+ ) from exc
+ Image.MAX_IMAGE_PIXELS = max_pixels
+ try:
+ with Image.open(path) as image:
+ width, height = image.size
+ if width <= 0 or height <= 0 or width * height > max_pixels:
+ raise CliError(f"image pixel count must be in [1, {max_pixels}]")
+ rgb = image.convert("RGB")
+ return int(width), int(height), rgb.tobytes()
+ except CliError:
+ raise
+ except Exception as exc:
+ raise CliError(f"cannot decode bounded image: {exc}") from exc
+
+
+def read_image(path: Path, max_pixels: int) -> tuple[int, int, bytes]:
+ """Read a bounded RGB image with PNM support in the standard library."""
+
+ if path.suffix.lower() in {".ppm", ".pgm"}:
+ return _read_pnm(path, max_pixels)
+ return _read_with_pillow(path, max_pixels)
+
+
+def synthetic_image(
+ width: int,
+ height: int,
+ tissue_fraction: float,
+) -> bytes:
+ """Create a deterministic white image with a centered pink tissue region."""
+
+ if width <= 0 or height <= 0 or width * height > MAX_PIXELS:
+ raise CliError(f"synthetic pixel count must be in [1, {MAX_PIXELS}]")
+ if not math.isfinite(tissue_fraction) or not 0 <= tissue_fraction <= 1:
+ raise CliError("--tissue-fraction must be finite and in [0, 1]")
+ pixels = bytearray(bytes((245, 245, 245)) * (width * height))
+ scale = math.sqrt(tissue_fraction)
+ tissue_width = min(width, round(width * scale))
+ tissue_height = min(height, round(height * scale))
+ left = (width - tissue_width) // 2
+ top = (height - tissue_height) // 2
+ for row in range(top, top + tissue_height):
+ for column in range(left, left + tissue_width):
+ offset = (row * width + column) * 3
+ pixels[offset : offset + 3] = bytes((180, 75, 135))
+ return bytes(pixels)
+
+
+def calculate_qc(
+ width: int,
+ height: int,
+ pixels: bytes,
+ *,
+ saturation_threshold: float,
+ brightness_threshold: float,
+) -> tuple[dict[str, Any], bytes]:
+ """Calculate simple bounded QC metrics and an 8-bit binary mask."""
+
+ if len(pixels) != width * height * 3:
+ raise CliError("RGB payload length does not match dimensions")
+ if not math.isfinite(saturation_threshold) or not (
+ 0 <= saturation_threshold <= 1
+ ):
+ raise CliError("--saturation-threshold must be finite and in [0, 1]")
+ if not math.isfinite(brightness_threshold) or not (
+ 0 <= brightness_threshold <= 1
+ ):
+ raise CliError("--brightness-threshold must be finite and in [0, 1]")
+
+ count = width * height
+ sums = [0, 0, 0]
+ tissue = 0
+ white = 0
+ dark = 0
+ saturated_channel = 0
+ mask = bytearray(count)
+ for pixel_index in range(count):
+ offset = pixel_index * 3
+ red, green, blue = pixels[offset : offset + 3]
+ sums[0] += red
+ sums[1] += green
+ sums[2] += blue
+ high = max(red, green, blue)
+ low = min(red, green, blue)
+ brightness = high / 255.0
+ saturation = 0.0 if high == 0 else (high - low) / high
+ is_tissue = (
+ saturation >= saturation_threshold
+ and brightness <= brightness_threshold
+ )
+ if is_tissue:
+ tissue += 1
+ mask[pixel_index] = 255
+ if brightness >= 0.90 and saturation <= 0.10:
+ white += 1
+ if brightness <= 0.15:
+ dark += 1
+ if high == 255:
+ saturated_channel += 1
+
+ report = {
+ "width": width,
+ "height": height,
+ "pixel_count": count,
+ "mean_rgb": [round(total / count, 6) for total in sums],
+ "tissue_like_fraction": round(tissue / count, 8),
+ "white_like_fraction": round(white / count, 8),
+ "dark_fraction": round(dark / count, 8),
+ "any_channel_clipped_high_fraction": round(saturated_channel / count, 8),
+ "mask_rule": {
+ "minimum_saturation": saturation_threshold,
+ "maximum_brightness": brightness_threshold,
+ },
+ "clinical_use": False,
+ "note": (
+ "This coarse RGB heuristic is for synthetic/pilot QC only; it is not "
+ "PathML TissueDetectionHE and is not a diagnostic quality decision."
+ ),
+ }
+ return report, bytes(mask)
+
+
+def _write_mask(
+ mask: bytes,
+ width: int,
+ height: int,
+ *,
+ destination: str,
+ root: str,
+ force: bool,
+) -> None:
+ header = f"P5\n{width} {height}\n255\n".encode("ascii")
+ atomic_write_bytes(
+ Path(destination),
+ header + mask,
+ root=root,
+ suffixes={".pgm"},
+ force=force,
+ )
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(
+ description=(
+ "Compute bounded synthetic/local RGB QC and a coarse tissue-like "
+ "mask. No network access."
+ )
+ )
+ subparsers = parser.add_subparsers(dest="command", required=True)
+
+ synthetic = subparsers.add_parser(
+ "synthetic", help="generate an in-memory synthetic image and report QC"
+ )
+ synthetic.add_argument("--width", type=int, default=256)
+ synthetic.add_argument("--height", type=int, default=256)
+ synthetic.add_argument("--tissue-fraction", type=float, default=0.5)
+ synthetic.add_argument("--saturation-threshold", type=float, default=0.15)
+ synthetic.add_argument("--brightness-threshold", type=float, default=0.95)
+ synthetic.add_argument("--mask-output")
+ synthetic.add_argument("--output")
+ synthetic.add_argument("--root", default=".")
+ synthetic.add_argument("--force", action="store_true")
+
+ inspect = subparsers.add_parser(
+ "inspect", help="inspect a bounded local raster or P5/P6 PNM image"
+ )
+ inspect.add_argument("--image", required=True)
+ inspect.add_argument("--root", default=".")
+ inspect.add_argument("--max-pixels", type=int, default=MAX_PIXELS)
+ inspect.add_argument("--max-image-bytes", type=int, default=MAX_IMAGE_BYTES)
+ inspect.add_argument("--saturation-threshold", type=float, default=0.15)
+ inspect.add_argument("--brightness-threshold", type=float, default=0.95)
+ inspect.add_argument("--mask-output")
+ inspect.add_argument("--output")
+ inspect.add_argument("--force", action="store_true")
+ return parser
+
+
+def main() -> None:
+ args = build_parser().parse_args()
+ root = checked_root(args.root)
+ if args.command == "synthetic":
+ width = args.width
+ height = args.height
+ pixels = synthetic_image(width, height, args.tissue_fraction)
+ source = "synthetic"
+ else:
+ if not 1 <= args.max_pixels <= 100_000_000:
+ raise CliError("--max-pixels must be between 1 and 100000000")
+ if not 1 <= args.max_image_bytes <= MAX_IMAGE_BYTES:
+ raise CliError(
+ f"--max-image-bytes must be between 1 and {MAX_IMAGE_BYTES}"
+ )
+ image = checked_input_file(
+ args.image,
+ root=root,
+ suffixes=IMAGE_SUFFIXES,
+ max_bytes=args.max_image_bytes,
+ )
+ width, height, pixels = read_image(image, args.max_pixels)
+ source = "local_file"
+
+ report, mask = calculate_qc(
+ width,
+ height,
+ pixels,
+ saturation_threshold=args.saturation_threshold,
+ brightness_threshold=args.brightness_threshold,
+ )
+ report["source"] = source
+ report["path_redacted"] = True
+ if args.mask_output:
+ _write_mask(
+ mask,
+ width,
+ height,
+ destination=args.mask_output,
+ root=str(root),
+ force=args.force,
+ )
+ report["mask_written"] = True
+ else:
+ report["mask_written"] = False
+ emit_json(report, output=args.output, root=root, force=args.force)
+
+
+if __name__ == "__main__":
+ raise SystemExit(run_cli(main))
diff --git a/skills/pathml/scripts/plan_inference.py b/skills/pathml/scripts/plan_inference.py
new file mode 100644
index 00000000..4fd1a00a
--- /dev/null
+++ b/skills/pathml/scripts/plan_inference.py
@@ -0,0 +1,282 @@
+#!/usr/bin/env python3
+"""Plan bounded inference batches from numbers or a JSON model card only."""
+
+from __future__ import annotations
+
+import argparse
+import math
+import re
+from pathlib import Path
+from typing import Any
+
+from _common import (
+ CliError,
+ MAX_JSON_BYTES,
+ emit_json,
+ finite_float,
+ load_json_object,
+ run_cli,
+ validate_keys,
+)
+
+
+DTYPE_BYTES = {
+ "uint8": 1,
+ "int8": 1,
+ "float16": 2,
+ "bfloat16": 2,
+ "float32": 4,
+ "float64": 8,
+}
+MODEL_SUFFIXES = {
+ ".bin",
+ ".ckpt",
+ ".joblib",
+ ".onnx",
+ ".pickle",
+ ".pkl",
+ ".pt",
+ ".pth",
+ ".safetensors",
+}
+SHA256_PATTERN = re.compile(r"^[0-9a-fA-F]{64}$")
+
+
+def _load_card(path: str | None, root: str) -> dict[str, Any]:
+ if path is None:
+ return {}
+ if Path(path).suffix.lower() in MODEL_SUFFIXES:
+ raise CliError(
+ "--model-card accepts JSON metadata only; model/checkpoint files "
+ "are intentionally never loaded"
+ )
+ card = load_json_object(path, root=root, max_bytes=MAX_JSON_BYTES)
+ validate_keys(
+ card,
+ allowed={
+ "schema_version",
+ "model_id",
+ "artifact_sha256",
+ "input_shape",
+ "dtype",
+ "output_elements_per_tile",
+ "activation_multiplier",
+ "parameter_bytes",
+ "runtime_workspace_mib",
+ },
+ required={"schema_version", "model_id", "input_shape", "dtype"},
+ context="model card",
+ )
+ if card["schema_version"] != "1.0":
+ raise CliError("model card schema_version must be '1.0'")
+ if not isinstance(card["model_id"], str) or not 1 <= len(card["model_id"]) <= 128:
+ raise CliError("model_id must be a nonempty string of at most 128 characters")
+ digest = card.get("artifact_sha256")
+ if digest is not None and (
+ not isinstance(digest, str) or not SHA256_PATTERN.fullmatch(digest)
+ ):
+ raise CliError("artifact_sha256 must be exactly 64 hexadecimal characters")
+ shape = card["input_shape"]
+ if (
+ not isinstance(shape, list)
+ or len(shape) != 3
+ or any(isinstance(value, bool) or not isinstance(value, int) for value in shape)
+ ):
+ raise CliError("input_shape must be [channels, height, width] integers")
+ return card
+
+
+def _select(cli_value: Any, card: dict[str, Any], card_key: str, default: Any) -> Any:
+ return cli_value if cli_value is not None else card.get(card_key, default)
+
+
+def make_plan(args: argparse.Namespace) -> dict[str, Any]:
+ card = _load_card(args.model_card, args.root)
+ shape = card.get("input_shape", [3, 256, 256])
+ channels = _select(args.channels, card, "channels", shape[0])
+ height = _select(args.height, card, "height", shape[1])
+ width = _select(args.width, card, "width", shape[2])
+ dtype = _select(args.dtype, card, "dtype", "float32")
+ output_elements = _select(
+ args.output_elements_per_tile,
+ card,
+ "output_elements_per_tile",
+ 0,
+ )
+ activation_multiplier = _select(
+ args.activation_multiplier,
+ card,
+ "activation_multiplier",
+ 8.0,
+ )
+ parameter_bytes = _select(
+ args.parameter_bytes,
+ card,
+ "parameter_bytes",
+ 0,
+ )
+ runtime_workspace_mib = _select(
+ args.runtime_workspace_mib,
+ card,
+ "runtime_workspace_mib",
+ 512.0,
+ )
+
+ integers = {
+ "tile_count": (args.tile_count, 1, 100_000_000),
+ "batch_size": (args.batch_size, 1, 1_000_000),
+ "channels": (channels, 1, 4096),
+ "height": (height, 1, 16384),
+ "width": (width, 1, 16384),
+ "output_elements_per_tile": (output_elements, 0, 10_000_000_000),
+ "parameter_bytes": (parameter_bytes, 0, 10_000_000_000_000),
+ }
+ checked: dict[str, int] = {}
+ for name, (value, minimum, maximum) in integers.items():
+ if isinstance(value, bool) or not isinstance(value, int):
+ raise CliError(f"{name} must be an integer")
+ if not minimum <= value <= maximum:
+ raise CliError(f"{name} must be between {minimum} and {maximum}")
+ checked[name] = value
+ if dtype not in DTYPE_BYTES:
+ raise CliError(
+ "--dtype must be one of: " + ", ".join(sorted(DTYPE_BYTES))
+ )
+ activation_multiplier = finite_float(
+ activation_multiplier,
+ name="activation_multiplier",
+ minimum=0,
+ maximum=10_000,
+ )
+ runtime_workspace_mib = finite_float(
+ runtime_workspace_mib,
+ name="runtime_workspace_mib",
+ minimum=0,
+ maximum=1_000_000,
+ )
+ max_memory_mib = finite_float(
+ args.max_memory_mib,
+ name="max_memory_mib",
+ minimum=1,
+ maximum=10_000_000,
+ )
+
+ bytes_per_element = DTYPE_BYTES[dtype]
+ input_elements = checked["channels"] * checked["height"] * checked["width"]
+ input_bytes_per_tile = input_elements * bytes_per_element
+ output_bytes_per_tile = (
+ checked["output_elements_per_tile"] * bytes_per_element
+ )
+ activation_bytes_per_tile = math.ceil(
+ input_bytes_per_tile * activation_multiplier
+ )
+ variable_bytes_per_tile = (
+ input_bytes_per_tile + output_bytes_per_tile + activation_bytes_per_tile
+ )
+ persistent_bytes = checked["parameter_bytes"] + round(
+ runtime_workspace_mib * 1024**2
+ )
+ memory_budget_bytes = round(max_memory_mib * 1024**2)
+ available_variable_bytes = max(0, memory_budget_bytes - persistent_bytes)
+ recommended_max_batch = (
+ available_variable_bytes // variable_bytes_per_tile
+ if variable_bytes_per_tile
+ else checked["tile_count"]
+ )
+ recommended_max_batch = min(recommended_max_batch, checked["tile_count"])
+ planned_peak_bytes = persistent_bytes + (
+ variable_bytes_per_tile * checked["batch_size"]
+ )
+ within_memory = planned_peak_bytes <= memory_budget_bytes
+ number_of_batches = math.ceil(
+ checked["tile_count"] / checked["batch_size"]
+ )
+ final_batch_size = checked["tile_count"] % checked["batch_size"]
+ if final_batch_size == 0:
+ final_batch_size = min(checked["batch_size"], checked["tile_count"])
+
+ warnings = [
+ "Estimate excludes allocator fragmentation, framework caches, graph "
+ "workspace, postprocessing, stitching, and concurrent workers."
+ ]
+ if not within_memory:
+ warnings.append(
+ "Requested batch exceeds the planning memory budget; reduce batch "
+ "size or change the explicit budget."
+ )
+ if checked["output_elements_per_tile"] == 0:
+ warnings.append(
+ "No output tensor size was supplied; output memory is omitted."
+ )
+ if checked["parameter_bytes"] == 0:
+ warnings.append("No parameter size was supplied; model weights are omitted.")
+
+ return {
+ "model_card_used": bool(card),
+ "model_id": card.get("model_id"),
+ "artifact_sha256": card.get("artifact_sha256"),
+ "checkpoint_or_model_loaded": False,
+ "input_shape_chw": [
+ checked["channels"],
+ checked["height"],
+ checked["width"],
+ ],
+ "dtype": dtype,
+ "bytes_per_element": bytes_per_element,
+ "tile_count": checked["tile_count"],
+ "requested_batch_size": checked["batch_size"],
+ "number_of_batches": number_of_batches,
+ "final_batch_size": final_batch_size,
+ "input_bytes_per_tile": input_bytes_per_tile,
+ "output_bytes_per_tile": output_bytes_per_tile,
+ "activation_bytes_per_tile_estimate": activation_bytes_per_tile,
+ "persistent_bytes_estimate": persistent_bytes,
+ "planned_peak_memory_mib": round(planned_peak_bytes / 1024**2, 6),
+ "memory_budget_mib": max_memory_mib,
+ "within_memory_budget": within_memory,
+ "recommended_max_batch_under_estimate": int(recommended_max_batch),
+ "estimated_total_output_gib": round(
+ checked["tile_count"] * output_bytes_per_tile / 1024**3,
+ 6,
+ ),
+ "warnings": warnings,
+ "note": (
+ "This planner reads numbers or strict JSON metadata only. It never "
+ "opens model/checkpoint artifacts or imports PathML/Torch/ONNX."
+ ),
+ }
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(
+ description=(
+ "Plan bounded inference batches from dimensions or a strict JSON "
+ "model card. Model/checkpoint files are never loaded."
+ )
+ )
+ parser.add_argument("--tile-count", type=int, required=True)
+ parser.add_argument("--batch-size", type=int, required=True)
+ parser.add_argument("--model-card")
+ parser.add_argument("--root", default=".")
+ parser.add_argument("--channels", type=int)
+ parser.add_argument("--height", type=int)
+ parser.add_argument("--width", type=int)
+ parser.add_argument("--dtype", choices=sorted(DTYPE_BYTES))
+ parser.add_argument("--output-elements-per-tile", type=int)
+ parser.add_argument("--activation-multiplier", type=float)
+ parser.add_argument("--parameter-bytes", type=int)
+ parser.add_argument("--runtime-workspace-mib", type=float)
+ parser.add_argument("--max-memory-mib", type=float, default=4096.0)
+ parser.add_argument("--output")
+ parser.add_argument("--force", action="store_true")
+ return parser
+
+
+def main() -> None:
+ args = build_parser().parse_args()
+ report = make_plan(args)
+ emit_json(report, output=args.output, root=args.root, force=args.force)
+
+
+if __name__ == "__main__":
+ raise SystemExit(run_cli(main))
diff --git a/skills/pathml/scripts/plan_pipeline.py b/skills/pathml/scripts/plan_pipeline.py
new file mode 100644
index 00000000..c02be4e0
--- /dev/null
+++ b/skills/pathml/scripts/plan_pipeline.py
@@ -0,0 +1,239 @@
+#!/usr/bin/env python3
+"""Plan bounded PathML tiling and pipeline work without opening a slide."""
+
+from __future__ import annotations
+
+import argparse
+import math
+from typing import Any
+
+from _common import CliError, emit_json, parse_name_list, run_cli
+
+
+TRANSFORM_KINDS = {
+ "AdaptiveHistogramEqualization": "image",
+ "BinaryThreshold": "mask",
+ "BoxBlur": "image",
+ "CollapseRunsCODEX": "image",
+ "CollapseRunsVectra": "image",
+ "ForegroundDetection": "mask",
+ "GaussianBlur": "image",
+ "HistogramEqualization": "image",
+ "LabelArtifactTileHE": "label",
+ "LabelWhiteSpaceHE": "label",
+ "MedianBlur": "image",
+ "MorphClose": "mask",
+ "MorphOpen": "mask",
+ "NucleusDetectionHE": "mask",
+ "QuantifyMIF": "counts",
+ "RescaleIntensity": "image",
+ "SegmentMIF": "two_instance_masks_deprecated",
+ "SegmentMIFRemote": "two_instance_masks_network_download",
+ "StainNormalizationHE": "image",
+ "SuperpixelInterpolation": "image",
+ "TissueDetectionHE": "mask",
+}
+
+
+def _stable_pathml_count(
+ dimension: int,
+ tile_extent: int,
+ stride: int,
+ pad: bool,
+) -> int:
+ """Match PathML 3.0.5 OpenSlide/Bio-Formats tile-count arithmetic."""
+
+ if pad and dimension % stride != 0:
+ return dimension // stride + 1
+ if dimension < tile_extent:
+ return 0
+ return (dimension - tile_extent) // stride + 1
+
+
+def _parse_pipeline(value: str | None) -> list[str]:
+ stages = parse_name_list(value, name="--pipeline")
+ unknown = sorted(set(stages) - set(TRANSFORM_KINDS))
+ if unknown:
+ raise CliError(
+ "unknown PathML 3.0.5 transform names: " + ", ".join(unknown)
+ )
+ return stages
+
+
+def make_plan(args: argparse.Namespace) -> dict[str, Any]:
+ if not 1 <= args.width <= 1_000_000_000:
+ raise CliError("--width must be between 1 and 1000000000")
+ if not 1 <= args.height <= 1_000_000_000:
+ raise CliError("--height must be between 1 and 1000000000")
+ if not 1 <= args.tile_size <= 8192:
+ raise CliError("--tile-size must be between 1 and 8192")
+ if not 1 <= args.stride <= 8192:
+ raise CliError("--stride must be between 1 and 8192")
+ if not math.isfinite(args.level_downsample) or not (
+ 1.0 <= args.level_downsample <= 1_000_000.0
+ ):
+ raise CliError("--level-downsample must be finite and in [1, 1000000]")
+ if not 1 <= args.channels <= 4096:
+ raise CliError("--channels must be between 1 and 4096")
+ if args.bytes_per_channel not in {1, 2, 4, 8}:
+ raise CliError("--bytes-per-channel must be one of 1, 2, 4, or 8")
+ if not 1 <= args.max_tiles <= 100_000_000:
+ raise CliError("--max-tiles must be between 1 and 100000000")
+ if not math.isfinite(args.max_output_gib) or not (
+ 0 < args.max_output_gib <= 1_000_000
+ ):
+ raise CliError("--max-output-gib must be finite and positive")
+ if args.mpp_x is not None and (
+ not math.isfinite(args.mpp_x) or not 0 < args.mpp_x <= 1000
+ ):
+ raise CliError("--mpp-x must be finite and in (0, 1000]")
+ if args.mpp_y is not None and (
+ not math.isfinite(args.mpp_y) or not 0 < args.mpp_y <= 1000
+ ):
+ raise CliError("--mpp-y must be finite and in (0, 1000]")
+
+ stages = _parse_pipeline(args.pipeline)
+ level_width = math.ceil(args.width / args.level_downsample)
+ level_height = math.ceil(args.height / args.level_downsample)
+ tiles_i = _stable_pathml_count(
+ level_height, args.tile_size, args.stride, args.pad
+ )
+ tiles_j = _stable_pathml_count(
+ level_width, args.tile_size, args.stride, args.pad
+ )
+ tile_count = tiles_i * tiles_j
+ if tile_count > args.max_tiles:
+ raise CliError(
+ f"planned tile count {tile_count} exceeds --max-tiles={args.max_tiles}"
+ )
+
+ image_bytes_per_tile = (
+ args.tile_size
+ * args.tile_size
+ * args.channels
+ * args.bytes_per_channel
+ )
+ mask_outputs = sum(
+ 2 if TRANSFORM_KINDS[stage].startswith("two_instance_masks") else 1
+ for stage in stages
+ if TRANSFORM_KINDS[stage] in {"mask", "two_instance_masks_deprecated",
+ "two_instance_masks_network_download"}
+ )
+ label_outputs = sum(
+ TRANSFORM_KINDS[stage] == "label" for stage in stages
+ )
+ count_outputs = sum(
+ TRANSFORM_KINDS[stage] == "counts" for stage in stages
+ )
+ mask_bytes_per_tile = args.tile_size * args.tile_size * mask_outputs
+ estimated_payload_bytes = tile_count * (
+ image_bytes_per_tile + mask_bytes_per_tile
+ )
+ estimated_payload_gib = estimated_payload_bytes / 1024**3
+ if estimated_payload_gib > args.max_output_gib:
+ raise CliError(
+ f"estimated uncompressed payload {estimated_payload_gib:.3f} GiB "
+ f"exceeds --max-output-gib={args.max_output_gib}"
+ )
+
+ overlap = max(0, args.tile_size - args.stride)
+ gap = max(0, args.stride - args.tile_size)
+ warnings: list[str] = []
+ if args.pad:
+ warnings.append(
+ "PathML 3.0.5 padding uses backend-specific count arithmetic and "
+ "zero-filled edges; verify a synthetic case."
+ )
+ if overlap:
+ warnings.append(
+ "Overlapping tiles duplicate pixels/objects; define stitching and "
+ "deduplication before counting."
+ )
+ if gap:
+ warnings.append("Stride exceeds tile size, leaving unprocessed gaps.")
+ if "SegmentMIF" in stages:
+ warnings.append("SegmentMIF is deprecated and needs a separate DeepCell stack.")
+ if "SegmentMIFRemote" in stages:
+ warnings.append(
+ "SegmentMIFRemote downloads Mesmer ONNX from Hugging Face at construction; "
+ "explicit network consent is required."
+ )
+ if args.level_downsample != 1:
+ warnings.append(
+ "Area thresholds and morphology kernels are in selected-level pixels."
+ )
+
+ physical_tile_um: list[float] | None = None
+ if args.mpp_x is not None and args.mpp_y is not None:
+ physical_tile_um = [
+ args.tile_size * args.level_downsample * args.mpp_y,
+ args.tile_size * args.level_downsample * args.mpp_x,
+ ]
+
+ return {
+ "pathml_version_modelled": "3.0.5",
+ "input_level0_shape_hw": [args.height, args.width],
+ "level_downsample": args.level_downsample,
+ "planned_level_shape_hw": [level_height, level_width],
+ "tile_size_hw": [args.tile_size, args.tile_size],
+ "stride_ij": [args.stride, args.stride],
+ "pad": args.pad,
+ "tiles_ij": [tiles_i, tiles_j],
+ "tile_count": tile_count,
+ "overlap_pixels_per_axis": overlap,
+ "gap_pixels_per_axis": gap,
+ "pipeline": [
+ {"name": stage, "kind": TRANSFORM_KINDS[stage]} for stage in stages
+ ],
+ "expected_mask_outputs_per_tile": mask_outputs,
+ "expected_label_outputs_per_tile": label_outputs,
+ "expected_count_outputs_per_tile": count_outputs,
+ "input_image_bytes_per_tile": image_bytes_per_tile,
+ "estimated_uncompressed_payload_gib": round(estimated_payload_gib, 6),
+ "physical_tile_size_um_yx": physical_tile_um,
+ "within_bounds": True,
+ "warnings": warnings,
+ "note": (
+ "This is a dry-run estimate. It does not open a slide, import PathML, "
+ "measure compression, or predict transform/model workspace memory."
+ ),
+ }
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(
+ description=(
+ "Estimate PathML 3.0.5 tile counts and payload bounds without "
+ "opening a slide or importing PathML."
+ )
+ )
+ parser.add_argument("--width", type=int, required=True, help="level-0 width")
+ parser.add_argument("--height", type=int, required=True, help="level-0 height")
+ parser.add_argument("--level-downsample", type=float, default=1.0)
+ parser.add_argument("--tile-size", type=int, default=256)
+ parser.add_argument("--stride", type=int, default=256)
+ parser.add_argument("--pad", action="store_true")
+ parser.add_argument("--channels", type=int, default=3)
+ parser.add_argument("--bytes-per-channel", type=int, default=1)
+ parser.add_argument(
+ "--pipeline",
+ help="comma-separated stable transform class names in execution order",
+ )
+ parser.add_argument("--mpp-x", type=float)
+ parser.add_argument("--mpp-y", type=float)
+ parser.add_argument("--max-tiles", type=int, default=1_000_000)
+ parser.add_argument("--max-output-gib", type=float, default=1024.0)
+ parser.add_argument("--output")
+ parser.add_argument("--root", default=".")
+ parser.add_argument("--force", action="store_true")
+ return parser
+
+
+def main() -> None:
+ args = build_parser().parse_args()
+ report = make_plan(args)
+ emit_json(report, output=args.output, root=args.root, force=args.force)
+
+
+if __name__ == "__main__":
+ raise SystemExit(run_cli(main))
diff --git a/skills/pathml/scripts/slide_manifest.py b/skills/pathml/scripts/slide_manifest.py
new file mode 100644
index 00000000..aedaa147
--- /dev/null
+++ b/skills/pathml/scripts/slide_manifest.py
@@ -0,0 +1,405 @@
+#!/usr/bin/env python3
+"""Validate local slide manifests and inspect allowlisted technical metadata."""
+
+from __future__ import annotations
+
+import argparse
+import csv
+import math
+import re
+from collections import Counter
+from pathlib import Path
+from typing import Any
+
+from _common import (
+ CliError,
+ MAX_CSV_BYTES,
+ MAX_ROWS,
+ PINNED_INSTALL,
+ checked_input_file,
+ checked_root,
+ emit_json,
+ parse_name_list,
+ run_cli,
+ sha256_file,
+)
+
+
+SLIDE_SUFFIXES = {
+ ".svs",
+ ".tif",
+ ".tiff",
+ ".ome.tif",
+ ".ome.tiff",
+ ".bif",
+ ".ndpi",
+ ".vms",
+ ".vmu",
+ ".scn",
+ ".mrxs",
+ ".svslide",
+ ".qptiff",
+ ".dcm",
+ ".dicom",
+ ".czi",
+ ".vsi",
+ ".zvi",
+ ".h5",
+ ".h5path",
+}
+OPENSLIDE_SUFFIXES = {
+ ".svs",
+ ".tif",
+ ".tiff",
+ ".bif",
+ ".ndpi",
+ ".vms",
+ ".vmu",
+ ".scn",
+ ".mrxs",
+ ".svslide",
+}
+DICOM_SUFFIXES = {".dcm", ".dicom"}
+ID_PATTERN = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$")
+
+
+def _matched_suffix(path: Path) -> str:
+ lowered = path.name.lower()
+ matches = [suffix for suffix in SLIDE_SUFFIXES if lowered.endswith(suffix)]
+ if not matches:
+ raise CliError(f"unsupported slide suffix: {path.suffix.lower() or '<none>'}")
+ return max(matches, key=len)
+
+
+def _validate_identifier(value: str, *, field: str, row_number: int) -> str:
+ clean = value.strip()
+ if not ID_PATTERN.fullmatch(clean):
+ raise CliError(
+ f"row {row_number}: {field} must be a pseudonymous identifier "
+ "using 1-128 letters, digits, dots, underscores, or hyphens"
+ )
+ return clean
+
+
+def validate_manifest(args: argparse.Namespace) -> dict[str, Any]:
+ root = checked_root(args.root)
+ manifest = checked_input_file(
+ args.manifest,
+ root=root,
+ suffixes={".csv"},
+ max_bytes=args.max_manifest_bytes,
+ )
+ allowed_splits = set(parse_name_list(args.splits, name="--splits"))
+ max_slide_bytes = int(args.max_slide_gib * 1024**3)
+
+ slide_ids: set[str] = set()
+ resolved_paths: set[Path] = set()
+ patient_splits: dict[str, str] = {}
+ split_counts: Counter[str] = Counter()
+ suffix_counts: Counter[str] = Counter()
+ patient_ids: set[str] = set()
+
+ try:
+ with manifest.open("r", encoding="utf-8-sig", newline="") as handle:
+ reader = csv.DictReader(handle)
+ headers = reader.fieldnames
+ if headers is None:
+ raise CliError("manifest has no header")
+ normalized_headers = [header.strip() for header in headers]
+ if len(normalized_headers) != len(set(normalized_headers)):
+ raise CliError("manifest header contains duplicate column names")
+ required = {"slide_id", "patient_id", "path"}
+ missing = sorted(required - set(normalized_headers))
+ if missing:
+ raise CliError(
+ f"manifest is missing required columns: {', '.join(missing)}"
+ )
+
+ row_count = 0
+ for row_count, raw_row in enumerate(reader, start=1):
+ if row_count > args.max_rows:
+ raise CliError(f"manifest exceeds --max-rows={args.max_rows}")
+ row_number = row_count + 1
+ row = {
+ key.strip(): (value or "").strip()
+ for key, value in raw_row.items()
+ if key is not None
+ }
+ slide_id = _validate_identifier(
+ row["slide_id"], field="slide_id", row_number=row_number
+ )
+ patient_id = _validate_identifier(
+ row["patient_id"], field="patient_id", row_number=row_number
+ )
+ if slide_id in slide_ids:
+ raise CliError(f"row {row_number}: duplicate slide_id")
+ slide_ids.add(slide_id)
+ patient_ids.add(patient_id)
+
+ path_value = row["path"]
+ if not path_value:
+ raise CliError(f"row {row_number}: path is empty")
+ slide_path = checked_input_file(
+ path_value,
+ root=root,
+ suffixes=SLIDE_SUFFIXES,
+ max_bytes=max_slide_bytes,
+ )
+ if slide_path in resolved_paths:
+ raise CliError(f"row {row_number}: duplicate resolved slide path")
+ resolved_paths.add(slide_path)
+ suffix_counts[_matched_suffix(slide_path)] += 1
+
+ split = row.get("split", "")
+ if split:
+ if allowed_splits and split not in allowed_splits:
+ raise CliError(
+ f"row {row_number}: split must be one of "
+ f"{', '.join(sorted(allowed_splits))}"
+ )
+ previous = patient_splits.setdefault(patient_id, split)
+ if previous != split:
+ raise CliError(
+ f"row {row_number}: patient_id appears in multiple splits: "
+ f"{previous!r} and {split!r}"
+ )
+ split_counts[split] += 1
+
+ if row_count == 0:
+ raise CliError("manifest contains no data rows")
+ except CliError:
+ raise
+ except (OSError, UnicodeError, csv.Error) as exc:
+ raise CliError(f"cannot parse manifest CSV: {exc}") from exc
+
+ return {
+ "command": "validate",
+ "valid": True,
+ "row_count": len(slide_ids),
+ "patient_count": len(patient_ids),
+ "split_counts": dict(sorted(split_counts.items())),
+ "suffix_counts": dict(sorted(suffix_counts.items())),
+ "checks": {
+ "local_regular_files": True,
+ "no_urls": True,
+ "no_symlinks": True,
+ "unique_slide_ids": True,
+ "unique_slide_paths": True,
+ "patient_split_isolation": True,
+ },
+ "privacy_note": (
+ "Identifiers were validated syntactically only; confirm they are "
+ "pseudonyms and keep the linkage key outside the analysis workspace."
+ ),
+ }
+
+
+def _inspect_openslide(path: Path) -> dict[str, Any]:
+ try:
+ import openslide
+ except ModuleNotFoundError as exc:
+ raise CliError(
+ f"technical OpenSlide metadata requires PathML dependencies; {PINNED_INSTALL}"
+ ) from exc
+
+ slide = openslide.OpenSlide(str(path))
+ try:
+ properties = slide.properties
+ technical = {
+ "backend": "openslide",
+ "level_count": int(slide.level_count),
+ "level_dimensions_xy": [
+ [int(width), int(height)] for width, height in slide.level_dimensions
+ ],
+ "level_downsamples": [float(value) for value in slide.level_downsamples],
+ }
+ allowlist = {
+ "openslide.vendor": "vendor",
+ "openslide.objective-power": "objective_power",
+ "openslide.mpp-x": "mpp_x",
+ "openslide.mpp-y": "mpp_y",
+ "openslide.comment": None,
+ }
+ for source, destination in allowlist.items():
+ if destination is not None and source in properties:
+ value: Any = properties[source]
+ if destination in {"objective_power", "mpp_x", "mpp_y"}:
+ try:
+ value = float(value)
+ except (TypeError, ValueError):
+ value = None
+ technical[destination] = value
+ return technical
+ finally:
+ slide.close()
+
+
+def _inspect_dicom(path: Path) -> dict[str, Any]:
+ try:
+ import pydicom
+ except ModuleNotFoundError as exc:
+ raise CliError(
+ f"technical DICOM metadata requires PathML dependencies; {PINNED_INSTALL}"
+ ) from exc
+
+ fields = (
+ "Rows",
+ "Columns",
+ "TotalPixelMatrixRows",
+ "TotalPixelMatrixColumns",
+ "NumberOfFrames",
+ "SamplesPerPixel",
+ "PhotometricInterpretation",
+ "BitsAllocated",
+ )
+ try:
+ dataset = pydicom.dcmread(
+ path,
+ stop_before_pixels=True,
+ specific_tags=list(fields),
+ force=False,
+ )
+ except Exception as exc:
+ raise CliError(f"cannot parse allowlisted DICOM metadata: {exc}") from exc
+ output: dict[str, Any] = {"backend": "dicom"}
+ for field in fields:
+ if hasattr(dataset, field):
+ value = getattr(dataset, field)
+ if field == "PhotometricInterpretation":
+ output[field] = str(value)
+ else:
+ try:
+ output[field] = int(value)
+ except (TypeError, ValueError):
+ output[field] = str(value)
+ return output
+
+
+def _inspect_raster(path: Path, max_pixels: int) -> dict[str, Any]:
+ try:
+ from PIL import Image
+ except ModuleNotFoundError as exc:
+ raise CliError(
+ f"technical raster metadata requires PathML/Pillow dependencies; {PINNED_INSTALL}"
+ ) from exc
+
+ Image.MAX_IMAGE_PIXELS = max_pixels
+ try:
+ with Image.open(path) as image:
+ width, height = image.size
+ if width * height > max_pixels:
+ raise CliError(
+ f"image has {width * height} pixels; limit is {max_pixels}"
+ )
+ return {
+ "backend": "pillow",
+ "width": int(width),
+ "height": int(height),
+ "mode": str(image.mode),
+ "frame_count": int(getattr(image, "n_frames", 1)),
+ "format": str(image.format or "unknown"),
+ }
+ except CliError:
+ raise
+ except Exception as exc:
+ raise CliError(f"cannot parse allowlisted raster metadata: {exc}") from exc
+
+
+def inspect_slide(args: argparse.Namespace) -> dict[str, Any]:
+ root = checked_root(args.root)
+ max_slide_bytes = int(args.max_slide_gib * 1024**3)
+ slide = checked_input_file(
+ args.slide,
+ root=root,
+ suffixes=SLIDE_SUFFIXES,
+ max_bytes=max_slide_bytes,
+ )
+ suffix = _matched_suffix(slide)
+ report: dict[str, Any] = {
+ "command": "inspect",
+ "local_regular_file": True,
+ "symlink": False,
+ "size_bytes": slide.stat().st_size,
+ "suffix": suffix,
+ "technical_metadata_included": False,
+ "path_redacted": True,
+ }
+ if args.sha256:
+ report["sha256"] = sha256_file(
+ slide, max_bytes=int(args.max_hash_gib * 1024**3)
+ )
+ if args.technical_metadata:
+ if suffix in DICOM_SUFFIXES:
+ technical = _inspect_dicom(slide)
+ elif suffix in OPENSLIDE_SUFFIXES:
+ technical = _inspect_openslide(slide)
+ else:
+ technical = _inspect_raster(slide, args.max_pixels)
+ report["technical_metadata"] = technical
+ report["technical_metadata_included"] = True
+ return report
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(
+ description=(
+ "Validate local pseudonymous slide manifests or inspect only "
+ "allowlisted technical metadata. No network access."
+ )
+ )
+ subparsers = parser.add_subparsers(dest="command", required=True)
+
+ validate = subparsers.add_parser(
+ "validate", help="validate a bounded local CSV manifest"
+ )
+ validate.add_argument("--manifest", required=True)
+ validate.add_argument("--root", default=".")
+ validate.add_argument("--splits", default="train,validation,test")
+ validate.add_argument("--max-rows", type=int, default=100_000)
+ validate.add_argument(
+ "--max-manifest-bytes", type=int, default=MAX_CSV_BYTES
+ )
+ validate.add_argument("--max-slide-gib", type=float, default=1024.0)
+ validate.add_argument("--output")
+ validate.add_argument("--force", action="store_true")
+
+ inspect = subparsers.add_parser(
+ "inspect", help="inspect one local slide without emitting its path"
+ )
+ inspect.add_argument("--slide", required=True)
+ inspect.add_argument("--root", default=".")
+ inspect.add_argument("--max-slide-gib", type=float, default=1024.0)
+ inspect.add_argument("--technical-metadata", action="store_true")
+ inspect.add_argument("--max-pixels", type=int, default=16_000_000)
+ inspect.add_argument("--sha256", action="store_true")
+ inspect.add_argument("--max-hash-gib", type=float, default=64.0)
+ inspect.add_argument("--output")
+ inspect.add_argument("--force", action="store_true")
+ return parser
+
+
+def main() -> None:
+ args = build_parser().parse_args()
+ if args.command == "validate":
+ if not 1 <= args.max_rows <= MAX_ROWS:
+ raise CliError(f"--max-rows must be between 1 and {MAX_ROWS}")
+ if not 0 < args.max_manifest_bytes <= MAX_CSV_BYTES:
+ raise CliError(
+ f"--max-manifest-bytes must be between 1 and {MAX_CSV_BYTES}"
+ )
+ if not math.isfinite(args.max_slide_gib) or not 0 < args.max_slide_gib <= 4096:
+ raise CliError("--max-slide-gib must be finite and in (0, 4096]")
+ report = validate_manifest(args)
+ else:
+ if not math.isfinite(args.max_slide_gib) or not 0 < args.max_slide_gib <= 4096:
+ raise CliError("--max-slide-gib must be finite and in (0, 4096]")
+ if not math.isfinite(args.max_hash_gib) or not 0 < args.max_hash_gib <= 4096:
+ raise CliError("--max-hash-gib must be finite and in (0, 4096]")
+ if not 1 <= args.max_pixels <= 100_000_000:
+ raise CliError("--max-pixels must be between 1 and 100000000")
+ report = inspect_slide(args)
+ emit_json(report, output=args.output, root=args.root, force=args.force)
+
+
+if __name__ == "__main__":
+ raise SystemExit(run_cli(main))
diff --git a/skills/pathml/scripts/validate_spatial_schema.py b/skills/pathml/scripts/validate_spatial_schema.py
new file mode 100644
index 00000000..e4401194
--- /dev/null
+++ b/skills/pathml/scripts/validate_spatial_schema.py
@@ -0,0 +1,420 @@
+#!/usr/bin/env python3
+"""Validate bounded graph JSON and multiplex cell-table CSV schemas."""
+
+from __future__ import annotations
+
+import argparse
+import csv
+import math
+import re
+from collections import Counter
+from pathlib import Path
+from typing import Any
+
+from _common import (
+ CliError,
+ MAX_CSV_BYTES,
+ MAX_JSON_BYTES,
+ checked_input_file,
+ checked_root,
+ emit_json,
+ finite_float,
+ load_json_object,
+ parse_name_list,
+ run_cli,
+ validate_keys,
+)
+
+
+ID_PATTERN = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$")
+COORDINATE_UNITS = {"level_pixels", "level0_pixels", "um"}
+
+
+def _identifier(value: Any, *, context: str) -> str:
+ if not isinstance(value, str) or not ID_PATTERN.fullmatch(value):
+ raise CliError(
+ f"{context} must use 1-128 letters, digits, dots, underscores, "
+ "colons, or hyphens"
+ )
+ return value
+
+
+def validate_graph(args: argparse.Namespace) -> dict[str, Any]:
+ root = checked_root(args.root)
+ document = load_json_object(
+ args.input,
+ root=root,
+ max_bytes=args.max_input_bytes,
+ )
+ validate_keys(
+ document,
+ allowed={
+ "schema_version",
+ "slide_id",
+ "coordinate_unit",
+ "level",
+ "nodes",
+ "edges",
+ "metadata",
+ },
+ required={"schema_version", "slide_id", "coordinate_unit", "nodes", "edges"},
+ context="graph",
+ )
+ if document["schema_version"] != "1.0":
+ raise CliError("graph schema_version must be '1.0'")
+ _identifier(document["slide_id"], context="slide_id")
+ coordinate_unit = document["coordinate_unit"]
+ if coordinate_unit not in COORDINATE_UNITS:
+ raise CliError(
+ "coordinate_unit must be one of: "
+ + ", ".join(sorted(COORDINATE_UNITS))
+ )
+ if "level" in document:
+ level = document["level"]
+ if isinstance(level, bool) or not isinstance(level, int) or level < 0:
+ raise CliError("level must be a nonnegative integer")
+ nodes = document["nodes"]
+ edges = document["edges"]
+ if not isinstance(nodes, list) or not isinstance(edges, list):
+ raise CliError("nodes and edges must be arrays")
+ if not 1 <= len(nodes) <= args.max_nodes:
+ raise CliError(f"node count must be in [1, {args.max_nodes}]")
+ if len(edges) > args.max_edges:
+ raise CliError(f"edge count exceeds --max-edges={args.max_edges}")
+
+ node_ids: set[str] = set()
+ feature_length: int | None = None
+ for index, node in enumerate(nodes):
+ if not isinstance(node, dict):
+ raise CliError(f"node {index} must be an object")
+ validate_keys(
+ node,
+ allowed={"id", "x", "y", "features", "label"},
+ required={"id", "x", "y"},
+ context=f"node {index}",
+ )
+ node_id = _identifier(node["id"], context=f"node {index} id")
+ if node_id in node_ids:
+ raise CliError(f"duplicate node id: {node_id!r}")
+ node_ids.add(node_id)
+ finite_float(node["x"], name=f"node {index} x", minimum=0, maximum=1e12)
+ finite_float(node["y"], name=f"node {index} y", minimum=0, maximum=1e12)
+ if "features" in node:
+ features = node["features"]
+ if not isinstance(features, list):
+ raise CliError(f"node {index} features must be an array")
+ if len(features) > args.max_features:
+ raise CliError(
+ f"node {index} has more than {args.max_features} features"
+ )
+ if feature_length is None:
+ feature_length = len(features)
+ elif len(features) != feature_length:
+ raise CliError("all feature arrays must have the same length")
+ for feature_index, value in enumerate(features):
+ finite_float(
+ value,
+ name=f"node {index} feature {feature_index}",
+ minimum=-1e15,
+ maximum=1e15,
+ )
+
+ seen_edges: set[tuple[str, str]] = set()
+ self_loops = 0
+ for index, edge in enumerate(edges):
+ if not isinstance(edge, dict):
+ raise CliError(f"edge {index} must be an object")
+ validate_keys(
+ edge,
+ allowed={"source", "target", "weight", "edge_type"},
+ required={"source", "target"},
+ context=f"edge {index}",
+ )
+ source = _identifier(edge["source"], context=f"edge {index} source")
+ target = _identifier(edge["target"], context=f"edge {index} target")
+ if source not in node_ids or target not in node_ids:
+ raise CliError(f"edge {index} references an unknown node")
+ if source == target:
+ self_loops += 1
+ if not args.allow_self_loops:
+ raise CliError(f"edge {index} is a self-loop")
+ key = tuple(sorted((source, target))) if args.undirected else (source, target)
+ if key in seen_edges:
+ raise CliError(f"edge {index} duplicates an existing edge")
+ seen_edges.add(key)
+ if "weight" in edge:
+ finite_float(
+ edge["weight"],
+ name=f"edge {index} weight",
+ minimum=-1e15,
+ maximum=1e15,
+ )
+
+ return {
+ "command": "graph",
+ "valid": True,
+ "node_count": len(nodes),
+ "edge_count": len(edges),
+ "feature_count": feature_length or 0,
+ "coordinate_unit": coordinate_unit,
+ "directed_edge_keys": not args.undirected,
+ "self_loop_count": self_loops,
+ "checks": {
+ "strict_json": True,
+ "bounded": True,
+ "unique_node_ids": True,
+ "finite_coordinates": True,
+ "uniform_feature_shape": True,
+ "valid_edge_endpoints": True,
+ "unique_edges": True,
+ },
+ "path_redacted": True,
+ }
+
+
+def _parse_csv_float(
+ raw: str,
+ *,
+ name: str,
+ minimum: float | None = None,
+) -> float:
+ try:
+ value = float(raw)
+ except ValueError as exc:
+ raise CliError(f"{name} must be numeric") from exc
+ if not math.isfinite(value):
+ raise CliError(f"{name} must be finite")
+ if minimum is not None and value < minimum:
+ raise CliError(f"{name} must be at least {minimum}")
+ return value
+
+
+def validate_multiplex(args: argparse.Namespace) -> dict[str, Any]:
+ root = checked_root(args.root)
+ path = checked_input_file(
+ args.input,
+ root=root,
+ suffixes={".csv"},
+ max_bytes=args.max_input_bytes,
+ )
+ requested_markers = parse_name_list(
+ args.marker_columns, name="--marker-columns"
+ )
+ keys: set[tuple[str, str]] = set()
+ slide_units: dict[str, str] = {}
+ slide_levels: dict[str, int] = {}
+ patient_splits: dict[str, str] = {}
+ unit_counts: Counter[str] = Counter()
+ marker_missing: Counter[str] = Counter()
+ slide_ids: set[str] = set()
+ patient_ids: set[str] = set()
+
+ try:
+ with path.open("r", encoding="utf-8-sig", newline="") as handle:
+ reader = csv.DictReader(handle)
+ headers = reader.fieldnames
+ if headers is None:
+ raise CliError("multiplex CSV has no header")
+ headers = [header.strip() for header in headers]
+ if len(headers) != len(set(headers)):
+ raise CliError("multiplex CSV header contains duplicates")
+ required = {"cell_id", "slide_id", "x", "y", "coordinate_unit"}
+ missing = sorted(required - set(headers))
+ if missing:
+ raise CliError(
+ "multiplex CSV is missing required columns: "
+ + ", ".join(missing)
+ )
+ marker_columns = requested_markers or [
+ header for header in headers if header.startswith("marker:")
+ ]
+ if not marker_columns:
+ raise CliError(
+ "provide --marker-columns or use at least one marker:* column"
+ )
+ missing_markers = sorted(set(marker_columns) - set(headers))
+ if missing_markers:
+ raise CliError(
+ "requested marker columns are absent: "
+ + ", ".join(missing_markers)
+ )
+
+ row_count = 0
+ for row_count, raw_row in enumerate(reader, start=1):
+ if row_count > args.max_rows:
+ raise CliError(f"CSV exceeds --max-rows={args.max_rows}")
+ row_number = row_count + 1
+ row = {
+ key.strip(): (value or "").strip()
+ for key, value in raw_row.items()
+ if key is not None
+ }
+ slide_id = _identifier(
+ row["slide_id"], context=f"row {row_number} slide_id"
+ )
+ cell_id = _identifier(
+ row["cell_id"], context=f"row {row_number} cell_id"
+ )
+ key = (slide_id, cell_id)
+ if key in keys:
+ raise CliError(
+ f"row {row_number}: duplicate (slide_id, cell_id)"
+ )
+ keys.add(key)
+ slide_ids.add(slide_id)
+ _parse_csv_float(
+ row["x"], name=f"row {row_number} x", minimum=0
+ )
+ _parse_csv_float(
+ row["y"], name=f"row {row_number} y", minimum=0
+ )
+ unit = row["coordinate_unit"]
+ if unit not in COORDINATE_UNITS:
+ raise CliError(
+ f"row {row_number}: coordinate_unit must be one of "
+ + ", ".join(sorted(COORDINATE_UNITS))
+ )
+ previous_unit = slide_units.setdefault(slide_id, unit)
+ if previous_unit != unit:
+ raise CliError(
+ f"row {row_number}: slide has inconsistent coordinate units"
+ )
+ unit_counts[unit] += 1
+
+ level_raw = row.get("level", "")
+ if level_raw:
+ try:
+ level = int(level_raw)
+ except ValueError as exc:
+ raise CliError(
+ f"row {row_number}: level must be an integer"
+ ) from exc
+ if level < 0:
+ raise CliError(
+ f"row {row_number}: level must be nonnegative"
+ )
+ previous_level = slide_levels.setdefault(slide_id, level)
+ if previous_level != level:
+ raise CliError(
+ f"row {row_number}: slide has inconsistent levels"
+ )
+
+ patient_id = row.get("patient_id", "")
+ split = row.get("split", "")
+ if patient_id:
+ patient_id = _identifier(
+ patient_id, context=f"row {row_number} patient_id"
+ )
+ patient_ids.add(patient_id)
+ if split and patient_id:
+ previous_split = patient_splits.setdefault(patient_id, split)
+ if previous_split != split:
+ raise CliError(
+ f"row {row_number}: patient appears in multiple splits"
+ )
+
+ for marker in marker_columns:
+ raw_value = row.get(marker, "")
+ if raw_value == "":
+ marker_missing[marker] += 1
+ if not args.allow_missing_markers:
+ raise CliError(
+ f"row {row_number}: marker {marker!r} is missing"
+ )
+ continue
+ _parse_csv_float(
+ raw_value,
+ name=f"row {row_number} marker {marker}",
+ )
+
+ if row_count == 0:
+ raise CliError("multiplex CSV contains no rows")
+ except CliError:
+ raise
+ except (OSError, UnicodeError, csv.Error) as exc:
+ raise CliError(f"cannot parse multiplex CSV: {exc}") from exc
+
+ return {
+ "command": "multiplex",
+ "valid": True,
+ "row_count": len(keys),
+ "slide_count": len(slide_ids),
+ "patient_count": len(patient_ids),
+ "marker_columns": marker_columns,
+ "missing_marker_values": dict(sorted(marker_missing.items())),
+ "coordinate_unit_counts": dict(sorted(unit_counts.items())),
+ "checks": {
+ "bounded": True,
+ "unique_slide_cell_ids": True,
+ "finite_nonnegative_coordinates": True,
+ "per_slide_coordinate_units": True,
+ "per_slide_levels": True,
+ "finite_marker_values": True,
+ "patient_split_isolation_when_present": True,
+ },
+ "path_redacted": True,
+ }
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(
+ description=(
+ "Validate bounded local graph JSON or multiplex cell CSV without "
+ "loading PathML, Torch, models, or checkpoints."
+ )
+ )
+ subparsers = parser.add_subparsers(dest="command", required=True)
+
+ graph = subparsers.add_parser("graph", help="validate graph JSON")
+ graph.add_argument("--input", required=True)
+ graph.add_argument("--root", default=".")
+ graph.add_argument("--max-input-bytes", type=int, default=MAX_JSON_BYTES)
+ graph.add_argument("--max-nodes", type=int, default=100_000)
+ graph.add_argument("--max-edges", type=int, default=1_000_000)
+ graph.add_argument("--max-features", type=int, default=4096)
+ graph.add_argument("--undirected", action="store_true")
+ graph.add_argument("--allow-self-loops", action="store_true")
+ graph.add_argument("--output")
+ graph.add_argument("--force", action="store_true")
+
+ multiplex = subparsers.add_parser(
+ "multiplex", help="validate a cell-by-marker CSV"
+ )
+ multiplex.add_argument("--input", required=True)
+ multiplex.add_argument("--root", default=".")
+ multiplex.add_argument("--max-input-bytes", type=int, default=MAX_CSV_BYTES)
+ multiplex.add_argument("--max-rows", type=int, default=100_000)
+ multiplex.add_argument("--marker-columns")
+ multiplex.add_argument("--allow-missing-markers", action="store_true")
+ multiplex.add_argument("--output")
+ multiplex.add_argument("--force", action="store_true")
+ return parser
+
+
+def main() -> None:
+ args = build_parser().parse_args()
+ if args.command == "graph":
+ if not 1 <= args.max_input_bytes <= MAX_JSON_BYTES:
+ raise CliError(
+ f"--max-input-bytes must be between 1 and {MAX_JSON_BYTES}"
+ )
+ if not 1 <= args.max_nodes <= 10_000_000:
+ raise CliError("--max-nodes must be between 1 and 10000000")
+ if not 0 <= args.max_edges <= 100_000_000:
+ raise CliError("--max-edges must be between 0 and 100000000")
+ if not 0 <= args.max_features <= 100_000:
+ raise CliError("--max-features must be between 0 and 100000")
+ report = validate_graph(args)
+ else:
+ if not 1 <= args.max_input_bytes <= MAX_CSV_BYTES:
+ raise CliError(
+ f"--max-input-bytes must be between 1 and {MAX_CSV_BYTES}"
+ )
+ if not 1 <= args.max_rows <= 1_000_000:
+ raise CliError("--max-rows must be between 1 and 1000000")
+ report = validate_multiplex(args)
+ emit_json(report, output=args.output, root=args.root, force=args.force)
+
+
+if __name__ == "__main__":
+ raise SystemExit(run_cli(main))
diff --git a/skills/pathml/tests/test_scripts.py b/skills/pathml/tests/test_scripts.py
new file mode 100644
index 00000000..5d4f70f8
--- /dev/null
+++ b/skills/pathml/tests/test_scripts.py
@@ -0,0 +1,441 @@
+#!/usr/bin/env python3
+"""Synthetic, network-free tests for the PathML skill CLIs."""
+
+from __future__ import annotations
+
+import ast
+import json
+import os
+import stat
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+
+SKILL_ROOT = Path(__file__).resolve().parents[1]
+SCRIPTS = SKILL_ROOT / "scripts"
+REFERENCES = SKILL_ROOT / "references"
+sys.path.insert(0, str(SCRIPTS))
+
+import _common # noqa: E402
+import image_qc # noqa: E402
+import plan_inference # noqa: E402
+import plan_pipeline # noqa: E402
+import slide_manifest # noqa: E402
+import validate_spatial_schema # noqa: E402
+
+
+def run_script(name: str, *arguments: str, cwd: Path | None = None) -> subprocess.CompletedProcess[str]:
+ return subprocess.run(
+ [sys.executable, "-S", str(SCRIPTS / name), *arguments],
+ cwd=cwd,
+ check=False,
+ capture_output=True,
+ text=True,
+ )
+
+
+class SafetyTests(unittest.TestCase):
+ def test_scripts_parse_without_dynamic_execution_or_network_imports(self) -> None:
+ banned_imports = {
+ "aiohttp",
+ "httpx",
+ "importlib",
+ "requests",
+ "socket",
+ "subprocess",
+ "urllib",
+ }
+ banned_calls = {"eval", "exec", "compile", "__import__"}
+ shadow_names = {
+ "csv.py",
+ "json.py",
+ "onnx.py",
+ "pathlib.py",
+ "pathml.py",
+ "pydicom.py",
+ "torch.py",
+ }
+ self.assertFalse({path.name for path in SCRIPTS.glob("*.py")} & shadow_names)
+ for path in sorted(SCRIPTS.glob("*.py")):
+ tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
+ for node in ast.walk(tree):
+ if isinstance(node, ast.Import):
+ roots = {alias.name.split(".", 1)[0] for alias in node.names}
+ self.assertFalse(roots & banned_imports, path.name)
+ if isinstance(node, ast.ImportFrom) and node.module:
+ self.assertNotIn(
+ node.module.split(".", 1)[0], banned_imports, path.name
+ )
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Name):
+ self.assertNotIn(node.func.id, banned_calls, path.name)
+ if isinstance(node, ast.Attribute):
+ self.assertFalse(
+ isinstance(node.value, ast.Name)
+ and node.value.id == "os"
+ and node.attr in {"environ", "getenv"},
+ path.name,
+ )
+
+ def test_every_cli_help_works_without_site_packages(self) -> None:
+ for path in sorted(SCRIPTS.glob("*.py")):
+ if path.name == "_common.py":
+ continue
+ with self.subTest(script=path.name):
+ result = run_script(path.name, "--help")
+ self.assertEqual(result.returncode, 0, result.stderr)
+ self.assertIn("usage:", result.stdout)
+ self.assertNotIn("Traceback", result.stderr)
+
+ def test_build_parsers_are_dependency_free(self) -> None:
+ modules = (
+ image_qc,
+ plan_inference,
+ plan_pipeline,
+ slide_manifest,
+ validate_spatial_schema,
+ )
+ for module in modules:
+ with self.subTest(module=module.__name__):
+ text = module.build_parser().format_help()
+ self.assertIn("usage:", text)
+ self.assertIn("--help", text)
+
+ def test_strict_local_io_rejects_url_symlink_duplicates_and_nan(self) -> None:
+ with self.assertRaises(_common.CliError):
+ _common.checked_input_file(
+ "https://example.invalid/slide.svs",
+ root=".",
+ suffixes={".svs"},
+ max_bytes=1024,
+ )
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ duplicate = root / "duplicate.json"
+ duplicate.write_text('{"x": 1, "x": 2}', encoding="utf-8")
+ with self.assertRaises(_common.CliError):
+ _common.load_json_object(duplicate, root=root)
+ nan = root / "nan.json"
+ nan.write_text('{"x": NaN}', encoding="utf-8")
+ with self.assertRaises(_common.CliError):
+ _common.load_json_object(nan, root=root)
+ real = root / "real.svs"
+ real.write_bytes(b"synthetic")
+ link = root / "link.svs"
+ try:
+ link.symlink_to(real)
+ except OSError:
+ self.skipTest("symlinks unavailable")
+ with self.assertRaises(_common.CliError):
+ _common.checked_input_file(
+ link,
+ root=root,
+ suffixes={".svs"},
+ max_bytes=1024,
+ )
+
+ def test_private_atomic_json_refuses_overwrite(self) -> None:
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ output = root / "report.json"
+ _common.emit_json({"ok": True}, output=output, root=root)
+ self.assertEqual(json.loads(output.read_text()), {"ok": True})
+ self.assertEqual(stat.S_IMODE(output.stat().st_mode), 0o600)
+ with self.assertRaises(_common.CliError):
+ _common.emit_json({"ok": False}, output=output, root=root)
+
+ def test_skill_version_and_progressive_disclosure(self) -> None:
+ skill = (SKILL_ROOT / "SKILL.md").read_text(encoding="utf-8")
+ self.assertIn('version: "1.1"', skill)
+ self.assertIn("license: MIT", skill)
+ self.assertLess(len(skill.splitlines()), 500)
+ self.assertEqual(
+ {path.name for path in REFERENCES.glob("*.md")},
+ {
+ "data_management.md",
+ "graphs.md",
+ "image_loading.md",
+ "machine_learning.md",
+ "multiparametric.md",
+ "preprocessing.md",
+ },
+ )
+
+
+class ManifestTests(unittest.TestCase):
+ def test_manifest_validation_and_redacted_inspection(self) -> None:
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ (root / "slide-a.svs").write_bytes(b"synthetic-a")
+ (root / "slide-b.svs").write_bytes(b"synthetic-b")
+ manifest = root / "manifest.csv"
+ manifest.write_text(
+ "slide_id,patient_id,path,split\n"
+ "slide-001,patient-001,slide-a.svs,train\n"
+ "slide-002,patient-002,slide-b.svs,test\n",
+ encoding="utf-8",
+ )
+ result = run_script(
+ "slide_manifest.py",
+ "validate",
+ "--manifest",
+ "manifest.csv",
+ "--root",
+ str(root),
+ )
+ self.assertEqual(result.returncode, 0, result.stderr)
+ report = json.loads(result.stdout)
+ self.assertTrue(report["valid"])
+ self.assertEqual(report["row_count"], 2)
+ self.assertEqual(report["patient_count"], 2)
+
+ inspect = run_script(
+ "slide_manifest.py",
+ "inspect",
+ "--slide",
+ "slide-a.svs",
+ "--root",
+ str(root),
+ )
+ self.assertEqual(inspect.returncode, 0, inspect.stderr)
+ inspected = json.loads(inspect.stdout)
+ self.assertTrue(inspected["path_redacted"])
+ self.assertNotIn("slide-a", inspect.stdout)
+
+ def test_manifest_detects_patient_split_leakage(self) -> None:
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ (root / "a.svs").write_bytes(b"a")
+ (root / "b.svs").write_bytes(b"b")
+ manifest = root / "manifest.csv"
+ manifest.write_text(
+ "slide_id,patient_id,path,split\n"
+ "slide-1,patient-1,a.svs,train\n"
+ "slide-2,patient-1,b.svs,test\n",
+ encoding="utf-8",
+ )
+ result = run_script(
+ "slide_manifest.py",
+ "validate",
+ "--manifest",
+ "manifest.csv",
+ "--root",
+ str(root),
+ )
+ self.assertEqual(result.returncode, 2)
+ self.assertIn("multiple", result.stderr)
+ self.assertNotIn("Traceback", result.stderr)
+
+
+class PlannerAndImageTests(unittest.TestCase):
+ def test_pipeline_planner_counts_tiles_and_rejects_unknown_transform(self) -> None:
+ result = run_script(
+ "plan_pipeline.py",
+ "--width",
+ "1024",
+ "--height",
+ "1024",
+ "--tile-size",
+ "512",
+ "--stride",
+ "512",
+ "--pipeline",
+ "TissueDetectionHE,LabelWhiteSpaceHE",
+ )
+ self.assertEqual(result.returncode, 0, result.stderr)
+ report = json.loads(result.stdout)
+ self.assertEqual(report["tile_count"], 4)
+ self.assertEqual(report["expected_mask_outputs_per_tile"], 1)
+ self.assertEqual(report["expected_label_outputs_per_tile"], 1)
+
+ bad = run_script(
+ "plan_pipeline.py",
+ "--width",
+ "1024",
+ "--height",
+ "1024",
+ "--pipeline",
+ "NotATransform",
+ )
+ self.assertEqual(bad.returncode, 2)
+ self.assertIn("unknown", bad.stderr)
+
+ def test_synthetic_and_binary_ppm_qc(self) -> None:
+ synthetic = run_script(
+ "image_qc.py",
+ "synthetic",
+ "--width",
+ "40",
+ "--height",
+ "20",
+ "--tissue-fraction",
+ "0.5",
+ )
+ self.assertEqual(synthetic.returncode, 0, synthetic.stderr)
+ report = json.loads(synthetic.stdout)
+ self.assertGreater(report["tissue_like_fraction"], 0.35)
+ self.assertLess(report["tissue_like_fraction"], 0.65)
+
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ ppm = root / "synthetic.ppm"
+ pixels = bytes((245, 245, 245, 180, 75, 135))
+ ppm.write_bytes(b"P6\n2 1\n255\n" + pixels)
+ result = run_script(
+ "image_qc.py",
+ "inspect",
+ "--image",
+ "synthetic.ppm",
+ "--root",
+ str(root),
+ "--mask-output",
+ "mask.pgm",
+ )
+ self.assertEqual(result.returncode, 0, result.stderr)
+ inspected = json.loads(result.stdout)
+ self.assertEqual(inspected["pixel_count"], 2)
+ self.assertAlmostEqual(inspected["tissue_like_fraction"], 0.5)
+ self.assertTrue((root / "mask.pgm").is_file())
+ self.assertEqual(stat.S_IMODE((root / "mask.pgm").stat().st_mode), 0o600)
+
+ def test_inference_planner_uses_json_only(self) -> None:
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ card = root / "card.json"
+ card.write_text(
+ json.dumps(
+ {
+ "schema_version": "1.0",
+ "model_id": "synthetic-model",
+ "artifact_sha256": "a" * 64,
+ "input_shape": [3, 256, 256],
+ "dtype": "float32",
+ "output_elements_per_tile": 65536,
+ "activation_multiplier": 4.0,
+ }
+ ),
+ encoding="utf-8",
+ )
+ result = run_script(
+ "plan_inference.py",
+ "--model-card",
+ "card.json",
+ "--root",
+ str(root),
+ "--tile-count",
+ "100",
+ "--batch-size",
+ "8",
+ )
+ self.assertEqual(result.returncode, 0, result.stderr)
+ report = json.loads(result.stdout)
+ self.assertTrue(report["model_card_used"])
+ self.assertFalse(report["checkpoint_or_model_loaded"])
+ self.assertEqual(report["number_of_batches"], 13)
+
+ rejected = run_script(
+ "plan_inference.py",
+ "--model-card",
+ "untrusted.pt",
+ "--root",
+ str(root),
+ "--tile-count",
+ "1",
+ "--batch-size",
+ "1",
+ )
+ self.assertEqual(rejected.returncode, 2)
+ self.assertIn("never loaded", rejected.stderr)
+
+
+class SpatialSchemaTests(unittest.TestCase):
+ def test_graph_schema(self) -> None:
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ graph = root / "graph.json"
+ graph.write_text(
+ json.dumps(
+ {
+ "schema_version": "1.0",
+ "slide_id": "slide-001",
+ "coordinate_unit": "um",
+ "nodes": [
+ {
+ "id": "cell-1",
+ "x": 1.0,
+ "y": 2.0,
+ "features": [0.1, 0.2],
+ },
+ {
+ "id": "cell-2",
+ "x": 3.0,
+ "y": 4.0,
+ "features": [0.3, 0.4],
+ },
+ ],
+ "edges": [{"source": "cell-1", "target": "cell-2"}],
+ }
+ ),
+ encoding="utf-8",
+ )
+ result = run_script(
+ "validate_spatial_schema.py",
+ "graph",
+ "--input",
+ "graph.json",
+ "--root",
+ str(root),
+ )
+ self.assertEqual(result.returncode, 0, result.stderr)
+ report = json.loads(result.stdout)
+ self.assertTrue(report["valid"])
+ self.assertEqual(report["node_count"], 2)
+ self.assertEqual(report["edge_count"], 1)
+
+ def test_multiplex_schema_and_patient_split(self) -> None:
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ cells = root / "cells.csv"
+ cells.write_text(
+ "cell_id,patient_id,slide_id,split,x,y,coordinate_unit,level,"
+ "marker:DAPI,marker:CD3\n"
+ "cell-1,patient-1,slide-1,train,1.0,2.0,um,0,10,20\n"
+ "cell-2,patient-1,slide-1,train,3.0,4.0,um,0,11,21\n",
+ encoding="utf-8",
+ )
+ result = run_script(
+ "validate_spatial_schema.py",
+ "multiplex",
+ "--input",
+ "cells.csv",
+ "--root",
+ str(root),
+ )
+ self.assertEqual(result.returncode, 0, result.stderr)
+ report = json.loads(result.stdout)
+ self.assertTrue(report["valid"])
+ self.assertEqual(report["row_count"], 2)
+ self.assertEqual(report["marker_columns"], ["marker:DAPI", "marker:CD3"])
+
+ cells.write_text(
+ "cell_id,patient_id,slide_id,split,x,y,coordinate_unit,marker:DAPI\n"
+ "cell-1,patient-1,slide-1,train,1,2,um,10\n"
+ "cell-2,patient-1,slide-2,test,3,4,um,11\n",
+ encoding="utf-8",
+ )
+ leaked = run_script(
+ "validate_spatial_schema.py",
+ "multiplex",
+ "--input",
+ "cells.csv",
+ "--root",
+ str(root),
+ )
+ self.assertEqual(leaked.returncode, 2)
+ self.assertIn("multiple splits", leaked.stderr)
+
+
+if __name__ == "__main__":
+ unittest.main()