diff --git a/.github/workflows/unit-tests.yml b/.github/workflows/unit-tests.yml index c37c060..e45b3e4 100644 --- a/.github/workflows/unit-tests.yml +++ b/.github/workflows/unit-tests.yml @@ -27,4 +27,5 @@ jobs: # --frozen fails if uv.lock is out of step with pyproject.toml instead of re-resolving. - name: Run - run: uv run --frozen --group dev pytest tests/unit -v + # build_sif.sbatch is a cluster helper, not pipeline code; its tests run locally only. + run: uv run --frozen --group dev pytest tests/unit -v --ignore=tests/unit/test_build_sif.py diff --git a/.gitignore b/.gitignore index bfb4658..ce3646f 100644 --- a/.gitignore +++ b/.gitignore @@ -49,3 +49,5 @@ fixture/ site/_build/ site/_generated/ site/node_modules/ +tests/unit/fixtures/nimbus_crop/ +tests/unit/fixtures/nimbus_crop_065/ diff --git a/.nf-core.yml b/.nf-core.yml index 53d2897..d6b5c41 100644 --- a/.nf-core.yml +++ b/.nf-core.yml @@ -79,9 +79,12 @@ lint: - tests/reference_channels.nf.test - tests/dearray_channel.nf.test - tests/validate_params.nf.test + - tests/validate_virtues_markers.nf.test - tests/args_cli.nf.test - tests/instanseg_memory.nf.test - tests/segmentation_specs.nf.test + - tests/feature_specs.nf.test + - tests/pixel_size.nf.test multiqc_config: false @@ -99,4 +102,4 @@ template: - igenomes - multiqc - fastqc - version: 2.0.0 + version: 3.2.0 diff --git a/CHANGELOG.md b/CHANGELOG.md index 51cf6e3..190140f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,7 +3,59 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -## v3.0.0 - [unreleased] +## v3.2.0 - [2026-11-27] + +### Added + +- `use_nimbus`: per-cell marker positivity scores from Nimbus, one `{method}_nimbus` table per + segmentation method, tiled so memory does not grow with the image. `nimbus_channels` picks the + markers. Provenance is published to `learned_features/`. +- `use_virtues`: 512-number VirTues embeddings per cell (`{method}_virtues`), per 128 µm tissue + square (`virtues_niches`, `virtues_niches_table`) and per core or slide (`virtues_tissue`), tiled + so memory does not grow with the image. Needs `use_gpu`, `use_preprocessing`, + `use_tissue_segmentation`, `segment_cells`, `pixel_size` and a `uniprot_id` column in the marker + sheet. `virtues_stats` reuses one statistics file. Weights (`sp32`) are CC BY-NC 4.0. +- `tools/build_sif.sbatch`: builds a SIF from a registry ref or a local `docker save` / OCI archive + into Nextflow's cache, never replacing an image there. Logs go to the cache's `logs/`. +- `tools/segmentation_benchmark/`: scores Cellpose-SAM settings against hand-drawn outlines on + SLURM. Results are on the site's Segmentation benchmark page. + +### Changed + +- Cellpose uses `cpsam_v2` (cellpose's own default); cell counts shift. `pretrained_model: cpsam` + restores the old model. +- Cellpose defaults from a segmentation benchmark against manual outlines: `flow_threshold` + 0.6, `cellprob_threshold` -1, no CLAHE (`clip_limit` 0), no smoothing (`gaussian_sigma` 0, + `projection_sigma` 0). Mean F1 rises from 0.53 to 0.73 on mIF crops; cell counts shift. sopa's + old values: `flow_threshold: 2`, `cellprob_threshold: -6`, `clip_limit: 0.2`, + `gaussian_sigma: 1`, `projection_sigma: 1`. + +### Fixed + +- QC's before-and-after background subtraction comparison never ran: the + pre-subtraction image lacked the sample keys QC joins on. Broken since at least 2.0.0. + +### Deprecated + +- `instanseg_pixel_size` is now `pixel_size`, shared by InstanSeg and Nimbus. The old name still + works and warns; setting both to different values is an error. + +## v3.1.0 - [2026-11-07] + +### Added + +- Documentation website (MyST, GitHub Pages): getting started, inputs, outputs and their + reports, tutorials on the exemplar data, one page per module, and a parameter reference + generated from the schema. Parameter rules + (requires, conflicts, ignored unless) are in the schema `help_text`. + +### Changed + +- Docs site navigation restructured: inputs, outputs by kind, tutorials on the exemplar data, one + page per module; how-to guides dropped. +- Metro map redrawn as two lines on two rows, larger and with higher contrast. + +## v3.0.0 - [2026-11-07] ### Breaking @@ -15,10 +67,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -- Documentation website (MyST, GitHub Pages): getting started, inputs, outputs and their - reports, tutorials on the exemplar data, one page per module, and a parameter reference - generated from the schema. Parameter rules - (requires, conflicts, ignored unless) are in the schema `help_text`. - `quantification_statistics` (default `mean,median,std`; also `min`, `max`, `q25`, `q75`, `q90`) sets the statistics per marker. `mean` is required. - Shape features in `obs` for the cell and, where linked, the nucleus: `cell_*` and `nucleus_*` diff --git a/CITATIONS.md b/CITATIONS.md index 402d5ef..978973e 100644 --- a/CITATIONS.md +++ b/CITATIONS.md @@ -65,6 +65,28 @@ Both are MIT licensed. This pipeline would not exist without them. > Schmidt U, Weigert M, Broaddus C, Myers G. Cell Detection with Star-Convex Polygons. MICCAI 2018, LNCS 11071, 265–273 (2018). https://doi.org/10.1007/978-3-030-00934-2_30 +- [Nimbus](https://doi.org/10.1038/s41592-025-02826-9) — per-cell marker positivity, under `use_nimbus` + + > Rumberger JL, Greenwald NF, Ranek JS, Boonrat P, Walker C, Franzen J, Varra SR, Kong A, Sowers C, Liu CC, Averbukh I, Piyadasa H, Vanguri R, Nederlof I, Wang XJ, Van Valen D, Kok M, Bendall SC, Hollmann TJ, Kainmueller D, Angelo M. Automated classification of cellular expression in multiplexed imaging data with Nimbus. Nat Methods 22(10), 2161–2170 (2025). https://doi.org/10.1038/s41592-025-02826-9 + +- [VirTues](https://doi.org/10.1038/s41586-026-10884-y) — cell, tissue-square and tissue embeddings, under `use_virtues` + + > Wenckstern J, Jain E, von Querfurth B, Cheng Y, Vasilev K, Pariset M, Cheng PF, Liakopoulos P, Michielin O, Wicki A, Gut G, Bunne C. The Virtual Tissues foundation model resolves spatial proteomics across scales. Nature 657(8132), 744–754 (2026). https://doi.org/10.1038/s41586-026-10884-y; preprint arXiv:2501.06039 + + The weights (`sp32`) are CC BY-NC 4.0; the code is MIT. [VirTues on GitHub](https://github.com/bunnelab/virtues). + +- [spora](https://arxiv.org/abs/2610.24002) — the spatial proteomics data and tooling the released VirTues weights were trained with; its intensity recipe is followed + + > von Querfurth B, Wenckstern J, Jain E, Klein L, Cheng P, Cheng Y, Vincent-Cuaz C, Haberecker M, Frossard P, Wicki A, Michielin O, Bunne C. spora: A Unified Multimodal Dataset and Platform for Spatial Proteomics. arXiv:2610.24002 (2026). https://arxiv.org/abs/2610.24002. Code: [spora-io](https://github.com/bunnelab/spora-io). + +- [ESM-2](https://doi.org/10.1126/science.ade2574) — protein sequence embeddings for each marker, under `use_virtues` + + > Lin Z, Akin H, Rao R, Hie B, Zhu Z, Lu W, Smetanin N, Verkuil R, Kabeli O, Shmueli Y, dos Santos Costa A, Fazel-Zarandi M, Sercu T, Candido S, Rives A. Evolutionary-scale prediction of atomic-level protein structure with a language model. Science 379, 1123–1130 (2023). https://doi.org/10.1126/science.ade2574 + +- [UniProt](https://doi.org/10.1093/nar/gkae1010) — human reviewed protein sequences, with isoforms, bundled in the VirTues image + + > The UniProt Consortium. UniProt: the Universal Protein Knowledgebase in 2025. Nucleic Acids Res 53(D1), D609–D619 (2025). https://doi.org/10.1093/nar/gkae1010 + - [SpatialData](https://www.nature.com/articles/s41592-024-02212-x) — the Zarr-backed data structure the whole downstream half is built on diff --git a/README.md b/README.md index ff66bc3..df41aa2 100644 --- a/README.md +++ b/README.md @@ -1,68 +1,45 @@ -# CosciaLab/histo - -Processing, segmentation and quantification of multiplex immunofluorescence (mIF) images. -Input is raw cycles in any format Ashlar reads (Bio-Formats), or a stitched OME-TIFF. -H&E is planned and not supported. - -> [!WARNING] -> **Version 2.0.0.** Runs end to end on real data (mIF, TMA, WSI). The samplesheet and marker -> sheet columns are stable. QC thresholds were calibrated on a single slide, so check your results. +# Histo [![Nextflow](https://img.shields.io/badge/version-%E2%89%A525.10.4-green?style=flat&logo=nextflow&logoColor=white&color=%230DC09D&link=https%3A%2F%2Fnextflow.io)](https://www.nextflow.io/) [![nf-test](https://img.shields.io/badge/unit_tests-nf--test-337ab7.svg)](https://www.nf-test.com) [![run with singularity](https://img.shields.io/badge/run%20with-singularity-1d355c.svg?labelColor=000000)](https://sylabs.io/docs/) -## What this is - -A Nextflow pipeline for imaging data from human tissue, built to run unattended on colleagues' -datasets as well as my own. It combines two existing projects: +Processing, segmentation and quantification of multiplex immunofluorescence (mIF) and H&E images from the same tissue. +H&E is planned and not yet supported. -| Source | What is taken from it | -| ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------- | -| [nf-core/mcmicro](https://github.com/nf-core/mcmicro) | Preprocessing: illumination correction, stitching and registration, background subtraction, TMA dearray | -| [nf-core/sopa](https://github.com/nf-core/sopa) | Everything from segmentation onward: SpatialData object, tiled segmentation, aggregation, reporting | - -The handoff between the two halves is a single stitched OME-TIFF. Segmentation is tiled, so it is -size independent: images from 5 GB to 100 GB run the same way. - -This is a **personal pipeline, not an nf-core pipeline**, and is not affiliated with or endorsed by -nf-core. It follows nf-core conventions for reproducibility and to keep upstream contributions open. - -## Steps +> [!WARNING] +> Pipeline is still in heavy development: features, inputs, and outputs will change. ![Metro map of the whole-slide and TMA paths through the pipeline](docs/images/pipeline_paths.svg) -Preprocessing (from mcmicro): +## What it does + +Preprocessing: 1. Illumination correction (BaSiCPy) 2. Stitching and registration (Ashlar) -3. TMA dearray (UNetCoreograph), optional: `--use_tma_dearray`; the downsample factor is chosen - from the expected core count and diameter -4. Background subtraction (backsub), optional: `--use_backsub`; per core on a TMA - -Downstream (from sopa): +3. TMA dearray (UNetCoreograph) +4. Background subtraction (backsub) -5. SpatialData Zarr conversion and channel naming from the marker sheet -6. Tiled segmentation of cells, nuclei or both, with Cellpose, InstanSeg or both, optionally - skipping empty tiles; nuclei are linked to their cells and the cytoplasm derived -7. Aggregation of mean channel intensity per cell, and per nucleus and cytoplasm -8. QC report per sample and method, a comparison when both methods segment cells, and for a TMA a merged - object per slide +Downstream: -`use_preprocessing: false` starts from an already stitched image; `preprocessing_only: true` stops -after preprocessing. At startup the run stops if the Ashlar or Coreograph channel is not `dna` in -the marker sheet; `--skip_reference_dna_check` overrides. +1. SpatialData Zarr conversion and channel naming from the marker sheet +2. Tiled segmentation of cells, nuclei or both, with Cellpose, InstanSeg or both +3. Resolve segmentation conflicts in tile overlaps +4. Nuclei are linked to their cells and the cytoplasm derived +5. Aggregation of channel intensity per cell, and per nucleus and cytoplasm +6. QC report per sample and method ## Usage ```bash -nextflow run CosciaLab/histo -r v2.0.0 \ - -profile singularity,size_small,slurm \ +nextflow run CosciaLab/histo \ + -profile \ + --input samplesheet.csv \ -params-file params.yml ``` -Needs Nextflow >= 25.10.4, a container engine and pre-staged images (no pulls at launch). Start -`params.yml` from [assets/params_template_compact.yml](assets/params_template_compact.yml). +Needs Nextflow >= 25.10.4, a container engine and pre-staged images (no pulls at launch). Start `params.yml` from [assets/params_template_compact.yml](assets/params_template_compact.yml). ## Documentation @@ -83,6 +60,9 @@ Needs Nextflow >= 25.10.4, a container engine and pre-staged images (no pulls at Written by Jose Nimo at the Max Delbrück Center for Molecular Medicine, Berlin. +This is a **personal pipeline, not an nf-core pipeline**, and is not affiliated with or endorsed by +nf-core. It follows nf-core conventions for reproducibility and to keep upstream contributions open. + This pipeline is derived from two MIT licensed projects and would not exist without them: - **nf-core/sopa**, written by [Quentin Blampey](https://github.com/quentinblampey) and diff --git a/ROADMAP.md b/ROADMAP.md index 9d589c2..b7015df 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -6,30 +6,12 @@ troubleshootability. Sizes are focused working time, estimated before the releas ## Next releases -Quantification, documentation, resources, segmentation defaults, learned features, then a QC -report overhaul. Each release adds a QC report chapter for what it measures (MultiQC suits tool -logs, not our figures). 2.0 is in the [CHANGELOG](CHANGELOG.md). +Released work is in the [CHANGELOG](CHANGELOG.md); 3.2 shipped Nimbus, VirTues and Cellpose +defaults from the segmentation benchmark. Next: tiling and resources, more learned features, then +a QC report overhaul. Each release adds a QC report chapter for what it measures (MultiQC suits +tool logs, not our figures). -### 3.0: quantification of every cell from every method, then filtering - -1. **Cell filtering.** One `obs` boolean per rule plus `keep`; never drop cells. Not - `passes_filtering`, which sopa deletes. Counts per rule in `{sample}_{method}_qc.json` and the report; - check `MERGE_SPATIALDATA` carries the columns. 2–3 days. -2. **Report chapters**, one per stage. - -### 3.1: documentation website - -The site is built (`site/`, deployed by `.github/workflows/docs.yml`). What remains: - -1. **Figures.** Fill the slots in `site/FIGURES.md` from exemplar-001 runs and viewer - screenshots. -2. **Odon.** Document it under Viewers in `site/outputs/reports.md`. -3. **Dark-field.** Decide whether BaSiCPy should fit one. It never does today - (`bin/basicpy_main.py` `--darkfield` is off, no parameter exposes it), yet - `docs/output.md` calls the profiles "fitted". -4. **Pages.** Set GitHub Pages source to "GitHub Actions" in the repo settings (one-time, owner). - -### 3.2: tiling and resources +### 3.3: tiling and resources 1. **Resources by tile size.** Run exemplar-001 crops from 256 px to the whole image as single patches, CPU and GPU, and fit CPUs, memory, GPU memory and time to tile area. Replaces the @@ -40,26 +22,35 @@ The site is built (`site/`, deployed by `.github/workflows/docs.yml`). What rema decision (decisions.md, Parameters): a value derived from the image alone is the same on any hardware. Needs item 1 for the cap. -### 3.3: segmentation defaults +### 3.4 onward: learned features -1. **`cpsam_v2`.** cellpose 4.2.1.1 defaults to it ("fewer spurious masks in low-contrast - regions"), but sopa passes `cpsam`, the only weights in `josenimo/sopa:2.3.0`. Bake both - in, select with `pretrained_model`, compare on exemplar-001 (or with item 2). ~1 day. -2. **Preprocessing benchmark with ground truth**, on `cpsam_v2` (item 1). Score - permutations of the steps before the model: combining (max, sum), smoothing - (`projection_sigma`, `gaussian_sigma`), normalisation and CLAHE, and thresholds (sopa's, - Cellpose's), against annotated cells: TissueNet (mIF, nuclear and whole-cell labels) and a - few in-house crops. Extends `tools/benchmark_projection.py`; on Apple MPS one setting takes - ~1.5 min per exemplar-001. Decides the defaults and item 3. 1–2 weeks. -3. **Three-channel projection** for CPSAM: split `use_projection`'s `cell` channel into membrane - and cytoplasm. The cellpose docs say a third channel needs retraining; item 2 tests it first. +KRONOS, on the stage Nimbus and VirTues use. One interface: image and shapes in, `obs`/`obsm` +out. Reuses 3.3's GPU sizing; weights baked into the image, as for Nimbus and VirTues. Not in +bioconda, so expect a private image. Check weight licences first. -### 3.4 onward: learned features +**VirTues follow-ups:** + +1. **QC plots** for the embeddings, after real-data validation. Only facts are in the QC report now. +2. **Per-tile tasks**, one GPU job per tile then a gather, if one task per store is too slow. +3. **A crop-step parameter**, now fixed at upstream's 42 px. +4. **Pre-stitched input**, which has no marker sheet and so no UniProt IDs. +5. **Per-slide statistics without waiting for the whole run.** Histograms are grouped with no + size, so no `VIRTUES` starts until every store is histogrammed. `groupKey(slide, n_cores)` + would pipeline multi-slide runs. + +### Carried over, not yet scheduled + +Left from 3.0 and 3.1. -Nimbus, KRONOS and VirTues, one per release; Nimbus first, as its per-cell marker positivity -feeds filtering. One interface: image and shapes in, `obs`/`obsm` out. Reuses 3.2's GPU sizing -and 3.3's baked weights. None is in bioconda, so expect private images. Check weight licences -first. +1. **Cell filtering.** One `obs` boolean per rule plus `keep`; never drop cells. Not + `passes_filtering`, which sopa deletes. Counts per rule in `{sample}_{method}_qc.json` and the + report; check `MERGE_SPATIALDATA` carries the columns. 2–3 days. +2. **Site figures.** Fill the slots in `site/FIGURES.md` from exemplar-001 runs and viewer + screenshots. +3. **Odon.** Document it under Viewers in `site/outputs/reports.md`. +4. **Dark-field.** Decide whether BaSiCPy should fit one. It never does today + (`bin/basicpy_main.py` `--darkfield` is off, no parameter exposes it), yet + `docs/output.md` calls the profiles "fitted". ### Then: QC report overhaul @@ -84,7 +75,8 @@ Images stay in our HTML reports: Depictio shows PNG/JPG only, not OME-TIFF or Za ### Separate track: dearray before Ashlar -Ships in 3.0: it changes the preprocessing outputs. Likely to change, as is Longer term item 4. +Not scheduled. It changes the preprocessing outputs, so it needs a major release. Likely to +change, as is Longer term item 4. Most valuable and most dangerous. Today Ashlar registers about 1000 tiles × 7 cycles in one job; one failure ruins the slide. Per core it would be about 36 tiles × 7 cycles, giving per-core @@ -140,8 +132,15 @@ Not scheduled. The marker sheet already has the columns these need (`channel_rol `clip_limit`, and with projection max or sum. An HTML sheet, settings by crops, shows each row's cell count, median area and nuclei inside cells, and a params snippet to paste; a rerun with `-resume` then reuses preprocessing. Works on copied crops, never the run's store. GPU - only: 3 × 3 × 2 settings on 5 crops is ~30 min on an A40. Complements 3.3 item 2, which sets - the defaults. Starts from `tools/benchmark_projection.py`. 1–2 weeks. + only: 3 × 3 × 2 settings on 5 crops is ~30 min on an A40. Complements the segmentation benchmark, + which set the defaults. Starts from `tools/benchmark_projection.py`. 1–2 weeks. +7. **Slide-wide Nimbus normalisation**, as an option beside the per-core default. One factor per + channel across all cores, so a core with no positive cells is not stretched to [0, 1]. +8. **Remove `instanseg_pixel_size`** at the next major release; `pixel_size` replaces it. +9. **Segmentation benchmark follow-ups.** Nuclear smoothing (`projection_sigma: 1`) helped + nuclei at 0.4 / 0 but is untested at the new 0.6 / -1: two settings on the cluster. A + three-channel CPSAM input (membrane and cytoplasm split) may need retraining, per the + cellpose docs; test with `tools/segmentation_benchmark` first. Items 3, 4 and dearray-first all need richer marker sheet metadata: design the columns once. If dearray-first happens, item 4 becomes "dearray the naive mosaic once per `dna` channel". @@ -158,6 +157,16 @@ dearray-first happens, item 4 becomes "dearray the naive mosaic once per `dna` c resolution, so it always picks the coarsest. Still reported; selection uses seed stability. - **Every `-stub` run warns about a positional argument `true`.** Nextflow 26.04.6 leaves it in the args for both `-stub` and `-stub-run`. Harmless. +- **An unchanged `-resume` reruns everything from `MAKE_IMAGE_PATCHES`.** Only `TO_SPATIALDATA` + is cached (seen in the Nimbus Mac run, 2026-11-12). Suspect the in-place Zarr mutation. + Also on the cluster (test13 07/08, 2026-11-27): the cache breaks at `SET_CHANNEL_NAMES`, same script. +- **A spaced boolean (`--use_qc false`) is reported as a samplesheet error.** The startup check + above catches it, but the message points at the wrong thing. +- **`bin/project_channels.py` reads tissue polygons as full-resolution pixels.** sopa stores + `region_of_interest` at the coarsest pyramid level (`Scale(16)`), so its tissue mask covers + about 1/16 of the tissue, top left. Use `to_image_pixels` from `bin/virtues_stats.py`. +- **`QC_IMAGES` on prestitched input needs a channel named `DAPI`.** `--nuclear-pattern` is not + exposed as a parameter. ### Known limitations @@ -166,10 +175,10 @@ dearray-first happens, item 4 becomes "dearray the naive mosaic once per `dna` c `params` ignores writes to set keys (Nextflow 26.04.6). Use a params file. - **InstanSeg on GPU is capped at 10 channels.** A stopgap (`instansegGpuMaxChannels`): sopa runs a whole patch at once, an A40 has 48 GB, and on CPU 37 channels at 2000 px peak near - 70 GB. 3.2 item 1 measures GPU peaks by channels and tile area; replace the cap with a warning + 70 GB. 3.3 item 1 measures GPU peaks by channels and tile area; replace the cap with a warning or a patch width that fits, and size InstanSeg's GPU tasks (CPUs, host memory) from the same runs. - **Segmentation-time area filtering is off by decision.** `min_area_pixels2 = null` means - sopa's CLI uses 0. Filtering belongs after aggregation (3.0 item 1). Note: + sopa's CLI uses 0. Filtering belongs after aggregation (Cell filtering, above). Note: `sopa/cli/resolve.py` takes `min_area` in µm², the segmentation CLI in px². - **Resource profiles are estimates** except `size_tiny`; rewrite from large-slide runs (`-with-tower`). @@ -188,7 +197,6 @@ dearray-first happens, item 4 becomes "dearray the naive mosaic once per `dna` c ### From 2.0 -- **Exemplar baselines are null** until 2.0's cluster runs, so the count checks are skipped. - **Repair geometry once in `RESOLVE`** (`make_valid`, polygonal parts), so `{m}_cells` and `{m}_nuclei` areas agree with the linking's; `LINK_COMPARTMENTS`' repair becomes a safety net. - **`uns['segmentation']` records the requested spec**, not sopa's defaults filled in later. diff --git a/assets/params_template.yml b/assets/params_template.yml index 2e661fe..5e62ec0 100644 --- a/assets/params_template.yml +++ b/assets/params_template.yml @@ -1,5 +1,5 @@ ## ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -## CosciaLab/histo 2.0.0 +## CosciaLab/histo 3.2.0 ## ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ## This is an example parameter file to pass to the `-params-file` option ## of nextflow run with the CosciaLab/histo pipeline. @@ -17,6 +17,15 @@ ## ============================================================================= ## Define where the pipeline should find input data and save output data. +## ----------------------------------------------------------------------------- +## pixel_size +## ----------------------------------------------------------------------------- +## µm per pixel of the image (OME PhysicalSizeX). Required by InstanSeg +## and Nimbus. +## Type: number +## ----------------------------------------------------------------------------- +# pixel_size: null + ## ----------------------------------------------------------------------------- ## input ## ----------------------------------------------------------------------------- @@ -426,13 +435,13 @@ ## Image preprocessing ## ============================================================================= ## Image preprocessing applied before segmentation (Cellpose, InstanSeg). -## Unset: sopa's per-method defaults (they differ for InstanSeg). +## Unset: none for either method. ## ----------------------------------------------------------------------------- ## gaussian_sigma ## ----------------------------------------------------------------------------- ## Parameter for scipy gaussian_filter (applied before running the -## segmentation method) +## segmentation method). Unset: 0, no smoothing. ## Type: number ## ----------------------------------------------------------------------------- # gaussian_sigma: null @@ -441,7 +450,7 @@ ## clip_limit ## ----------------------------------------------------------------------------- ## Parameter for skimage.exposure.equalize_adapthist (applied before -## running the segmentation method) +## running the segmentation method). Unset: 0, no CLAHE. ## Type: number ## ----------------------------------------------------------------------------- # clip_limit: null @@ -516,7 +525,7 @@ ## 0 for none. ## Type: number ## ----------------------------------------------------------------------------- -# projection_sigma: 1.0 +# projection_sigma: 0.0 ## ============================================================================= @@ -571,7 +580,8 @@ ## ----------------------------------------------------------------------------- ## flow_threshold ## ----------------------------------------------------------------------------- -## Cellpose `flow_threshold` parameter +## Cellpose `flow_threshold` parameter. Unset: 0.6, from the segmentation +## benchmark. ## Type: number ## ----------------------------------------------------------------------------- # flow_threshold: null @@ -579,7 +589,8 @@ ## ----------------------------------------------------------------------------- ## cellprob_threshold ## ----------------------------------------------------------------------------- -## Cellpose `cellprob_threshold` parameter +## Cellpose `cellprob_threshold` parameter. Unset: -1, from the +## segmentation benchmark. ## Type: number ## ----------------------------------------------------------------------------- # cellprob_threshold: null @@ -587,10 +598,11 @@ ## ----------------------------------------------------------------------------- ## pretrained_model ## ----------------------------------------------------------------------------- -## Cellpose `pretrained_model` parameter +## Cellpose weights: a name baked into the image (`cpsam_v2`, `cpsam`) or +## a path ## Type: string ## ----------------------------------------------------------------------------- -# pretrained_model: null +# pretrained_model: "cpsam_v2" ## ----------------------------------------------------------------------------- ## cellpose_kwargs @@ -606,6 +618,9 @@ ## ============================================================================= ## Parameters related to the InstanSeg segmentation method +## (1 hidden parameters are not shown) + + ## ----------------------------------------------------------------------------- ## use_instanseg ## ----------------------------------------------------------------------------- @@ -626,8 +641,7 @@ ## ----------------------------------------------------------------------------- ## instanseg_pixel_size ## ----------------------------------------------------------------------------- -## Image resolution in microns per pixel. Required: without it InstanSeg -## does not rescale and may find no cells +## Deprecated: use pixel_size ## Type: number ## ----------------------------------------------------------------------------- # instanseg_pixel_size: null @@ -654,6 +668,53 @@ # instanseg_kwargs: null +## ============================================================================= +## Learned features +## ============================================================================= +## Parameters related to learned-features models, which score each segmented +## cell + +## (1 hidden parameters are not shown) + + +## ----------------------------------------------------------------------------- +## use_nimbus +## ----------------------------------------------------------------------------- +## Score per-cell marker positivity with Nimbus. +## Type: boolean +## ----------------------------------------------------------------------------- +# use_nimbus: null + +## ----------------------------------------------------------------------------- +## nimbus_channels +## ----------------------------------------------------------------------------- +## Channel(s) to score with Nimbus. Unset takes the `marker` channels +## from each sample's marker sheet. Required without a marker sheet +## (`use_preprocessing = false`). Use marker names, separated by space, +## comma or pipe characters. +## Type: ['string', 'integer'] +## ----------------------------------------------------------------------------- +# nimbus_channels: null + +## ----------------------------------------------------------------------------- +## use_virtues +## ----------------------------------------------------------------------------- +## Embed each segmented cell with VirTues, a multiplex protein-marker +## foundation model. +## Type: boolean +## ----------------------------------------------------------------------------- +# use_virtues: null + +## ----------------------------------------------------------------------------- +## virtues_stats +## ----------------------------------------------------------------------------- +## A `{slide}_virtues_stats.json` from an earlier run, applied to every +## slide instead of computing per-slide statistics. +## Type: string +## ----------------------------------------------------------------------------- +# virtues_stats: null + + ## ============================================================================= ## QC report ## ============================================================================= diff --git a/assets/params_template_compact.yml b/assets/params_template_compact.yml index 64c0a63..9736335 100644 --- a/assets/params_template_compact.yml +++ b/assets/params_template_compact.yml @@ -8,9 +8,10 @@ # default; docs/usage.md lists the few you must set. ## Input/output options -# input: null # Path to a comma-separated samplesheet. Required. -# outdir: null # The output directory where the results will be saved. Required. -# email: null # Email address for completion summary. +# pixel_size: null # µm per pixel of the image (OME PhysicalSizeX). +# input: null # Path to a comma-separated samplesheet. Required. +# outdir: null # The output directory where the results will be saved. Required. +# email: null # Email address for completion summary. ## Preprocessing # use_preprocessing: true # Run the preprocessing half: illumination correction, stitching and registration, and the optional steps below. @@ -74,27 +75,33 @@ # projection_method: "max" # How the rescaled markers of a channel are combined. max keeps markers that stain only one cell type at full brightness; mean averages out noise but dims them. One of: max, mean. # projection_low_percentile: 1.0 # Per-marker percentile mapped to 0 before combining. # projection_high_percentile: 99.9 # Per-marker percentile mapped to 1 before combining. -# projection_sigma: 1.0 # Gaussian smoothing in pixels applied to each marker before combining; 0 for none. +# projection_sigma: 0.0 # Gaussian smoothing in pixels applied to each marker before combining; 0 for none. ## Segmentation targets # segment_cells: true # Segment whole cells with each enabled method: shapes `{method}_cells`. # segment_nuclei: null # Segment nuclei with each enabled method: shapes `{method}_nuclei`. ## Cellpose -# use_cellpose: null # Segment with Cellpose. -# cellpose_channels: null # Channel(s) to segment with Cellpose. -# flow_threshold: null # Cellpose `flow_threshold` parameter. -# cellprob_threshold: null # Cellpose `cellprob_threshold` parameter. -# pretrained_model: null # Cellpose `pretrained_model` parameter. -# cellpose_kwargs: null # Additional cellpose parameters as a python dict string. +# use_cellpose: null # Segment with Cellpose. +# cellpose_channels: null # Channel(s) to segment with Cellpose. +# flow_threshold: null # Cellpose `flow_threshold` parameter. +# cellprob_threshold: null # Cellpose `cellprob_threshold` parameter. +# pretrained_model: "cpsam_v2" # Cellpose weights: a name baked into the image (`cpsam_v2`, `cpsam`) or a path. +# cellpose_kwargs: null # Additional cellpose parameters as a python dict string. ## InstanSeg # use_instanseg: null # Segment with InstanSeg. # instanseg_model_type: null # Name of the pretrained InstanSeg model, or path to a local model. sopa defaults to `fluorescence_nuclei_and_cells`. -# instanseg_pixel_size: null # Image resolution in microns per pixel. +# instanseg_pixel_size: null # Deprecated: use pixel_size. # instanseg_channels: null # Channel(s) to segment with InstanSeg. # instanseg_kwargs: null # Additional InstanSeg parameters as a python dict string. +## Learned features +# use_nimbus: null # Score per-cell marker positivity with Nimbus. +# nimbus_channels: null # Channel(s) to score with Nimbus. +# use_virtues: null # Embed each segmented cell with VirTues, a multiplex protein-marker foundation model. +# virtues_stats: null # A `{slide}_virtues_stats.json` from an earlier run, applied to every slide instead of computing per-slide statistics. + ## QC report # use_qc: true # Whether to compute QC metrics, write Ashlar's stitching and registration QC, and render the QC report. # use_qc_images: true # Whether to include the segmentation crops and the cell clustering in the QC report. diff --git a/assets/schema_marker.json b/assets/schema_marker.json index eb6065a..7dcd5b0 100644 --- a/assets/schema_marker.json +++ b/assets/schema_marker.json @@ -90,6 +90,14 @@ "default": null, "description": "Set true to drop this channel from downstream output.", "meta": "remove" + }, + "uniprot_id": { + "type": "string", + "default": null, + "pattern": "^([OPQ][0-9][A-Z0-9]{3}[0-9]|[A-NR-Z][0-9]([A-Z][A-Z0-9]{2}[0-9]){1,2})(-[0-9]+)?$", + "description": "Optional. UniProt accession of the protein this channel stains, optionally with an isoform suffix. Read by use_virtues, which embeds a channel only when it has one. Leave empty for DNA stains and channels to skip.", + "errorMessage": "uniprot_id must be a UniProt accession, optionally with an isoform suffix (e.g. P08575 or P08575-8)", + "meta": "uniprot_id" } }, "required": ["channel_number", "cycle_number", "marker_name", "channel_role"], diff --git a/bin/merge_spatialdata.py b/bin/merge_spatialdata.py index 8ad6541..c644161 100755 --- a/bin/merge_spatialdata.py +++ b/bin/merge_spatialdata.py @@ -29,16 +29,14 @@ def core_id_from_path(zarr_path: Path) -> str: def retarget_table(table, rename_map: dict[str, str], core: str): """Rewrite a table's region in uns['spatialdata_attrs'] and its obs region_key column. - Both must agree or SpatialData refuses to link the table. + Both must agree or SpatialData refuses to link the table. A table without a region is returned as is. """ import pandas as pd attrs = table.uns.get("spatialdata_attrs") - if not attrs: - raise ValueError( - f"[{core}] table has no uns['spatialdata_attrs']; it was not written " - f"by SpatialData and cannot be relinked safely." - ) + # A table with no region annotates nothing, so there is nothing to retarget. + if not attrs or attrs.get("region") is None: + return table region = attrs.get("region") if isinstance(region, str): diff --git a/bin/nimbus_cells.py b/bin/nimbus_cells.py new file mode 100755 index 0000000..e436335 --- /dev/null +++ b/bin/nimbus_cells.py @@ -0,0 +1,347 @@ +#!/usr/bin/env python3 +"""Score each marker channel per cell with Nimbus, in tile windows so image size does not limit memory. + +The tiling core (assignment, windows, label rasterisation, normalisation factor, per-cell means) is +model-free; load_nimbus, nimbus_predictor and the CLI add the model. Sizes are in image px unless +named *_MODEL_PX. +""" + +import argparse +import hashlib +import json +import math +import sys +from pathlib import Path + +QUANTILE = 0.999 +TILE_MODEL_PX = 2048 +MIN_WINDOW_MODEL_PX = 1056 +MARGIN_EXTRA_MODEL_PX = 32 +WEIGHTS = "V1.pt" +MODEL_MAGNIFICATION = 10 +# um per model px; the one place for the "10x = 1 um/px" assumption, unconfirmed upstream (tools/containers/nimbus/README.md) +MODEL_UM_PER_PX = 1.0 +# Heavy libraries are imported inside functions so pure helpers test without them. + + +def image_px(model_px, pixel_size): + """Convert a size in model px to image px.""" + return math.ceil(model_px * MODEL_UM_PER_PX / pixel_size) + + +def resize_scale(pixel_size): + """Factor that takes an image of pixel_size um/px to the model's scale.""" + return pixel_size / MODEL_UM_PER_PX + + +def assign_tiles(centroids, tile_size): + """Tile index (tx, ty) of each (x, y) centroid; a cell belongs to the tile holding its centroid.""" + import numpy as np + + return np.floor(np.asarray(centroids, dtype=float) / tile_size).astype(int) + + +def _axis(lo, hi, margin, min_window, size): + lo, hi = lo - margin, hi + margin + if hi - lo < min_window: + extra = min_window - (hi - lo) + lo -= extra // 2 + hi = lo + min_window + if hi - lo <= size: + # shift inward at the border so the minimum holds where the image allows + if lo < 0: + lo, hi = 0, hi - lo + if hi > size: + lo, hi = lo - (hi - size), size + return max(int(lo), 0), min(int(hi), size) + + +def tile_windows(bounds, tiles, tile_size, margin, min_window, image_shape): + """(y0, y1, x0, x1) per tile: grown to its cells' bounds, then by margin, then to min_window, clipped.""" + import numpy as np + + bounds, tiles = np.asarray(bounds, dtype=float), np.asarray(tiles) + h, w = image_shape + windows = {} + for tx, ty in np.unique(tiles, axis=0): + b = bounds[(tiles == (tx, ty)).all(axis=1)] + x_lo = min(tx * tile_size, b[:, 0].min()) + x_hi = max((tx + 1) * tile_size, math.ceil(b[:, 2].max()) + 1) + y_lo = min(ty * tile_size, b[:, 1].min()) + y_hi = max((ty + 1) * tile_size, math.ceil(b[:, 3].max()) + 1) + x0, x1 = _axis(math.floor(x_lo), math.ceil(x_hi), margin, min_window, w) + y0, y1 = _axis(math.floor(y_lo), math.ceil(y_hi), margin, min_window, h) + windows[(int(tx), int(ty))] = (y0, y1, x0, x1) + return windows + + +def label_window(geoms, labels, window): + """int32 label image of every geom intersecting the window; labels must be > 0.""" + import numpy as np + from aggregate_compartments import pixel_outer_bounds, rasterize + + y0, y1, x0, x1 = window + out = np.zeros((y1 - y0, x1 - x0), dtype=np.int32) + for geom, label in zip(geoms, labels, strict=True): + # same outer bounds as aggregation (polygon() includes boundary pixels), clipped to the window + gx0, gy0, gx1, gy1 = pixel_outer_bounds(geom.bounds) + bx0, bx1, by0, by1 = max(gx0, x0), min(gx1, x1), max(gy0, y0), min(gy1, y1) + if bx1 <= bx0 or by1 <= by0: + continue + mask = rasterize(geom, (by1 - by0, bx1 - bx0), (bx0, by0)) + sub = out[by0 - y0 : by1 - y0, bx0 - x0 : bx1 - x0] + sub[mask > 0] = label + return out + + +def normalisation_factors(image, channel_names, quantile=QUANTILE, max_pixels=50_000_000): + """Per-channel quantile of nonzero pixels on a strided grid; None where a channel is all zero.""" + import numpy as np + + _, h, w = image.shape + s = max(1, math.ceil(math.sqrt(h * w / max_pixels))) + factors = {} + for c, name in enumerate(channel_names): + sub = np.asarray(image[c, ::s, ::s]) + nz = sub[sub > 0] + factors[name] = float(np.quantile(nz, quantile)) if nz.size else None + return factors + + +def cell_means(labels, prediction, wanted): + """Mean of prediction over each wanted label's pixels; NaN where a label has no pixel.""" + import numpy as np + + wanted = np.asarray(wanted) + n = int(max(labels.max(), wanted.max())) + 1 + flat = labels.ravel() + counts = np.bincount(flat, minlength=n) + sums = np.bincount(flat, weights=np.asarray(prediction, dtype=np.float64).ravel(), minlength=n) + with np.errstate(invalid="ignore", divide="ignore"): + means = sums[wanted] / counts[wanted] + return np.where(counts[wanted] > 0, means, np.nan) + + +def score_cells(image, geoms, cell_labels, channel_names, factors, predict, tile_size, margin, min_window): + """(n_cells, n_channels) float32 scores in geoms order; each cell scored once, in its centroid's tile.""" + import numpy as np + import shapely + + # a missing factor must never fall back to a per-window quantile + missing = [c for c in channel_names if c not in factors] + if missing: + raise KeyError(f"no normalisation factor for channels: {missing}") + + cell_labels = np.asarray(cell_labels) + out = np.full((len(geoms), len(channel_names)), np.nan, dtype=np.float32) + if not len(geoms): + return out + # empty or None geoms are skipped (rows stay NaN), as in aggregation + valid = np.array([g is not None and not g.is_empty for g in geoms], dtype=bool) + if not valid.any(): + return out + garr = np.asarray(geoms, dtype=object) + vidx = np.flatnonzero(valid) + centroids = np.array([(garr[i].centroid.x, garr[i].centroid.y) for i in vidx]) + bounds = np.array([garr[i].bounds for i in vidx]) + tiles = assign_tiles(centroids, tile_size) + windows = tile_windows(bounds, tiles, tile_size, margin, min_window, image.shape[1:]) + tree = shapely.STRtree(garr[vidx]) + + for tile, (y0, y1, x0, x1) in windows.items(): + owned = vidx[(tiles == tile).all(axis=1)] + near = vidx[tree.query(shapely.box(x0, y0, x1, y1), predicate="intersects")] + labels = label_window(garr[near], cell_labels[near], (y0, y1, x0, x1)) + for c, name in enumerate(channel_names): + factor = factors[name] + if factor is None: + continue + window = np.asarray(image[c, y0:y1, x0:x1], dtype=np.float32) + normalised = np.clip(window / factor, 0, 1) + pred = predict(name, normalised, labels) + out[owned, c] = cell_means(labels, pred, cell_labels[owned]) + return out + + +def magnification(pixel_size): + """Upstream magnification of an image of pixel_size um/px, derived from MODEL_UM_PER_PX.""" + return MODEL_MAGNIFICATION / resize_scale(pixel_size) + + +def load_nimbus(device, batch_size=4): + """Nimbus with V1.pt as a valid-padding model; weights come from the image, never the network.""" + from nimbus_inference.nimbus import Nimbus + + nimbus = Nimbus( + dataset=None, + output_dir="", + save_predictions=False, + batch_size=batch_size, + test_time_aug=True, + model_magnification=MODEL_MAGNIFICATION, + device=device, + checkpoint=WEIGHTS, + ) + nimbus.load_checkpoint(padding="valid") + return nimbus + + +def model_halo(nimbus): + """Model px lost per side by the valid model after upstream's crop_by (96 for V1).""" + import numpy as np + import torch + + side = np.array(nimbus.input_shape) + with torch.no_grad(): + out = np.array(nimbus.model(torch.rand(1, 2, *side).to(nimbus.device)).shape[-2:]) + out = out - out % 2**5 + halo = (side - out) // 2 + return int(halo.max()) + + +def nimbus_predictor(nimbus, pixel_size, batch_size=4): + """predict(channel, normalised, labels) -> probability map, mirroring upstream predict_fovs per channel.""" + import cv2 + import numpy as np + from nimbus_inference.utils import prepare_binary_mask, prepare_input_data, test_time_aug + + scale = resize_scale(pixel_size) + + def predict(channel, normalised, labels): + h, w = normalised.shape + binary = prepare_binary_mask(labels) + img = normalised + if scale != 1: + size = (int(w * scale), int(h * scale)) # int() as upstream predict_fovs + img = cv2.resize(normalised, size) + binary = cv2.resize(binary, size, interpolation=cv2.INTER_NEAREST) + data = prepare_input_data(img, binary_mask=binary) + # the image is already normalised, so upstream's factor argument is unused here + pred = test_time_aug(data, channel, nimbus, normalization_dict={channel: 1.0}, batch_size=batch_size) + if not isinstance(pred, np.ndarray): + pred = pred.cpu().numpy() + pred = np.squeeze(pred) + if scale != 1: + pred = cv2.resize(pred, (w, h), interpolation=cv2.INTER_NEAREST) + assert pred.shape == (h, w), f"prediction shape {pred.shape} != window shape {(h, w)}" + return pred + + return predict + + +def build_table(scores, channels, obs, region, provenance): + """AnnData of scores (cells x channels) with the source table's obs, parsed as a SpatialData table.""" + import pandas as pd + from anndata import AnnData + from spatialdata.models import TableModel + + adata = AnnData(scores.astype("float32"), obs=obs.copy(), var=pd.DataFrame(index=pd.Index(channels))) + adata.uns["nimbus"] = provenance + return TableModel.parse(adata, region=region, region_key="region", instance_key="cell_id") + + +def parse_args(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--sdata", required=True, help="SpatialData store; only read") + parser.add_argument( + "--method", required=True, help="segmentation method; reads {method}_cells and {method}_table" + ) + parser.add_argument("--channels", required=True, help="comma-separated image channels to score") + parser.add_argument("--pixel-size", type=float, required=True, help="image um/px") + parser.add_argument("--device", default="cpu", choices=["cpu", "cuda"]) + parser.add_argument("--output", required=True, help="h5ad file to write") + parser.add_argument("--provenance", required=True, help="JSON file to write") + args = parser.parse_args(argv) + if args.pixel_size <= 0: + parser.error("--pixel-size must be positive") + args.channels = [c for c in args.channels.split(",") if c] + if not args.channels or len(set(args.channels)) != len(args.channels): + parser.error("--channels needs at least one name, each once") + return args + + +def sha256(path): + h = hashlib.sha256() + with Path(path).open("rb") as f: + for chunk in iter(lambda: f.read(1 << 20), b""): + h.update(chunk) + return h.hexdigest() + + +def main(argv=None, predict=None, halo=None) -> int: + """predict and halo are injected by tests; otherwise the real model is loaded.""" + import numpy as np + import spatialdata as sd + + from resolve_segmentation import store_image_key + + args = parse_args(argv) + sdata = sd.read_zarr(args.sdata) + image = sdata.images[store_image_key(args.sdata)] + if hasattr(image, "children"): # multiscale: full resolution is scale0 + image = image["scale0"]["image"] + available = [str(c) for c in image.coords["c"].values] + unknown = [c for c in args.channels if c not in available] + if unknown: + print(f"[nimbus] unknown channels {unknown}; the store has {available}", file=sys.stderr) + sys.exit(1) + image = image.sel(c=args.channels) # score_cells indexes channels by position + + table = sdata.tables[f"{args.method}_table"] + shapes = sdata.shapes[f"{args.method}_cells"] + names = [str(n) for n in table.obs_names] + by_id = shapes.set_axis(shapes.index.astype(str)) + missing = [n for n in names if n not in by_id.index] + if missing: + sys.exit(f"[nimbus] {len(missing)} table cells have no shape, e.g. {missing[:3]}") + geoms = list(by_id.loc[names].geometry) + labels = np.arange(1, len(names) + 1) # compact, as cell_means sizes its bincount by the largest label + + weights_sha = "" + if predict is None: + nimbus = load_nimbus(args.device) + predict = nimbus_predictor(nimbus, args.pixel_size) + halo = model_halo(nimbus) + weights_sha = sha256(nimbus.checkpoint_path) + tile = image_px(TILE_MODEL_PX, args.pixel_size) + margin = image_px(halo + MARGIN_EXTRA_MODEL_PX, args.pixel_size) + min_window = image_px(MIN_WINDOW_MODEL_PX, args.pixel_size) + + factors = normalisation_factors(image, args.channels) + scores = score_cells(image, geoms, labels, args.channels, factors, predict, tile, margin, min_window) + + try: + from importlib.metadata import PackageNotFoundError, version + + nimbus_version = version("Nimbus-Inference") + except PackageNotFoundError: + nimbus_version = "unknown" + provenance = { + "nimbus_version": nimbus_version, + "weights": WEIGHTS, + "weights_sha256": weights_sha, + "channels": args.channels, + "factors": {c: f for c, f in factors.items() if f is not None}, + "unscored": [c for c, f in factors.items() if f is None], + "pixel_size": args.pixel_size, + "model_um_per_px": MODEL_UM_PER_PX, + "magnification": magnification(args.pixel_size), + "tile_size": tile, + "margin": margin, + "halo": halo, + "min_window": min_window, + "test_time_aug": True, + "device": args.device, + } + obs = table.obs[[c for c in ("region", "slide", "core_id", "cell_id") if c in table.obs.columns]] + out = build_table(scores, args.channels, obs, f"{args.method}_cells", provenance) + out.write_h5ad(args.output) + Path(args.provenance).write_text(json.dumps(provenance, indent=2)) + print( + f"[nimbus] {args.method}: {out.n_obs} cells x {len(args.channels)} channels, unscored {provenance['unscored']}" + ) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/bin/project_channels.py b/bin/project_channels.py index 3f454a5..43646e6 100755 --- a/bin/project_channels.py +++ b/bin/project_channels.py @@ -311,7 +311,7 @@ def main() -> int: p.add_argument("--low-percentile", type=float, default=1.0, help="maps to 0 (default: 1)") p.add_argument("--high-percentile", type=float, default=99.9, help="maps to 1 (default: 99.9)") p.add_argument( - "--sigma", type=float, default=1.0, help="Gaussian sigma in pixels, 0 for none (default: 1)" + "--sigma", type=float, default=0.0, help="Gaussian sigma in pixels, 0 for none (default: 0)" ) args = ap.parse_args() diff --git a/bin/qc_metrics.py b/bin/qc_metrics.py index ffce433..83e3683 100755 --- a/bin/qc_metrics.py +++ b/bin/qc_metrics.py @@ -18,6 +18,10 @@ PERCENTILES = (1.0, 25.0, 50.0, 75.0, 99.0, 99.9, 99.99) +# Nimbus scores are probabilities; a cell above this counts as positive for the marker. +NIMBUS_THRESHOLD = 0.5 + + def percentiles_from_histogram(hist: Any, percentiles: tuple[float, ...] = PERCENTILES) -> dict[str, float]: """Exact percentiles from a full-range histogram where `hist[v]` counts pixels of value `v`. @@ -479,6 +483,49 @@ def open_table(sdata_path: Path, name: str) -> Any: return zarr.open_group(str(path), mode="r") +def nimbus_metrics(X: Any, markers: list[str], threshold: float = 0.5) -> dict[str, Any]: + """Per marker, the fraction of scored cells above `threshold` and the median score.""" + import numpy as np + + X = np.asarray(X, dtype=np.float64) + out: dict[str, Any] = {} + for i, marker in enumerate(markers): + col = X[:, i] + col = col[~np.isnan(col)] + # None, not NaN, for an unscored marker: JSON has no NaN. + out[marker] = ( + {"fraction_positive": None, "median": None} + if col.size == 0 + else {"fraction_positive": float((col > threshold).mean()), "median": float(np.median(col))} + ) + return out + + +def read_uns(node: Any) -> Any: + """Read an AnnData `uns` element (nested dicts, scalars, arrays) into plain Python.""" + import zarr + + if isinstance(node, zarr.Group): + return {k: read_uns(node[k]) for k in node} + if node.shape == (): + value = node[()] + return value.item() if hasattr(value, "item") else value + return [v.item() if hasattr(v, "item") else v for v in node[:]] + + +def virtues_metrics(uns: dict[str, Any], method: str) -> dict[str, Any]: + """The VirTues facts the report shows, for one segmentation `method`.""" + return { + "channels": sorted(uns["channels"]), + "unembedded": list(uns["unembedded"]), + "stats": uns["stats"], + "n_cells": int(uns["n_cells"][method]), + "n_cells_without_pixel": int(uns["n_cells_without_pixel"][method]), + "n_niches_kept": int(uns["n_niches_kept"]), + "n_niches_dropped": int(uns["n_niches_dropped"]), + } + + def collect( sdata_path: Path, table: str, @@ -488,8 +535,10 @@ def collect( nuclear_pattern: str | None = None, before_image: Path | None = None, histogram_range: str = "channels-max", + nimbus_table: str | None = None, + virtues_table: str | None = None, ) -> dict[str, Any]: - """Every metric for one sample; `before_image` and `marker_rows` add optional sections.""" + """Every metric for one sample; `before_image`, `marker_rows` and `nimbus_table` add optional sections.""" import numpy as np import pyarrow.parquet as pq import zarr @@ -662,6 +711,18 @@ def collect( # None, not zero, so "not tiled" differs from "tiled and empty". out["patches"] = None + if nimbus_table: + nimbus = open_table(sdata_path, nimbus_table) + out["nimbus"] = nimbus_metrics( + nimbus["X"][:], [str(m) for m in read_column(nimbus["var"]["_index"])], NIMBUS_THRESHOLD + ) + + if virtues_table: + virtues = open_table(sdata_path, virtues_table) + out["virtues"] = virtues_metrics( + read_uns(virtues["uns"]["virtues"]), virtues_table.removesuffix("_virtues") + ) + return out @@ -701,6 +762,16 @@ def main() -> int: "this only for a sheet with no channel_role column, or to override a wrong one. " f"Without either, falls back to matching {DEFAULT_NUCLEAR_PATTERN!r}.", ) + ap.add_argument( + "--nimbus-table", + default=None, + help="name of the Nimbus table under tables/, e.g. cellpose_nimbus; adds per-marker positivity", + ) + ap.add_argument( + "--virtues-table", + default=None, + help="name of the VirTues table under tables/, e.g. cellpose_virtues; adds its provenance facts", + ) args = ap.parse_args() markers = None @@ -721,6 +792,8 @@ def main() -> int: nuclear_pattern=args.nuclear_pattern, before_image=args.before_image, histogram_range=args.histogram_range, + nimbus_table=args.nimbus_table, + virtues_table=args.virtues_table, ) args.out.write_text(json.dumps(metrics, indent=2, sort_keys=False) + "\n") diff --git a/bin/qc_report.py b/bin/qc_report.py index 4041355..da493c3 100755 --- a/bin/qc_report.py +++ b/bin/qc_report.py @@ -860,6 +860,52 @@ def linking_section(linking: dict[str, Any]) -> str: """ +def nimbus_section(nimbus: dict[str, Any]) -> str: + """Per marker, the share of cells Nimbus calls positive and its median score.""" + rows = [ + [ + esc(marker), + "n/a" if v["fraction_positive"] is None else f"{v['fraction_positive'] * 100:.1f}%", + "n/a" if v["median"] is None else f"{v['median']:.2f}", + ] + for marker, v in nimbus.items() + ] + return f""" +
+

Nimbus marker scores

+

Nimbus scores each cell for each marker from 0 (absent) to 1 (present). + A cell above 0.5 counts as positive. Cells Nimbus could not score are left out; + “n/a” means no cell was scored for that marker.

+ {table(["Marker", "Cells positive", "Median score"], rows)} +
+""" + + +def virtues_section(v: dict[str, Any]) -> str: + """VirTues facts: channels embedded, per-marker statistics, cells and squares counted.""" + rows = [ + [ + esc(m), + esc(str(e["uniprot_id"])), + f"{e['cap']:g}", + f"{e['mean']:.3g}", + f"{e['sd']:.3g}", + f"{e['tissue_pixels']:,}", + ] + for m, e in v["stats"].items() + ] + unembedded = ", ".join(esc(m) for m in v["unembedded"]) or "none" + return f""" +
+

VirTues embeddings

+

Cells embedded: {v["n_cells"]:,} ({v["n_cells_without_pixel"]:,} without a pixel). + Tissue squares kept: {v["n_niches_kept"]:,}, dropped: {v["n_niches_dropped"]:,}. + Channels not embedded: {unembedded}.

+ {table(["Marker", "UniProt", "Cap", "Mean", "SD", "Tissue pixels"], rows)} +
+""" + + def inline_png(path: Path) -> str: """Return a PNG or JPEG file as a base64 data URI.""" import base64 @@ -1804,6 +1850,9 @@ def build( {linking_section(metrics["linking"]) if metrics.get("linking") else ""} +{nimbus_section(metrics["nimbus"]) if "nimbus" in metrics else ""} +{virtues_section(metrics["virtues"]) if "virtues" in metrics else ""} + {patch_block} {crops_section(images, asset_dir) if images and asset_dir else ""} diff --git a/bin/segment_patch.py b/bin/segment_patch.py index 22d0772..4bcb77d 100755 --- a/bin/segment_patch.py +++ b/bin/segment_patch.py @@ -11,6 +11,7 @@ import argparse import ast import json +import os import shutil import sys import tempfile @@ -20,14 +21,15 @@ METHOD_BUILDERS = {"cellpose": "cellpose_patch", "instanseg": "instanseg_patch"} # The builders name the device choice differently. DEVICE_ARGUMENT = {"cellpose": "gpu", "instanseg": "device"} -# Defaults copied from sopa 2.3.0 cli/segmentation.py, so unset params segment as the CLI does. +# Defaults for unset params: sopa 2.3.0 cli/segmentation.py, except Cellpose's thresholds and +# preprocessing, which come from tools/segmentation_benchmark (docs/decisions.md#segmentation-benchmark). METHOD_DEFAULTS = { # cli/segmentation.py:18-27 (diameter has no default; gpu is set by --device) "cellpose": { - "flow_threshold": 2, - "cellprob_threshold": -6, + "flow_threshold": 0.6, # ours; sopa 2 + "cellprob_threshold": -1, # ours; sopa -6 "model_type": "cyto3", - "pretrained_model": None, + "pretrained_model": "cpsam_v2", # ours, not sopa's (None) "gpu": False, }, # cli/segmentation.py:148-158 (device is set by --device) @@ -40,7 +42,8 @@ } SEGMENTATION_DEFAULTS = { # cli/segmentation.py:28-39 (cellpose) and :160-172 (instanseg) - "cellpose": {"min_area": 0, "clip_limit": 0.2, "clahe_kernel_size": None, "gaussian_sigma": 1}, + # clip_limit and gaussian_sigma are ours; sopa 0.2 and 1 + "cellpose": {"min_area": 0, "clip_limit": 0, "clahe_kernel_size": None, "gaussian_sigma": 0}, "instanseg": {"min_area": 0, "clip_limit": 0, "clahe_kernel_size": None, "gaussian_sigma": 0}, } @@ -109,6 +112,21 @@ def method_arguments(spec: dict) -> dict: return kwargs +def check_weights(pretrained_model: str | None, models_dir: str | None) -> None: + """Fail naming the model: cellpose silently loads its default for an unknown name, then downloads.""" + if not pretrained_model or Path(pretrained_model).exists(): + return + if not models_dir: + raise ValueError( + f"pretrained_model '{pretrained_model}' is a name but CELLPOSE_LOCAL_MODELS_PATH is not set" + ) + if not (Path(models_dir) / pretrained_model).is_file(): + raise ValueError( + f"pretrained_model '{pretrained_model}' has no weights in CELLPOSE_LOCAL_MODELS_PATH ({models_dir}); " + "use a name baked into the image or a path" + ) + + def segmentation_arguments(spec: dict) -> dict: """StainingSegmentation keyword arguments: per-method CLI defaults, then the spec's segmentation_kwargs.""" _check_method(spec["method"]) @@ -129,6 +147,8 @@ def main() -> int: spec = json.loads(Path(args.spec).read_text()) kwargs = method_arguments(spec) # first: a bad {method}_kwargs fails before the store is read + if spec["method"] == "cellpose": + check_weights(kwargs.get("pretrained_model"), os.environ.get("CELLPOSE_LOCAL_MODELS_PATH")) sdata = read_zarr_standardized(args.sdata) key = image_key_for(sdata.attrs, spec["image"]) require_image(key, sdata.images, spec["image"]) diff --git a/bin/virtues_cells.py b/bin/virtues_cells.py new file mode 100755 index 0000000..1dbacef --- /dev/null +++ b/bin/virtues_cells.py @@ -0,0 +1,559 @@ +#!/usr/bin/env python3 +"""VirTues cell, niche and tissue embeddings, in tile windows so image size does not limit memory. + +The tiling core is model-free and tested with a fake encoder; load_virtues, virtues_encoder and the +CLI add the model. Coordinates are model px (1 um/px); "padded" coordinates shift them by PAD, as +upstream pads before cutting crops. torch, virtues and esm are imported inside functions, so the +core imports without them. +""" + +import argparse +import hashlib +import json +import os +import sys +from collections.abc import Callable +from dataclasses import dataclass +from pathlib import Path + +import numpy as np + +from virtues_stats import ( + MODEL_UM_PER_PX, + load_stats, + model_shape, + resample_window, + tissue_mask, + tissue_polygons, + to_image_pixels, +) + +CROP = 128 +PATCH = 8 +STEP = 42 +PAD = 120 +TILE = 2048 +BATCH = 32 +NICHE_MIN_TISSUE = 0.30 +BLUR_SIGMA = 1.0 +GRID = CROP // PATCH # patches per crop side +EMBED_DIM = 512 +ESM_MODEL = "esm2_t30_150M_UR50D" + +_K = np.exp(-0.5 * (np.array([-1.0, 0.0, 1.0]) / BLUR_SIGMA) ** 2) +BLUR_KERNEL = (_K / _K.sum()).astype(np.float32) # torchvision v2.GaussianBlur(3, 1.0), 1D +# patch index of each pixel in a crop, row-major as the encoder's 16 x 16 tokens +_PATCH_OF_PIXEL = (np.arange(CROP)[:, None] // PATCH * GRID + np.arange(CROP)[None, :] // PATCH).ravel() + + +def _crop_starts(n): + """Upstream's crop starts along one axis: every STEP, plus one flush with the far edge.""" + return sorted(set(range(0, n - CROP + 1, STEP)) | {n - CROP}) + + +def uniform_crops(h, w): + """Sorted crop origins of upstream _get_uniform_crops(img, STEP, CROP) for an h x w padded image.""" + return [(i, j) for i in _crop_starts(h) for j in _crop_starts(w)] + + +def model_input(read_raw, stats, y0, y1, x0, x1, padded_shape): + """Standardised, blurred float32 (c, y1 - y0, x1 - x0) in padded coordinates.""" + cap, mean, sd = (np.asarray(stats[k], dtype=np.float32)[:, None, None] for k in ("cap", "mean", "sd")) + h, w = padded_shape[0] - 2 * PAD, padded_shape[1] - 2 * PAD + # one pixel more on each side feeds the blur; zeros outside the image are upstream's pad + ey0, ex0 = y0 - 1 - PAD, x0 - 1 - PAD + raw = np.zeros((len(cap), y1 - y0 + 2, x1 - x0 + 2), dtype=np.float32) + ry0, ry1 = max(ey0, 0), min(y1 + 1 - PAD, h) + rx0, rx1 = max(ex0, 0), min(x1 + 1 - PAD, w) + if ry1 > ry0 and rx1 > rx0: + for c in range(len(cap)): + raw[c, ry0 - ey0 : ry1 - ey0, rx0 - ex0 : rx1 - ex0] = read_raw(c, ry0, ry1, rx0, rx1) + z = (np.log1p(np.minimum(raw, cap)) - mean) / sd + k0, k1, k2 = BLUR_KERNEL + z = k0 * z[:, :-2] + k1 * z[:, 1:-1] + k2 * z[:, 2:] + return (k0 * z[:, :, :-2] + k1 * z[:, :, 1:-1] + k2 * z[:, :, 2:]).astype(np.float32) + + +@dataclass +class CellSource: + """One segmentation method's cells, labels 1..n, all in padded coordinates.""" + + read_labels: Callable # (y0, y1, x0, x1) -> int32 labels, 0 for background + centroids: np.ndarray # (n, 2) y, x + bboxes: np.ndarray # (n, 4) y0, y1, x0, x1 + + +def label_reader(geoms, pixel_size): + """read_labels(y0, y1, x0, x1) in padded coordinates; geoms in image coordinates, the earlier wins.""" + from shapely import STRtree + from shapely.geometry import box + + tree = STRtree(geoms) + + def read_labels(y0, y1, x0, x1): + labels = np.zeros((y1 - y0, x1 - x0), dtype=np.int32) + my0, my1, mx0, mx1 = y0 - PAD, y1 - PAD, x0 - PAD, x1 - PAD + window = box(mx0 / pixel_size, my0 / pixel_size, mx1 / pixel_size, my1 / pixel_size) + for i in np.sort(tree.query(window)): + gx0, gy0, gx1, gy1 = geoms[i].bounds + # model pixels whose centre can lie inside the geom's bounds + ky0 = max(int(np.ceil(gy0 * pixel_size - 0.5)), my0) + ky1 = min(int(np.floor(gy1 * pixel_size - 0.5)) + 1, my1) + kx0 = max(int(np.ceil(gx0 * pixel_size - 0.5)), mx0) + kx1 = min(int(np.floor(gx1 * pixel_size - 0.5)) + 1, mx1) + if ky1 <= ky0 or kx1 <= kx0: + continue + inside = tissue_mask([geoms[i]], ky0, ky1, kx0, kx1, pixel_size) + region = labels[ky0 - my0 : ky1 - my0, kx0 - mx0 : kx1 - mx0] + region[inside & (region == 0)] = i + 1 + return labels + + return read_labels + + +def _embed_dim(read_input, encode): + """Embedding size D, from an empty batch, for outputs with no rows.""" + c = read_input(0, 0, 0, 0).shape[0] + return encode(np.zeros((0, c, CROP, CROP), dtype=np.float32)).shape[-1] + + +def _crop_mask(rows, cols, bboxes): + """Bool (len(rows), len(cols)): crops whose box meets any bbox (y0, y1, x0, x1).""" + ri0 = np.searchsorted(rows, bboxes[:, 0] - CROP, side="right") + ri1 = np.searchsorted(rows, bboxes[:, 1], side="left") + ci0 = np.searchsorted(cols, bboxes[:, 2] - CROP, side="right") + ci1 = np.searchsorted(cols, bboxes[:, 3], side="left") + ok = (ri1 > ri0) & (ci1 > ci0) + ri0, ri1, ci0, ci1 = ri0[ok], ri1[ok], ci0[ok], ci1[ok] + # 2D difference array: each bbox adds 1 over its rectangle of crops + diff = np.zeros((len(rows) + 1, len(cols) + 1), dtype=np.int64) + np.add.at(diff, (ri0, ci0), 1) + np.add.at(diff, (ri0, ci1), -1) + np.add.at(diff, (ri1, ci0), -1) + np.add.at(diff, (ri1, ci1), 1) + return diff.cumsum(0).cumsum(1)[:-1, :-1] > 0 + + +def _crop_cells(labels, tokens): + """Cells in one crop: ids, float32 (p, D) sums of count x token, int64 pixel counts.""" + lab = labels.ravel() + fg = lab > 0 + if not fg.any(): + return None + # sorted by cell then patch, so each cell's sum adds its patches in a fixed order + keys, counts = np.unique(lab[fg].astype(np.int64) * GRID * GRID + _PATCH_OF_PIXEL[fg], return_counts=True) + cells, patches = keys // (GRID * GRID), keys % (GRID * GRID) + starts = np.flatnonzero(np.r_[True, cells[1:] != cells[:-1]]) + vals = counts[:, None].astype(np.float32) * tokens[patches] + return cells[starts], np.add.reduceat(vals, starts, axis=0), np.add.reduceat(counts, starts) + + +def cell_embeddings(read_input, sources, padded_shape, encode, tile=TILE, batch=BATCH): + """Per method (emb float32 (n, D), weight float64 (n,)), NaN rows where the weight is 0.""" + rows, cols = np.array(_crop_starts(padded_shape[0])), np.array(_crop_starts(padded_shape[1])) + nx = -(-padded_shape[1] // tile) + owner = { + m: (s.centroids[:, 0] // tile * nx + s.centroids[:, 1] // tile).astype(np.int64) + for m, s in sources.items() + } + sums = dict.fromkeys(sources) + weights = {m: np.zeros(len(s.centroids), dtype=np.float64) for m, s in sources.items()} + tiles = np.unique(np.concatenate([np.zeros(0, np.int64), *owner.values()])) + for t in tiles: + owned = {m: owner[m] == t for m in sources} + bboxes = np.concatenate([np.asarray(s.bboxes)[owned[m]] for m, s in sources.items()]) + mask = _crop_mask(rows, cols, bboxes) + if not mask.any(): + continue + ri, ci = np.nonzero(mask) # row-major, upstream's sorted order + wy0, wy1 = rows[ri.min()], rows[ri.max()] + CROP + wx0, wx1 = cols[ci.min()], cols[ci.max()] + CROP + x = read_input(wy0, wy1, wx0, wx1) + labels = {m: s.read_labels(wy0, wy1, wx0, wx1) for m, s in sources.items() if owned[m].any()} + for b in range(0, len(ri), batch): + origins = [ + (rows[i] - wy0, cols[j] - wx0) + for i, j in zip(ri[b : b + batch], ci[b : b + batch], strict=False) + ] + crops = np.stack([x[:, y : y + CROP, xx : xx + CROP] for y, xx in origins]) + tokens = encode(crops).reshape(len(origins), GRID * GRID, -1) + for (y, xx), tok in zip(origins, tokens, strict=False): + for m, lab in labels.items(): + found = _crop_cells(lab[y : y + CROP, xx : xx + CROP], tok) + if found is None: + continue + ids, vals, counts = found + keep = owned[m][ids - 1] # only this tile's cells, so each cell is summed once + if sums[m] is None: + sums[m] = np.zeros((len(weights[m]), tok.shape[-1]), dtype=np.float32) + sums[m][ids[keep] - 1] += vals[keep] + weights[m][ids[keep] - 1] += counts[keep] + del x, labels + out = {} + for m in sources: + if sums[m] is None: + sums[m] = np.zeros((len(weights[m]), _embed_dim(read_input, encode)), dtype=np.float32) + emb, has = sums[m], weights[m][:, None] > 0 + np.divide(emb, weights[m][:, None], out=emb, where=has) # in place: no (n, D) float64 copy + emb[~has[:, 0]] = np.nan + out[m] = (emb, weights[m]) + return out + + +def niche_embeddings(read_input, read_tissue, image_shape_model, encode, batch=BATCH): + """Kept squares' model origins, tissue fractions and float32 (k, D) patch-mean embeddings.""" + h, w = (n // CROP * CROP for n in image_shape_model) # squares fully inside the image + origins, fractions, embeddings, pending = [], [], [], [] + + def flush(): + tokens = encode(np.stack(pending)) + embeddings.append(tokens.reshape(len(pending), GRID * GRID, -1).mean(axis=1)) + pending.clear() + + for ty in range(0, h, TILE): + for tx in range(0, w, TILE): # one tile window at a time + y1, x1 = min(ty + TILE, h), min(tx + TILE, w) + tissue = read_tissue(ty, y1, tx, x1) + frac = tissue.reshape((y1 - ty) // CROP, CROP, (x1 - tx) // CROP, CROP).mean(axis=(1, 3)) + if not (frac >= NICHE_MIN_TISSUE).any(): + continue + x = read_input(ty + PAD, y1 + PAD, tx + PAD, x1 + PAD) + for i, j in zip(*np.nonzero(frac >= NICHE_MIN_TISSUE), strict=False): + origins.append((ty + i * CROP, tx + j * CROP)) + fractions.append(frac[i, j]) + pending.append(x[:, i * CROP : (i + 1) * CROP, j * CROP : (j + 1) * CROP].copy()) + if len(pending) == batch: + flush() + del x + if pending: + flush() + if not origins: + return [], np.zeros(0), np.zeros((0, _embed_dim(read_input, encode)), dtype=np.float32) + emb = np.concatenate(embeddings).astype(np.float32) + order = sorted(range(len(origins)), key=origins.__getitem__) # grid order across tiles + return [origins[i] for i in order], np.asarray(fractions, dtype=np.float64)[order], emb[order] + + +def tissue_embedding(niches): + """Mean of the niche rows; NaN (D,) when there are none.""" + if len(niches) == 0: + return np.full(niches.shape[1], np.nan, dtype=np.float32) + return niches.astype(np.float64).mean(axis=0).astype(np.float32) + + +# --- model --- + + +def uniprot_sequences(fasta, ids): + """Sequences for ids from a UniProt FASTA (headers >sp|ACC|...); KeyError names absent IDs.""" + wanted, seqs, current = set(ids), {}, None + with Path(fasta).open() as f: + for line in f: + if line.startswith(">"): + acc = line.split("|")[1] if line.count("|") >= 2 else None + current = acc if acc in wanted else None + if current is not None: + seqs[current] = [] + elif current is not None: + seqs[current].append(line.strip()) + missing = [i for i in ids if i not in seqs] + if missing: + raise KeyError(f"UniProt IDs {missing} are not in {fasta}") + return {i: "".join(seqs[i]) for i in ids} + + +def esm_embeddings(sequences, device): + """float32 (n, 640) ESM-2 marker embeddings: upstream ESMWrapper's model and its mean over residues.""" + import torch + from virtues.utils.compute_esm_embeddings import ESMWrapper + + esm = ESMWrapper(ESM_MODEL, device) + layer = esm.model.num_layers + out = [] + for seq in sequences: + _, _, tokens = esm.batch_converter([("marker", seq)]) + with torch.no_grad(): + # ESMWrapper.embed without return_contacts: its attention maps for Ki-67 (3256 aa) exceed an A40 + rep = esm.model(tokens.to(device), repr_layers=[layer])["representations"][layer] + out.append(rep[0, 1 : len(seq) + 1].mean(0).float().cpu()) + del esm + return torch.stack(out) + + +def build_model(weights, prior_bias_embeddings, device): + """MultiplexVirtues with these marker embeddings (row i = channel i) and the weights, in eval mode.""" + from safetensors.torch import load_file + from virtues.modules.multiplex_virtues import MultiplexVirtues + + model = MultiplexVirtues(prior_bias_embeddings=prior_bias_embeddings) + model.load_state_dict(load_file(str(weights))) + return model.to(device).eval() + + +def load_virtues(weights, sequences, device): + """The model, with ESM-2 embeddings of the channels' sequences in channel order.""" + return build_model(weights, esm_embeddings(sequences, device), device) + + +def virtues_encoder(model, n_channels, device): + """encode(crops float32 (n, c, 128, 128)) -> patch summary tokens float32 (n, 16, 16, 512), as upstream.""" + import torch + + channels = torch.arange(n_channels, device=device) + + def encode(crops): + if len(crops) == 0: # the core asks with an empty batch for the embedding size + return np.zeros((0, GRID, GRID, EMBED_DIM), dtype=np.float32) + x = torch.from_numpy(np.ascontiguousarray(crops, dtype=np.float32)).to(device) + with torch.no_grad(), torch.amp.autocast("cuda", enabled=True): + out = model.encoder.forward_list(list(x), [channels] * len(crops), multiplex_mask=None) + return torch.stack(out.patch_summary_tokens).float().cpu().numpy() + + return encode + + +# --- CLI --- + +OBS_COLUMNS = ("region", "slide", "core_id", "cell_id") + + +def cell_source(geoms, pixel_size, model_hw): + """CellSource for image-coordinate geoms, clipped to the model grid so no label falls outside it.""" + import shapely + + geoms = np.asarray(geoms, dtype=object) + extent = shapely.box(0, 0, model_hw[1] / pixel_size, model_hw[0] / pixel_size) + # clip only cells crossing the edge, so interior geometries stay bit-identical + out = ~shapely.covered_by(geoms, extent) + geoms = geoms.copy() + if out.any(): + geoms[out] = shapely.intersection(geoms[out], extent) + b = shapely.bounds(geoms).reshape(-1, 4) # minx, miny, maxx, maxy; NaN when empty + empty = np.isnan(b).any(axis=1) + centroids = np.zeros((len(geoms), 2)) + c = shapely.centroid(geoms[~empty]) + centroids[~empty] = np.stack([shapely.get_y(c), shapely.get_x(c)], axis=-1) * pixel_size + PAD + # rounded outward, so the box holds every pixel centre inside the cell + k = b * pixel_size # minx, miny, maxx, maxy in model px + bboxes = ( + np.stack([np.floor(k[:, 1]), np.ceil(k[:, 3]), np.floor(k[:, 0]), np.ceil(k[:, 2])], axis=-1) + PAD + ) + bboxes[empty] = 0 # no pixel: an empty box selects no crop + return CellSource(label_reader(list(geoms), pixel_size), centroids, bboxes) + + +def stats_arrays(entries, names): + """cap, mean, sd arrays in channel order, from load_stats' per-marker entries.""" + return {k: np.array([entries[n][k] for n in names], dtype=np.float64) for k in ("cap", "mean", "sd")} + + +def build_table(x, obs, provenance, region=None, instance_key=None): + """float16 AnnData with virtues_0 ... columns, parsed as a SpatialData table.""" + import pandas as pd + from anndata import AnnData + from spatialdata.models import TableModel + + var = pd.DataFrame(index=pd.Index([f"virtues_{i}" for i in range(x.shape[1])])) + adata = AnnData(x.astype(np.float16), obs=obs.copy(), var=var) + adata.uns["virtues"] = provenance + if region is None: + return TableModel.parse(adata) + return TableModel.parse(adata, region=region, region_key="region", instance_key=instance_key) + + +def sha256(path): + with Path(path).open("rb") as f: + return hashlib.file_digest(f, "sha256").hexdigest() + + +def fail(message): + print(f"[virtues] {message}", file=sys.stderr) + sys.exit(1) + + +def parse_args(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--sdata", required=True, help="SpatialData store; only read") + parser.add_argument("--methods", required=True, help="M1,M2; reads {M}_cells and {M}_table") + parser.add_argument("--channels", required=True, help="NAME:UNIPROT_ID,... in model channel order") + parser.add_argument("--unembedded", default="", help="channels without an ID; recorded only") + parser.add_argument("--stats", required=True, help="slide statistics, *_virtues_stats.json") + parser.add_argument("--pixel-size", type=float, required=True, help="image um/px") + parser.add_argument("--device", required=True, help="cuda; FlashAttention has no CPU path") + parser.add_argument("--batch-size", type=int, default=BATCH, help="crops per GPU batch") + parser.add_argument("--outdir", default=".") + args = parser.parse_args(argv) + if args.pixel_size <= 0: + parser.error("--pixel-size must be positive") + if args.batch_size < 1: + parser.error("--batch-size must be at least 1") + args.methods = [m for m in args.methods.split(",") if m] + bad = [c for c in args.channels.split(",") if c and ":" not in c] + if bad: + parser.error(f"--channels entries need NAME:UNIPROT_ID; got {bad}") + args.channels = [tuple(c.rsplit(":", 1)) for c in args.channels.split(",") if c] + names = [n for n, _ in args.channels] + if not names or len(set(names)) != len(names) or not args.methods: + parser.error("--channels and --methods need at least one entry, each once") + args.unembedded = [c for c in args.unembedded.split(",") if c] + return args + + +def main(argv=None, encode=None) -> int: + """encode is injected by tests; otherwise the model is loaded on the GPU.""" + import geopandas as gpd + import pandas as pd + import spatialdata as sd + from shapely.geometry import box + + from resolve_segmentation import store_image_key + + args = parse_args(argv) + if not (args.device == "cuda" or args.device.startswith("cuda:")): + fail(f"VirTues needs a CUDA device (FlashAttention has no CPU path); got --device {args.device}") + names = [n for n, _ in args.channels] + ids = [u for _, u in args.channels] + + sdata = sd.read_zarr(args.sdata) + image = sdata.images[store_image_key(args.sdata)] + if hasattr(image, "children"): # multiscale: full resolution is scale0 + image = image["scale0"]["image"] + available = [str(c) for c in image.coords["c"].values] + unknown = [n for n in names + args.unembedded if n not in available] + if unknown: + fail(f"unknown channels {unknown}; the store has {available}") + try: + entries = load_stats(args.stats, args.channels) + except ValueError as e: + fail(str(e)) + fasta = os.environ.get("VIRTUES_UNIPROT") + if not fasta: + fail("VIRTUES_UNIPROT is not set; it names the UniProt FASTA baked into the image") + try: + sequences = uniprot_sequences(fasta, ids) + except KeyError as e: + fail(e.args[0]) + + weights = os.environ.get("VIRTUES_WEIGHTS", "") + weights_sha = "" + if encode is None: + import torch + + if not torch.cuda.is_available(): + fail(f"--device {args.device}, but torch sees no CUDA device") + model = load_virtues(weights, [sequences[u] for u in ids], args.device) + encode = virtues_encoder(model, len(ids), args.device) + weights_sha = sha256(weights) + + ps = args.pixel_size + data = image.data + model_hw = model_shape(data.shape[1:], ps) + padded = (model_hw[0] + 2 * PAD, model_hw[1] + 2 * PAD) + index = [available.index(n) for n in names] + st = stats_arrays(entries, names) + + def read_raw(c, y0, y1, x0, x1): + return resample_window(data, index[c], y0, y1, x0, x1, ps) + + def read_input(y0, y1, x0, x1): + return model_input(read_raw, st, y0, y1, x0, x1, padded) + + try: + tissue_polys = tissue_polygons(sdata, image, args.sdata) + except ValueError as e: + fail(f"tissue ROI: {e}") + + def read_tissue(y0, y1, x0, x1): + return tissue_mask(tissue_polys, y0, y1, x0, x1, ps) + + sources, obs = {}, {} + for m in args.methods: + table = sdata.tables[f"{m}_table"] + rows = [str(n) for n in table.obs_names] + shapes = sdata.shapes[f"{m}_cells"] + try: + by_id = pd.Series(to_image_pixels(shapes, image), index=shapes.index.astype(str)) + except ValueError as e: + fail(f"{m}_cells: {e}") + missing = [n for n in rows if n not in by_id.index] + if missing: + fail(f"{m}: {len(missing)} table cells have no shape, e.g. {missing[:3]}") + sources[m] = cell_source(list(by_id.loc[rows]), ps, model_hw) + obs[m] = table.obs[[c for c in OBS_COLUMNS if c in table.obs.columns]] + + cells = cell_embeddings(read_input, sources, padded, encode, batch=args.batch_size) + origins, fractions, niche_emb = niche_embeddings( + read_input, read_tissue, model_hw, encode, batch=args.batch_size + ) + n_squares = (model_hw[0] // CROP) * (model_hw[1] // CROP) + + provenance = { + "virtues_commit": os.environ.get("VIRTUES_COMMIT", "unknown"), + "weights": weights, + "weights_sha256": weights_sha, + "esm_model": ESM_MODEL, + "uniprot_release": os.environ.get("VIRTUES_UNIPROT_RELEASE", "unknown"), + "channels": dict(args.channels), + "unembedded": args.unembedded, + "stats": entries, + "pixel_size": ps, + "model_um_per_px": MODEL_UM_PER_PX, + "crop_size": CROP, + "crop_step": STEP, + "patch_size": PATCH, + "padding": PAD, + "tile_size": TILE, + "batch_size": args.batch_size, + "device": args.device, + "n_cells": {m: len(w) for m, (_, w) in cells.items()}, + "n_cells_without_pixel": {m: int((w == 0).sum()) for m, (_, w) in cells.items()}, + "n_niches_kept": len(origins), + "n_niches_dropped": n_squares - len(origins), + } + + outdir = Path(args.outdir) + outdir.mkdir(parents=True, exist_ok=True) + for m in args.methods: + build_table(cells[m][0], obs[m], provenance, f"{m}_cells", "cell_id").write_h5ad( + outdir / f"{m}_virtues.h5ad" + ) + # slide and core_id are per store; any non-empty method table carries them + labels = {} + for c in ("slide", "core_id"): + found = [o[c].iloc[0] for o in obs.values() if c in o.columns and len(o)] + if found: + labels[c] = str(found[0]) + if origins: + niche_ids = [f"niche_{i}" for i in range(len(origins))] + squares = [box(x / ps, y / ps, (x + CROP) / ps, (y + CROP) / ps) for y, x in origins] + gpd.GeoDataFrame(geometry=squares, index=pd.Index(niche_ids)).to_parquet( + outdir / "virtues_niches.parquet" + ) + niche_obs = pd.DataFrame( + { + "region": pd.Categorical(["virtues_niches"] * len(origins)), + "niche_id": niche_ids, + "tissue_fraction": fractions, + **{c: pd.Categorical([v] * len(origins)) for c, v in labels.items()}, + }, + index=niche_ids, + ) + build_table(niche_emb, niche_obs, provenance, "virtues_niches", "niche_id").write_h5ad( + outdir / "virtues_niches_table.h5ad" + ) + tissue_obs = pd.DataFrame( + {**{c: [v] for c, v in labels.items()}, "n_niches": [len(origins)]}, index=["tissue_0"] + ) + build_table(tissue_embedding(niche_emb)[None, :], tissue_obs, provenance).write_h5ad( + outdir / "virtues_tissue.h5ad" + ) + (outdir / "virtues.json").write_text(json.dumps(provenance, indent=2) + "\n") + print( + f"[virtues] cells {provenance['n_cells']}, without a pixel {provenance['n_cells_without_pixel']}; " + f"squares kept {len(origins)}, dropped {provenance['n_niches_dropped']}" + ) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/bin/virtues_stats.py b/bin/virtues_stats.py new file mode 100755 index 0000000..a18aa2c --- /dev/null +++ b/bin/virtues_stats.py @@ -0,0 +1,269 @@ +#!/usr/bin/env python3 +"""VirTues model scale and slide statistics; no torch, so it runs in the sopa image. + +Model pixel k covers image interval [k / pixel_size, (k + 1) / pixel_size) at 1 um/px, so +windows are resampled on demand and never written as a temporary image. +""" + +import argparse +import json +import math +import sys +from pathlib import Path + +import numpy as np + +MODEL_UM_PER_PX = 1.0 +QUANTILE = 0.99 +N_BINS = 65536 # uint16 values +STATS_FORMAT = 1 +TISSUE_KEY = "region_of_interest" # written by sopa's tissue segmentation + + +def model_shape(image_yx, pixel_size): + """Model grid (rows, cols) for an image of (y, x) pixels.""" + return tuple(int(math.floor(n * pixel_size)) for n in image_yx) + + +def _axis_weights(start, stop, pixel_size, n_image): + """Source indices and area weights, both (stop - start, taps), for model pixels start..stop-1.""" + taps = math.ceil(1 / pixel_size) + 1 + k = np.arange(start, stop, dtype=np.float64) + lo, hi = k / pixel_size, (k + 1) / pixel_size + j = np.floor(lo).astype(np.int64)[:, None] + np.arange(taps)[None, :] + overlap = np.minimum(j + 1, hi[:, None]) - np.maximum(j, lo[:, None]) + weights = np.clip(overlap, 0, None) * pixel_size + weights[j >= n_image] = 0.0 + return np.minimum(j, n_image - 1), weights + + +def resample_window(image, channel, y0, y1, x0, x1, pixel_size): + """Area-averaged model window, float32 (y1 - y0, x1 - x0); reads only the pixels it needs.""" + _, h, w = image.shape + if pixel_size == 1.0: + return np.asarray(image[channel, y0:y1, x0:x1]).astype(np.float32) + rows, wr = _axis_weights(y0, y1, pixel_size, h) + cols, wc = _axis_weights(x0, x1, pixel_size, w) + ra, rb, ca, cb = rows.min(), rows.max() + 1, cols.min(), cols.max() + 1 + block = np.asarray(image[channel, ra:rb, ca:cb]).astype(np.float64) + # explicit fixed-order sums, not a matrix product, so a value never depends on the window shape + tmp = np.zeros((y1 - y0, cb - ca)) + for t in range(rows.shape[1]): + tmp += block[rows[:, t] - ra, :] * wr[:, t, None] + out = np.zeros((y1 - y0, x1 - x0)) + for t in range(cols.shape[1]): + out += tmp[:, cols[:, t] - ca] * wc[None, :, t] + return out.astype(np.float32) + + +def tissue_mask(polygons, y0, y1, x0, x1, pixel_size): + """True where a model pixel's centre, in image coordinates, lies inside a polygon.""" + import shapely + + xs = (np.arange(x0, x1) + 0.5) / pixel_size + ys = (np.arange(y0, y1) + 0.5) / pixel_size + gx, gy = np.meshgrid(xs, ys) + mask = np.zeros(gx.shape, dtype=bool) + for poly in polygons: + mask |= shapely.contains_xy(poly, gx, gy) + return mask + + +def to_image_pixels(shapes, image): + """A shapes element's geometries in the image's pixel coordinates, in row order. + + sopa's tissue() keeps the ROI in its coarsest level's pixels, with a scale to global. + """ + import shapely + from spatialdata.transformations import get_transformation + + from_shapes = get_transformation(shapes, get_all=True) + from_image = get_transformation(image, get_all=True) + shared = sorted(set(from_shapes) & set(from_image), key=lambda cs: cs != "global") # global first + if not shared: + raise ValueError( + f"shapes and image share no coordinate system: {sorted(from_shapes)}, {sorted(from_image)}" + ) + xy = ("x", "y") + shapes_to_cs = from_shapes[shared[0]].to_affine_matrix(xy, xy) + image_to_cs = from_image[shared[0]].to_affine_matrix(xy, xy) + m = np.linalg.inv(image_to_cs) @ shapes_to_cs # shape px -> coordinate system -> image px + geoms = np.asarray(shapes.geometry, dtype=object) + if np.array_equal(m, np.eye(3)): + return list(geoms) # untouched, so coordinates stay bit-identical + return list(shapely.transform(geoms, lambda c: c @ m[:2, :2].T + m[:2, 2])) + + +def tissue_polygons(sdata, image, store): + """The ROI in image pixels; none when sopa found no tissue, as it then writes no ROI.""" + if TISSUE_KEY not in sdata.shapes: + print( + f"[virtues] warning: tissue segmentation found no tissue in {store}; counting zero tissue pixels", + file=sys.stderr, + ) + return [] + return to_image_pixels(sdata.shapes[TISSUE_KEY], image) + + +def histogram(image, polygons, channels, pixel_size, rows=2048): + """int64 (len(channels), N_BINS) counts of rounded model values over tissue pixels.""" + if not np.issubdtype(image.dtype, np.unsignedinteger): + raise TypeError(f"image dtype is {image.dtype}; VirTues statistics need an unsigned integer image") + h, w = model_shape(image.shape[1:], pixel_size) + counts = np.zeros((len(channels), N_BINS), dtype=np.int64) + for y0 in range(0, h, rows): + for x0 in range(0, w, rows): # square windows bound memory by tile size, not image width + y1, x1 = min(y0 + rows, h), min(x0 + rows, w) + mask = tissue_mask(polygons, y0, y1, x0, x1, pixel_size) + if not mask.any(): + continue + for i, channel in enumerate(channels): + values = resample_window(image, channel, y0, y1, x0, x1, pixel_size)[mask] + bins = np.clip(np.rint(values), 0, N_BINS - 1).astype(np.int64) + counts[i] += np.bincount(bins, minlength=N_BINS) + return counts + + +def stats_from_histogram(counts): + """cap, mean, sd (population, two-pass) of log1p(min(v, cap)), and tissue_pixels.""" + counts = np.asarray(counts, dtype=np.int64) + n = int(counts.sum()) + if n == 0: + raise ValueError("no tissue pixels") + cum = np.cumsum(counts) + + def value_at(rank): # rank-th smallest pixel value, 0-based + return int(np.searchsorted(cum, rank, side="right")) + + virtual = QUANTILE * (n - 1) + lower = math.floor(virtual) + # numpy's linear method, on the two neighbouring values + cap = float(np.quantile([value_at(lower), value_at(min(lower + 1, n - 1))], virtual - lower)) + x = np.log1p(np.minimum(np.arange(N_BINS, dtype=np.float64), cap)) + c = counts.astype(np.float64) + mean = float((c * x).sum() / n) + sd = float(np.sqrt((c * (x - mean) ** 2).sum() / n)) + if sd == 0: + raise ValueError("standard deviation is zero (constant marker)") + return {"cap": cap, "mean": mean, "sd": sd, "tissue_pixels": n} + + +def load_stats(path, channels): + """Markers for [(name, uniprot_id)], checking format and IDs against the file.""" + stats = json.loads(Path(path).read_text()) + if stats.get("format") != STATS_FORMAT: + raise ValueError(f"{path}: format {stats.get('format')}, expected {STATS_FORMAT}") + out = {} + for name, uid in channels: + entry = stats["markers"].get(name) + if entry is None: + raise ValueError(f"{path}: marker {name} is missing; the file has {sorted(stats['markers'])}") + if entry["uniprot_id"] != uid: + raise ValueError(f"{path}: marker {name} has UniProt ID {entry['uniprot_id']}, expected {uid}") + out[name] = entry + return out + + +def combine(paths, slide, pixel_size, output): + """Sum per-core histograms and write the slide statistics file.""" + first, cores, total = None, [], None + for p in paths: + with np.load(p, allow_pickle=False) as z: + sample, markers, ids = ( + str(z["sample"]), + [str(m) for m in z["markers"]], + [str(u) for u in z["uniprot_ids"]], + ) + if first is None: + first, total = (sample, markers, ids), z["counts"].astype(np.int64) + elif markers != first[1] or ids != first[2]: + raise ValueError( + f"{sample} has markers/IDs {list(zip(markers, ids, strict=True))}, " + f"but {first[0]} has {list(zip(first[1], first[2], strict=True))}" + ) + else: + total += z["counts"] # running sum: one core in memory at a time + cores.append(sample) + if not total.any(): + raise ValueError( + f"tissue segmentation found no tissue on slide {slide}, so it has no statistics; " + "check its tissue segmentation, or pass virtues_stats" + ) + result = {} + for i, (name, uid) in enumerate(zip(first[1], first[2], strict=True)): + try: + result[name] = {"uniprot_id": uid, **stats_from_histogram(total[i])} + except ValueError as e: + raise ValueError( + f"slide {slide}, marker {name}: {e}; remove its uniprot_id from the marker sheet, or pass virtues_stats" + ) from e + doc = { + "format": STATS_FORMAT, + "slide": slide, + "cores": sorted(cores), + "model_um_per_px": MODEL_UM_PER_PX, + "pixel_size": pixel_size, + "markers": result, + } + Path(output).write_text(json.dumps(doc, indent=2) + "\n") + + +def _histogram_cli(args): + import spatialdata as sd + + from resolve_segmentation import store_image_key + + pairs = [c.rsplit(":", 1) for c in args.channels.split(",")] + sdata = sd.read_zarr(args.sdata) + image = sdata.images[store_image_key(args.sdata)] + if hasattr(image, "children"): # multiscale: full resolution is scale0 + image = image["scale0"]["image"] + available = [str(c) for c in image.coords["c"].values] + unknown = [n for n, _ in pairs if n not in available] + if unknown: + sys.exit(f"[virtues_stats] unknown channels {unknown}; the store has {available}") + try: + counts = histogram( + image.data, + tissue_polygons(sdata, image, args.sdata), + [available.index(n) for n, _ in pairs], + args.pixel_size, + ) + except (TypeError, ValueError) as e: + sys.exit(f"[virtues_stats] {e}") + sample = Path(args.output).name.removesuffix("_virtues_hist.npz") + np.savez_compressed( + args.output, + counts=counts, + markers=np.array([n for n, _ in pairs]), + uniprot_ids=np.array([u for _, u in pairs]), + sample=sample, + ) + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + sub = parser.add_subparsers(dest="command", required=True) + h = sub.add_parser("histogram", help="per-core tissue histograms") + h.add_argument("--sdata", required=True, help="SpatialData store; only read") + h.add_argument("--channels", required=True, help="NAME:UNIPROT_ID,...") + h.add_argument("--pixel-size", required=True, type=float, help="um per image px") + h.add_argument("--output", required=True) + c = sub.add_parser("combine", help="sum a slide's histograms into statistics") + c.add_argument("--slide", required=True) + c.add_argument("--pixel-size", required=True, type=float) + c.add_argument("--output", required=True) + c.add_argument("histograms", nargs="+") + args = parser.parse_args(argv) + if args.command == "histogram": + _histogram_cli(args) + else: + try: + combine(args.histograms, args.slide, args.pixel_size, args.output) + except ValueError as e: + sys.exit(f"[virtues_stats] {e}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/bin/write_features.py b/bin/write_features.py new file mode 100755 index 0000000..102a590 --- /dev/null +++ b/bin/write_features.py @@ -0,0 +1,95 @@ +#!/usr/bin/env python3 +"""Write learned-feature shapes and tables into the SpatialData store. + +Tables are `{method}_{model}.h5ad` (region `{method}_cells`), VirTues niche tables (region a +shapes file in this write) and tables without a region. Each is checked against its region +before the store is touched. An element of the same name is removed by path first, so a retry +or -resume gives the same result. +""" + +from __future__ import annotations + +import argparse +import re +import shutil +import sys +from pathlib import Path + +from write_segmentations import image_transformations, reconsolidate, write_element + +# spatialdata is imported inside functions so the module imports without it. + + +def check_table(name: str, adata, sdata_path: Path, shape_index: dict) -> None: + """Raise ValueError unless the table's rows fit its region; no region means no check.""" + import anndata as ad + + attrs = adata.uns.get("spatialdata_attrs") or {} + region = attrs.get("region") + if region is None: + return + match = re.fullmatch(r"(.+)_cells", region) if isinstance(region, str) else None + if match: + base = f"{match.group(1)}_table" + reference = ad.read_zarr(sdata_path / "tables" / base) + if not adata.obs_names.equals(reference.obs_names): + raise ValueError(f"table '{name}' rows differ from '{base}' (names or order); refusing to write") + elif isinstance(region, str) and region in shape_index: + ids = adata.obs[attrs["instance_key"]].astype(str).tolist() + if ids != shape_index[region]: + raise ValueError( + f"table '{name}' rows differ from shapes '{region}' (ids or order); refusing to write" + ) + else: + raise ValueError(f"table '{name}' has region {region!r}: not a cells region nor shapes in this write") + + +def write_features(sdata_path: Path, tables: list[Path], shapes: list[Path] = ()) -> None: + import anndata as ad + import geopandas as gpd + import spatialdata as sd + from spatialdata.models import ShapesModel + + _, transformations = image_transformations(sdata_path) + + # Validate everything before touching the store. + gdfs = {p.stem: gpd.read_parquet(p) for p in shapes} + shape_index = {name: gdf.index.astype(str).tolist() for name, gdf in gdfs.items()} + adatas = {p.stem: ad.read_h5ad(p) for p in tables} + for name, adata in adatas.items(): + check_table(name, adata, sdata_path, shape_index) + + for kind, names in (("shapes", gdfs), ("tables", adatas)): + for name in names: + element = sdata_path / kind / name + if element.is_dir(): + shutil.rmtree(element) + print(f"[write_features] removed {kind} {name}: replaced by this write") + reconsolidate(sdata_path) + + sdata = sd.read_zarr(sdata_path) + for name, gdf in gdfs.items(): + write_element(sdata, name, ShapesModel.parse(gdf, transformations=transformations), "shapes") + for name, adata in adatas.items(): + write_element(sdata, name, adata, "table") + + # Re-read: an in-place write that silently did nothing must not pass. + check = sd.read_zarr(sdata_path) + absent = [n for n in gdfs if n not in check.shapes] + [n for n in adatas if n not in check.tables] + if absent: + raise RuntimeError(f"not in {sdata_path} after writing: {absent}") + print(f"[write_features] {sdata_path} :: shapes {list(gdfs)}, tables {list(adatas)}") + + +def main() -> int: + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument("--sdata", required=True, type=Path, help="SpatialData .zarr store, written in place") + ap.add_argument("--tables", nargs="*", default=[], type=Path, help="NAME.h5ad files") + ap.add_argument("--shapes", nargs="*", default=[], type=Path, help="NAME.parquet GeoParquet files") + args = ap.parse_args() + write_features(args.sdata, args.tables, args.shapes) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/bin/write_segmentations.py b/bin/write_segmentations.py index 3c40f80..0b1aae6 100755 --- a/bin/write_segmentations.py +++ b/bin/write_segmentations.py @@ -23,7 +23,11 @@ # spatialdata is imported inside functions so the module imports without it. SEGMENTATION_ATTR = "cell_segmentation_image" # sopa's SopaAttrs.CELL_SEGMENTATION -RESERVED = re.compile(r"^(cellpose|instanseg)_(cells|nuclei|cytoplasm|table)$") +LEARNED_MODELS = ("nimbus", "virtues") # a new learned-features model adds its name here +RESERVED = re.compile( + rf"^((cellpose|instanseg)_(cells|nuclei|cytoplasm|table|{'|'.join(LEARNED_MODELS)})" + r"|virtues_(niches|niches_table|tissue))$" +) ELEMENT_KINDS = ("shapes", "tables") @@ -94,23 +98,30 @@ def drop_projection(sdata, image_key: str) -> None: print(f"[write_segmentations] dropped {name}") -def write_segmentations( - sdata_path: Path, shapes: list[Path], tables: list[Path], keep_projection: bool = False -) -> None: - import anndata as ad - import geopandas as gpd +def image_transformations(sdata_path: Path): + """The segmentation image's key and transformations, which new shapes must carry.""" import spatialdata as sd - from spatialdata.models import ShapesModel from spatialdata.transformations import get_transformation - # Images only: other elements may be stale or half-written, and are dealt with below. + # Images only: other elements may be stale or half-written, and are dealt with by the caller. images = sd.read_zarr(sdata_path, selection=("images",)) image_key = images.attrs.get(SEGMENTATION_ATTR) if image_key is None: raise ValueError(f"{sdata_path} has no '{SEGMENTATION_ATTR}' attribute: no image to place shapes on") if image_key not in images.images: raise ValueError(f"'{SEGMENTATION_ATTR}' is '{image_key}' but {sdata_path} has no such image") - transformations = get_transformation(images.images[image_key], get_all=True) + return image_key, get_transformation(images.images[image_key], get_all=True) + + +def write_segmentations( + sdata_path: Path, shapes: list[Path], tables: list[Path], keep_projection: bool = False +) -> None: + import anndata as ad + import geopandas as gpd + import spatialdata as sd + from spatialdata.models import ShapesModel + + image_key, transformations = image_transformations(sdata_path) # Read and validate everything before touching the store. gdfs = {p.stem: gpd.read_parquet(p) for p in shapes} diff --git a/conf/base.config b/conf/base.config index 130b2f4..5300d47 100644 --- a/conf/base.config +++ b/conf/base.config @@ -61,6 +61,14 @@ process { cpus = 4 } + withName: 'NIMBUS' { + cpus = 4 + } + + withName: 'VIRTUES' { + cpus = 4 + } + // From channels and patch area: instansegMemoryGB in modules/local/utils.nf, set per sample // in subworkflows/local/segmentation. A closure, so `spec` is the task's own input. withName: 'SEGMENT_PATCH_INSTANSEG' { diff --git a/conf/gpu.config b/conf/gpu.config index 7a4555c..b3d230c 100644 --- a/conf/gpu.config +++ b/conf/gpu.config @@ -2,16 +2,17 @@ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ GPU segmentation (use_gpu) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - Included by nextflow.config only when use_gpu is true. Asks for one GPU per Cellpose and - InstanSeg patch task; conf/slurm.config and conf/mdc.config turn that into SLURM options. + Included by nextflow.config only when use_gpu is true. Asks for one GPU per Cellpose or + InstanSeg patch task, per Nimbus task and per VirTues task; conf/slurm.config and conf/mdc.config turn that + into SLURM options. ---------------------------------------------------------------------------------------- */ process { - withName: 'SEGMENT_PATCH_(CELLPOSE|INSTANSEG)' { + withName: 'SEGMENT_PATCH_(CELLPOSE|INSTANSEG)|NIMBUS|VIRTUES' { accelerator = 1 - // So one run cannot take every free GPU on a shared cluster (16 per method). + // So one run cannot take every free GPU on a shared cluster; maxForks applies per process. maxForks = 16 // Mounts the host's CUDA driver into the container. Docker on the Mac has no GPU to pass. diff --git a/conf/modules.config b/conf/modules.config index 6bc821a..9b8ebc2 100644 --- a/conf/modules.config +++ b/conf/modules.config @@ -111,6 +111,12 @@ process { // Metrics JSON published beside the HTML so unattended runs can gate on it. withName: QC_METRICS { + ext.args = { + [ + params.use_nimbus ? "--nimbus-table ${meta.method}_nimbus" : "", + params.use_virtues ? "--virtues-table ${meta.method}_virtues" : "", + ].findAll { it }.join(' ') + } publishDir = [ path: { "${params.outdir}/qc" }, mode: params.publish_dir_mode, @@ -164,4 +170,31 @@ process { saveAs: { filename -> filename.equals('versions.yml') ? null : filename }, ] } + + // Only the provenance JSON is published; the scores live in the store. + withName: NIMBUS { + publishDir = [ + path: { "${params.outdir}/learned_features" }, + mode: params.publish_dir_mode, + // Prefixed by sample: every store writes the same {method}_nimbus.json name. + saveAs: { filename -> filename.endsWith('.json') ? "${meta.sample}_${filename}" : null }, + ] + } + + withName: VIRTUES_STATS { + publishDir = [ + path: { "${params.outdir}/learned_features" }, + mode: params.publish_dir_mode, + saveAs: { filename -> filename.endsWith('.json') ? filename : null }, + ] + } + + // Only the provenance JSON is published; the embeddings live in the store. + withName: VIRTUES { + publishDir = [ + path: { "${params.outdir}/learned_features" }, + mode: params.publish_dir_mode, + saveAs: { filename -> filename == 'virtues.json' ? "${meta.sample}_virtues.json" : null }, + ] + } } diff --git a/conf/sizes.config b/conf/sizes.config index 177ce74..52619e4 100644 --- a/conf/sizes.config +++ b/conf/sizes.config @@ -28,12 +28,14 @@ profiles { withName: 'RESOLVE' { cpus = 2; memory = { 4.GB * task.attempt }; time = { 30.m * task.attempt } } // 515 MB, 34 s withName: 'LINK_COMPARTMENTS' { cpus = 2; memory = { 4.GB * task.attempt }; time = { 30.m * task.attempt } } // as RESOLVE; not measured withName: 'WRITE_SEGMENTATIONS' { cpus = 2; memory = { 4.GB * task.attempt }; time = { 30.m * task.attempt } } // as RESOLVE; not measured + withName: 'WRITE_FEATURES' { cpus = 2; memory = { 4.GB * task.attempt }; time = { 30.m * task.attempt } } // as RESOLVE; not measured withName: 'AGGREGATE' { cpus = 2; memory = { 4.GB * task.attempt }; time = { 30.m * task.attempt } } // 858 MB, 18 s withName: 'QC_METRICS' { cpus = 2; memory = { 4.GB * task.attempt }; time = { 30.m * task.attempt } } // streams row bands withName: 'QC_IMAGES' { cpus = 2; memory = { 8.GB * task.attempt }; time = { 1.h * task.attempt } } // graph over cells withName: 'QC_REPORT' { cpus = 1; memory = { 2.GB * task.attempt }; time = { 15.m * task.attempt } } // JSON to HTML withName: 'COMPARE_SEGMENTATIONS' { cpus = 1; memory = { 4.GB * task.attempt }; time = { 30.m * task.attempt } } // ~4.5 GB, 20 s per 1e6 cells a method (synthetic) withName: 'MERGE_SPATIALDATA' { cpus = 2; memory = { 8.GB * task.attempt }; time = { 1.h * task.attempt } } // not exercised + withName: 'VIRTUES' { cpus = 4; memory = { 16.GB * task.attempt }; time = { 15.m * task.attempt } } // 3.5 GB, 1.1 min per exemplar-002 core (22 markers, A40) } } @@ -54,6 +56,7 @@ profiles { withName: 'RESOLVE' { cpus = 2; memory = { 16.GB * task.attempt }; time = { 2.h * task.attempt } } withName: 'LINK_COMPARTMENTS' { cpus = 2; memory = { 16.GB * task.attempt }; time = { 2.h * task.attempt } } // as RESOLVE; not measured withName: 'WRITE_SEGMENTATIONS' { cpus = 2; memory = { 16.GB * task.attempt }; time = { 2.h * task.attempt } } // as RESOLVE; not measured + withName: 'WRITE_FEATURES' { cpus = 2; memory = { 16.GB * task.attempt }; time = { 2.h * task.attempt } } // as RESOLVE; not measured withName: 'AGGREGATE' { cpus = 4; memory = { 16.GB * task.attempt }; time = { 2.h * task.attempt } } withName: 'QC_METRICS' { cpus = 2; memory = { 8.GB * task.attempt }; time = { 1.h * task.attempt } } // streams row bands withName: 'QC_IMAGES' { cpus = 4; memory = { 16.GB * task.attempt }; time = { 2.h * task.attempt } } // graph over cells @@ -78,6 +81,7 @@ profiles { withName: 'RESOLVE' { cpus = 4; memory = { 32.GB * task.attempt }; time = { 4.h * task.attempt } } withName: 'LINK_COMPARTMENTS' { cpus = 4; memory = { 32.GB * task.attempt }; time = { 4.h * task.attempt } } // as RESOLVE; not measured withName: 'WRITE_SEGMENTATIONS' { cpus = 4; memory = { 32.GB * task.attempt }; time = { 4.h * task.attempt } } // as RESOLVE; not measured + withName: 'WRITE_FEATURES' { cpus = 4; memory = { 32.GB * task.attempt }; time = { 4.h * task.attempt } } // as RESOLVE; not measured withName: 'AGGREGATE' { cpus = 8; memory = { 32.GB * task.attempt }; time = { 4.h * task.attempt } } withName: 'QC_METRICS' { cpus = 2; memory = { 16.GB * task.attempt }; time = { 2.h * task.attempt } } // streams row bands withName: 'QC_IMAGES' { cpus = 4; memory = { 32.GB * task.attempt }; time = { 4.h * task.attempt } } // graph over cells @@ -105,6 +109,7 @@ profiles { withName: 'RESOLVE' { cpus = 8; memory = { 64.GB * task.attempt }; time = { 8.h * task.attempt } } withName: 'LINK_COMPARTMENTS' { cpus = 8; memory = { 64.GB * task.attempt }; time = { 8.h * task.attempt } } // as RESOLVE; not measured withName: 'WRITE_SEGMENTATIONS' { cpus = 8; memory = { 64.GB * task.attempt }; time = { 8.h * task.attempt } } // as RESOLVE; not measured + withName: 'WRITE_FEATURES' { cpus = 8; memory = { 64.GB * task.attempt }; time = { 8.h * task.attempt } } // as RESOLVE; not measured withName: 'AGGREGATE' { cpus = 16; memory = { 64.GB * task.attempt }; time = { 8.h * task.attempt } } withName: 'QC_METRICS' { cpus = 4; memory = { 32.GB * task.attempt }; time = { 4.h * task.attempt } } // streams row bands withName: 'QC_IMAGES' { cpus = 8; memory = { 64.GB * task.attempt }; time = { 8.h * task.attempt } } // graph over cells diff --git a/conf/test_exemplar001.config b/conf/test_exemplar001.config index 6402039..c3d833b 100644 --- a/conf/test_exemplar001.config +++ b/conf/test_exemplar001.config @@ -35,10 +35,11 @@ params { segment_nuclei = true use_cellpose = true - cellpose_channels = "DNA_6" + // A membrane marker for cells; DNA_6 alone makes cells equal nuclei, with no cytoplasm. + cellpose_channels = "CD45 DNA_6" // Channels from the marker sheet. 1500 px asks 16 GB per patch for cells (12 channels). use_instanseg = true - instanseg_pixel_size = 0.65 // PhysicalSizeX in the exemplar-001 OME-XML + pixel_size = 0.65 // PhysicalSizeX in the exemplar-001 OME-XML } diff --git a/conf/test_exemplar002.config b/conf/test_exemplar002.config index da0c660..efaf98b 100644 --- a/conf/test_exemplar002.config +++ b/conf/test_exemplar002.config @@ -36,7 +36,7 @@ params { // InstanSeg only, cells and nuclei; channels from the marker sheet. use_cellpose = false use_instanseg = true - instanseg_pixel_size = 0.65 // PhysicalSizeX in the exemplar-002 OME-XML + pixel_size = 0.65 // PhysicalSizeX in the exemplar-002 OME-XML segment_nuclei = true // Cores are ~2900 px square, so 2000 gives 2 x 2 patches per core. diff --git a/containers.tsv b/containers.tsv index 661991f..e656a23 100644 --- a/containers.tsv +++ b/containers.tsv @@ -4,7 +4,9 @@ singularity_uri docker_uri conda modules https://community-cr-prod.seqera.io/docker/registry/v2/blobs/sha256/70/707825bb6afa202806406063665a361b2a4a2fc6d6f802132359407408826ffe/data community.wave.seqera.io/library/python_sopa:54a97bc5a187152d python=3.12,sopa=2.2.9 modules/local/compare_segmentations,modules/local/make_image_patches,modules/local/merge_report,modules/local/merge_spatialdata,modules/local/project_channels,modules/local/qc_images,modules/local/qc_metrics,modules/local/qc_report,modules/local/set_channel_names,modules/local/tissue_segmentation,modules/local/to_spatialdata docker.io/josenimo/ashlar:1.22.1 modules/nf-core/ashlar - docker.io/josenimo/sopa:2.3.0 python=3.12,pip,pip:,sopa[cellpose,instanseg]==2.3.0,cellpose==4.2.1.1 modules/local/aggregate,modules/local/link_compartments,modules/local/resolve,modules/local/segment_patch,modules/local/write_segmentations + docker.io/josenimo/nimbus:0.0.5 python=3.12,pip,pip:,Nimbus-Inference==0.0.5 modules/local/nimbus + docker.io/josenimo/sopa:2.3.0-1 python=3.12,pip,pip:,sopa[cellpose,instanseg]==2.3.0,cellpose==4.2.1.1 modules/local/aggregate,modules/local/link_compartments,modules/local/resolve,modules/local/segment_patch,modules/local/virtues_histogram,modules/local/virtues_stats,modules/local/write_features,modules/local/write_segmentations + docker.io/josenimo/virtues:d2c25e1-2 python=3.12,pip,pip:,torch==2.5.1 modules/local/virtues docker.io/labsyspharm/basicpy-docker-mcmicro:1.2.0-patch5 modules/nf-core/basicpy docker.io/labsyspharm/unetcoreograph:2.4.6 modules/local/coreograph_detect,modules/local/coreograph_select,modules/nf-core/coreograph ghcr.io/schapirolabor/background_subtraction:v0.5.1 dask-image=2024.5.3,dask=2025.7.0,loguru=0.7.3,numpy=2.3.2,ome-types=0.6.0,pandas=2.3.1,python=3.12.11,scikit-image=0.25.2,tifffile=2025.6.11,zarr=3.1.1,pip=25.3,pip:,backsub==0.5.1 modules/nf-core/backsub diff --git a/docs/CONTRIBUTING.md b/docs/CONTRIBUTING.md index 542770e..cb3b078 100644 --- a/docs/CONTRIBUTING.md +++ b/docs/CONTRIBUTING.md @@ -127,7 +127,7 @@ Data: Assertions are properties, not checksums: channel names, TMA core count, which processes ran and how often, nuclear stain chosen by `channel_role`, subtraction blocks on every core, background channels unchanged by subtraction, `versions.yml` complete. Cell counts must stay within ±2% of the -baselines in ROADMAP. +baselines in the test files. ## Containers @@ -153,11 +153,11 @@ tools/container_manifest.py --check # fail if stale; the container-manifest p Regenerate it after adding or removing a module, or bumping a container. -**Five images are Docker-only.** `basicpy`, `coreograph` and `backsub` come from mcmicro and have no +**Six images are Docker-only.** `basicpy`, `coreograph` and `backsub` come from mcmicro and have no BioContainers Singularity build. `ashlar` uses our own public `josenimo/ashlar` image, built from the `Dockerfile` in [josenimo/ashlar](https://github.com/josenimo/ashlar) (branch `histo-qc`). -`josenimo/sopa:2.3.0` (Cellpose-SAM and InstanSeg, weights baked in) is also ours. Their -`singularity_uri` column is empty. They have to be converted from Docker rather than downloaded +`josenimo/sopa:2.3.0-1` (Cellpose-SAM and InstanSeg, weights baked in, plus `cpsam_v2`) and `josenimo/nimbus:0.0.5` +(Nimbus, `V1.pt` baked in) are also ours. Their `singularity_uri` column is empty. They have to be converted from Docker rather than downloaded directly, which is slower and subject to Docker Hub rate limiting. Budget for that. ### Building an image @@ -222,8 +222,8 @@ The map is authored in [`pipeline_paths.mmd`](pipeline_paths.mmd) and rendered w pip install nf-metro==2.1.0 # 1.1.0 aborts on the turns between rows nf-metro validate docs/pipeline_paths.mmd nf-metro render docs/pipeline_paths.mmd -o docs/images/pipeline_paths.svg --animate --responsive \ - --font-scale 1.7 --stroke-scale 1.8 --x-spacing 85 --y-spacing 200 --section-y-gap 50 \ - --diamond-style symmetric --height 1036 # --height pads to 1:2.2 + --font-scale 1.7 --stroke-scale 1.8 --x-spacing 111 --y-spacing 90 \ + --diamond-style symmetric --compact-offsets --validate ``` **Re-render this after any rewiring, and look at the result.** A change to the graph that leaves diff --git a/docs/decisions.md b/docs/decisions.md index df10190..cb3e8e2 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -73,9 +73,7 @@ panel (0.35 µm/px, raw). No ground truth; outlines were judged by eye, with met - **Low percentile 1.** 50 changed little once zeros were excluded; it helps hazy raw images. - **Thresholds matter more than projection.** sopa's `flow_threshold: 2`, `cellprob_threshold: -6` and CLAHE 0.2 tile the tissue into cells with or without - projection (cells cover 94 to 96% of the crop). Cellpose's 0.4 and 0 with CLAHE off follow - membranes. Documented, not defaulted, since changing them would change runs without - projection. + projection (cells cover 94 to 96% of the crop). The segmentation benchmark set new ones. - **Projection over DNA only**, both at Cellpose thresholds, exemplar-001: nuclei inside a cell rose from 86% to 99%; CD45-positive pixels inside a cell from 65% to 84%. - Cellpose-SAM took about 24 s per 1200 px crop on Apple MPS, against 3 s for `cyto3`. @@ -107,13 +105,15 @@ fails the task, since cellpose falls back to CPU silently. **Cellpose-SAM replaced Cellpose 3.** In the projection benchmark Cyto3 fell back to nuclei where Cellpose-SAM found cells, at ~8x the time. `diameter` is fixed at 30, cpsam's training size, so -images are not rescaled. +images are not rescaled. `cpsam_v2` is the default, following the cellpose developers; it is not +benchmarked against `cpsam`. ## Segmentation **One spec per method × target**, built once from params (`segmentationSpecs`), so a new -method is one more entry. Unset options keep sopa's per-method CLI defaults: -`StainingSegmentation`'s own would blur and equalise InstanSeg's input. +method is one more entry. Unset options keep sopa's per-method CLI defaults, except Cellpose's +thresholds and preprocessing (Segmentation benchmark, below): `StainingSegmentation`'s own would +blur and equalise InstanSeg's input. **One writer per store.** `sopa resolve` and `sopa aggregate` write into the store, and parallel writers race on its root metadata: last writer wins, silently. So patch, resolve, link and @@ -151,6 +151,138 @@ the kwargs JSON fails sopa in every patch task. **StarDist was sunset in 2.0.** Cellpose and InstanSeg segment nuclei. +## Segmentation benchmark + +Cellpose's defaults come from `tools/segmentation_benchmark`: 475 settings of `cpsam_v2` scored +by F1 at IoU 0.5 against manual outlines. Data: Cross-platform mIF (119 Vectra and 10 CODEX +crops), TissueNet 1.1 test (1324 tiles) and 10 tonsil crops, partly annotated, used as a check +only. Deck and results: `3_Projects/Segmentation_Benchmark` (lab share). + +- **No smoothing, no CLAHE.** Round 1 (168 settings): `projection_sigma`, `gaussian_sigma` and + CLAHE 0.2 each lowered F1, and the smoothings add up; Cellpose-SAM normalises each patch itself. + Round 2: CLAHE 0.01 also lost near good thresholds. Max and percentile 1 stay. +- **`flow_threshold: 0.6`, `cellprob_threshold: -1`.** Round 2 scored 7 × 8 pairs. Flow is flat + from 0.6; on cellprob, Cross-platform nuclei want -1 or less and TissueNet nuclei 0 or more. + The pair is the one with the smallest largest shortfall from each target's own best, a rule set + before the run: within 0.065 of the best for cells and nuclei on both datasets. Separate + nuclear thresholds would gain about 0.02 and add two parameters. +- **Gain.** Cells on Cross-platform 0.53 to 0.73 (128 of 129 crops better), on TissueNet 0.60 + to 0.87; nuclei 0.42 to 0.80 and 0.39 to 0.76. +- **Leave autofluorescence out of the cell channel** (+0.012 F1, Vectra only); nuclear markers + too (+0.004). The marker sheet already chooses, so this is advice, not code. +- **Open:** nuclear projection smoothing at -1 is untested (it helped at 0.4 / 0); percentiles + were per crop, not per slide. + +## Learned features + +**A stage after segmentation, one table per model and method.** `LEARNED_FEATURES` runs after +`SEGMENTATION`, only when a model is enabled. `NIMBUS` writes files; `WRITE_FEATURES` alone writes +`{method}_nimbus` into the store, after `WRITE_SEGMENTATIONS`. Scores are a table, not a layer: a +layer must share `{method}_table`'s `var` (marker × statistic), and viewers colour cells by table. +Later models (KRONOS) add a flag and a spec. + +**Tile windows are sized at model scale.** The image is resized by `pixel_size` before inference. +Tile: 2048 model px, each cell owned by the tile holding its centroid. Window: the tile grown to its +cells' bounds plus a margin of halo + 32 model px. The halo is measured from the loaded model, 96 px +for `V1.pt`. Minimum window: 1056 model px, so the valid-padding path is always taken. Neighbours +are rasterised too, since they shape the binary mask Nimbus sees; only owned cells are scored. + +**Tiling is meant to change nothing Nimbus computes; at 0.65 µm/px it does, measurably.** + +- The one global step, the per-channel factor, is computed once per store and shared by every + window. A channel with no factor is never passed on, or Nimbus would fall back to the window's + own quantile. +- BatchNorm runs in eval mode on fixed statistics, and test-time augmentation averages within one + input. No statistic crosses windows. +- A margin of at least the halo gives every owned cell the receptive field of whole-image inference. +- Upstream uses reflect padding up to 1024 px and tile-and-stitch above it, with different results. + The minimum window keeps every window on the valid path, as upstream whole-slide inference is. + +Measured on exemplar-001 crops, scores in [0, 1], with the real model on CPU: + +| Pixel size | Crop | Whole image against upstream | Tiled against whole image (2 × 2 windows) | +| ---------- | ----------- | ---------------------------- | ----------------------------------------- | +| 1.0 | 1280 × 1280 | max 7.2e-07 | max 0 (window origins on the 16 px grid) | +| 0.65 | 2100 × 2100 | max 3.0e-08, mean 4.3e-09 | max 0.414, mean 0.0113 (origins off grid) | + +The 1.0 tiling result is uninformative: its window origins are multiples of the model's 16 px +pooling period. At 0.65 the origins fall off that grid and some cells move by up to 0.41, so the +claim "tiling changes no score" does not hold there. Cause not yet found; fixing it is open work +(Task 11 follows up). The 0.65 test is marked xfail with these numbers. + +**Normalisation is per store.** Per core on a TMA, per image otherwise. A slide-wide factor would +erase differences between patients' cores. The cost: a core with no positive cells has noise +stretched to [0, 1]. The factor is the exact 0.999 quantile of nonzero pixels over a fixed-stride +subsample, so it is deterministic. Slide-wide is a ROADMAP item. A channel with no nonzero pixel +is NaN and listed in `uns`. + +**Test-time augmentation is fixed on, upstream code unchanged.** It is the Nimbus default, and +it is the same setting on CPU and GPU. CPU against GPU agreement is still to be measured on the cluster. Upstream functions (`prepare_binary_mask`, +`prepare_input_data`, `test_time_aug`, `segment_mean`) are called as `predict_fovs` calls them. + +**Cells only.** Nimbus was trained on whole-cell masks, so `use_nimbus` requires `segment_cells`. + +**One pixel size.** `pixel_size` serves InstanSeg and Nimbus. `instanseg_pixel_size` is deprecated, +and removed at the next major release. + +**Weights are baked in.** `V1.pt` (MIT, from HF `JLrumberger/Nimbus-Inference`) is inside +`docker.io/josenimo/nimbus:0.0.5`, with `HF_HUB_OFFLINE=1`. + +**Open: magnification.** The code sets `MODEL_UM_PER_PX = 1.0` in `bin/nimbus_cells.py`, treating Nimbus' "10x" as +1 µm/px; resize scale, window sizes and `magnification = 10 * MODEL_UM_PER_PX / pixel_size` all follow it. Upstream never defines it ([issue #61](https://github.com/angelolab/Nimbus-Inference/issues/61)), +and 10x is often 0.5 µm/px. Both are compared on real data before the default is chosen. + +### VirTues + +**Slide statistics over tissue pixels.** Intensities are capped at the 0.99 quantile, `log1p` +transformed and z-scored per marker, per slide, over tissue pixels (`use_tissue_segmentation` is +required). On a TMA every core of a slide shares them, unlike Nimbus's per-core factor, so cells +stay comparable across cores and patients. The released weights were trained with the cap per image +and mean and SD per dataset; per-slide statistics depart from that, and `virtues_stats` is the way +back to dataset-wide ones. Statistics come from integer histograms, equal to numpy's quantile on +the pooled pixels; off 1 µm/px, on resampled values rounded to integers (the model input is not rounded). + +**A core with no tissue does not stop the run.** sopa writes no ROI when it finds no tissue; such a +store counts as zero tissue, with a warning, and its cells are still embedded. A slide with no tissue +at all stops, naming it. sopa keeps the ROI on its coarsest pyramid level, so it is mapped to image +pixels first. + +**One task per store, every method at once.** The GPU pass does not depend on cell masks; only the +averaging into cells does, and it is repeated per method. Per-tile tasks are on the ROADMAP. + +**One global crop grid, so tiles match upstream.** Upstream's crop grid (128 px every 42 px, padded +by 120 px) is built once on the whole padded image. A tile embeds every crop touching its cells, so +each cell sees upstream's crop set. Attention never crosses crops, and resampling weights depend +on global coordinates only, so tiles give identical rows to a whole-image run with exact arithmetic +(tested with a fake encoder). On an A40 the fp16 encoder is too: batch 32 vs 8 and tile 512 vs 2048 +give identical rows (parity tool). + +**ESM-2 without attention contacts.** Upstream's `embed` keeps every attention map (about 25 GB for +Ki-67); we skip them. The embeddings are the same. + +**Embed only channels with a `uniprot_id`, never DNA.** No parameter: the sheet decides. Upstream +leaves DNA stains out, so a `dna` row with an ID is an error, and no Histone H3 mapping is made. + +**Cells only; cell, square and tissue embeddings.** Like upstream, no nuclei. A square is kept at +30% tissue or more; the tissue embedding is the mean of the kept squares. Squares are shapes with a +table, and the tissue vector has no region, as one row per store does not map onto the tissue polygons. + +**Float16, `sp32`.** Embeddings are stored as float16, half the size, and enough for 512 numbers +per cell. `sp32` is the authors' default and benchmarked model; it is CC BY-NC 4.0, so non-commercial +use only. `sp31` (MIT) and `imc14` are not wired in. + +**GPU, preprocessing and pixel size required.** FlashAttention has no CPU path. A stitched input has +no marker sheet, so no UniProt IDs. The model runs at 1 µm/px. The whole run is then on GPU, +segmentation included, so outlines differ slightly from a CPU run. + +**Weights and sequences are baked in.** `docker.io/josenimo/virtues:d2c25e1-2`: virtues `d2c25e1`, +spora-io `ef15868`, FlashAttention 2.7.4.post1, torch 2.5.1+cu124, ESM-2 `esm2_t30_150M_UR50D`, +human Swiss-Prot with isoforms (release 2026_04), `HF_HUB_OFFLINE=1`. + +**Checked on an A40:** every cell within cosine 0.99999999 of upstream's code; repeat runs identical. + +**Open:** usefulness on real data. + ## Quantification **Shapes are read in tile windows, not segmentation patches.** `patch_width_pixel` is tuned for diff --git a/docs/images/pipeline_paths.svg b/docs/images/pipeline_paths.svg index aa2d4ba..1078f84 100644 --- a/docs/images/pipeline_paths.svg +++ b/docs/images/pipeline_paths.svg @@ -1,8 +1,8 @@ - + -{"groups":[{"color":"#0072B2","id":"wsi","label":"Whole slide"},{"color":"#D55E00","id":"tma","label":"Tissue microarray"}],"height":1036,"match":{"flags":"i","target":"fqProcessName","type":"regex"},"nodes":[{"groups":["tma","wsi"],"h":28.8,"id":"BASICPY","label":"Illumination (BaSiCPy)","patterns":[],"r":10.8,"region":"preprocessing","rx":10.8,"w":21.6,"x":202.3,"y":223.6},{"groups":["tma","wsi"],"h":28.8,"id":"ASHLAR","label":"Stitch + register (Ashlar)","patterns":[],"r":10.8,"region":"preprocessing","rx":10.8,"w":21.6,"x":287.3,"y":223.6},{"groups":["tma"],"h":21.6,"id":"COREOGRAPH","label":"TMA dearray (Coreograph)","patterns":[],"r":10.8,"region":"preprocessing","rx":10.8,"w":21.6,"x":571.2,"y":127.2},{"groups":["tma","wsi"],"h":28.8,"id":"BACKSUB","label":"Background subtraction","patterns":[],"r":10.8,"region":"preprocessing","rx":10.8,"w":21.6,"x":824.5,"y":223.6},{"groups":["tma","wsi"],"h":28.8,"id":"TO_SPATIALDATA","label":"SpatialData + patches","patterns":[],"r":10.8,"region":"store","rx":10.8,"w":21.6,"x":1253.9,"y":223.6},{"groups":["tma","wsi"],"h":28.8,"id":"PROJECT_CHANNELS","label":"Channel projection","patterns":[],"r":10.8,"region":"segmentation","rx":10.8,"w":21.6,"x":1663.0,"y":123.6},{"groups":["tma","wsi"],"h":28.8,"id":"SEGMENT_PATCH_CELLPOSE","label":"Cellpose-SAM","patterns":[],"r":10.8,"region":"segmentation","rx":10.8,"w":21.6,"x":1748.0,"y":123.6},{"groups":["tma","wsi"],"h":28.8,"id":"SEGMENT_PATCH_INSTANSEG","label":"InstanSeg","patterns":[],"r":10.8,"region":"segmentation","rx":10.8,"w":21.6,"x":1662.5,"y":323.6},{"groups":["tma","wsi"],"h":28.8,"id":"LINK_COMPARTMENTS","label":"Link nucleus ↔ cell","patterns":[],"r":10.8,"region":"segmentation","rx":10.8,"w":21.6,"x":1978.3,"y":223.6},{"groups":["tma","wsi"],"h":28.8,"id":"AGGREGATE","label":"Quantify per cell","patterns":[],"r":10.8,"region":"segmentation","rx":10.8,"w":21.6,"x":2063.3,"y":223.6},{"groups":["tma"],"h":21.6,"id":"MERGE_SPATIALDATA","label":"Merge cores per slide","patterns":[],"r":10.8,"region":"output","rx":10.8,"w":21.6,"x":2032.8,"y":690.4},{"groups":["tma","wsi"],"h":28.8,"id":"PUBLISH_SPATIALDATA","label":"Publish SpatialData","patterns":[],"r":10.8,"region":"output","rx":10.8,"w":21.6,"x":1802.4,"y":594.0},{"groups":["tma","wsi"],"h":36.0,"id":"QC_METRICS","label":"QC metrics","patterns":[],"r":10.8,"region":"qc","rx":10.8,"w":21.6,"x":380.8,"y":590.4},{"groups":["tma","wsi"],"h":36.0,"id":"QC_REPORT","label":"QC report","patterns":[],"r":10.8,"region":"qc","rx":10.8,"w":21.6,"x":295.8,"y":590.4},{"groups":["tma","wsi"],"h":36.0,"id":"COMPARE_SEGMENTATIONS","label":"Compare methods","patterns":[],"r":10.8,"region":"qc","rx":10.8,"w":21.6,"x":210.8,"y":590.4},{"groups":["tma"],"h":21.6,"id":"MERGE_REPORT","label":"Slide report","patterns":[],"r":10.8,"region":"qc","rx":10.8,"w":21.6,"x":125.8,"y":583.2}],"regions":[{"id":"preprocessing","label":"Preprocessing"},{"id":"store","label":"SpatialData"},{"id":"segmentation","label":"Segmentation"},{"id":"output","label":"Output"},{"id":"qc","label":"Quality control"}],"title":"CosciaLab/histo","version":"1.0","width":2280} +{"groups":[{"color":"#0072B2","id":"wsi","label":"Whole slide"},{"color":"#D55E00","id":"tma","label":"Tissue microarray"}],"height":879,"match":{"flags":"i","target":"fqProcessName","type":"regex"},"nodes":[{"groups":["tma","wsi"],"h":28.8,"id":"BASICPY","label":"Illumination (BaSiCPy)","patterns":[],"r":10.8,"region":"preprocessing","rx":10.8,"w":21.6,"x":232.7,"y":168.6},{"groups":["tma","wsi"],"h":28.8,"id":"ASHLAR","label":"Stitch + register (Ashlar)","patterns":[],"r":10.8,"region":"preprocessing","rx":10.8,"w":21.6,"x":343.7,"y":168.6},{"groups":["tma"],"h":21.6,"id":"COREOGRAPH","label":"TMA dearray (Coreograph)","patterns":[],"r":10.8,"region":"preprocessing","rx":10.8,"w":21.6,"x":653.6,"y":120.0},{"groups":["tma","wsi"],"h":28.8,"id":"BACKSUB","label":"Background subtraction","patterns":[],"r":10.8,"region":"preprocessing","rx":10.8,"w":21.6,"x":932.9,"y":168.6},{"groups":["tma","wsi"],"h":28.8,"id":"TO_SPATIALDATA","label":"SpatialData + patches","patterns":[],"r":10.8,"region":"store","rx":10.8,"w":21.6,"x":1496.3,"y":123.6},{"groups":["tma","wsi"],"h":28.8,"id":"PROJECT_CHANNELS","label":"Channel projection","patterns":[],"r":10.8,"region":"segmentation","rx":10.8,"w":21.6,"x":1379.8,"y":353.8},{"groups":["tma","wsi"],"h":28.8,"id":"SEGMENT_PATCH_CELLPOSE","label":"Cellpose-SAM","patterns":[],"r":10.8,"region":"segmentation","rx":10.8,"w":21.6,"x":1268.8,"y":353.8},{"groups":["tma","wsi"],"h":28.8,"id":"SEGMENT_PATCH_INSTANSEG","label":"InstanSeg","patterns":[],"r":10.8,"region":"segmentation","rx":10.8,"w":21.6,"x":1379.8,"y":533.8},{"groups":["tma","wsi"],"h":28.8,"id":"LINK_COMPARTMENTS","label":"Link nucleus ↔ cell","patterns":[],"r":10.8,"region":"segmentation","rx":10.8,"w":21.6,"x":1012.5,"y":443.8},{"groups":["tma","wsi"],"h":28.8,"id":"AGGREGATE","label":"Quantify per cell","patterns":[],"r":10.8,"region":"features","rx":10.8,"w":21.6,"x":663.0,"y":533.8},{"groups":["tma","wsi"],"h":28.8,"id":"NIMBUS","label":"Nimbus scores","patterns":[],"r":10.8,"region":"features","rx":10.8,"w":21.6,"x":663.0,"y":443.8},{"groups":["tma","wsi"],"h":28.8,"id":"VIRTUES","label":"VirTues embeddings","patterns":[],"r":10.8,"region":"features","rx":10.8,"w":21.6,"x":663.0,"y":353.8},{"groups":["tma"],"h":21.6,"id":"MERGE_SPATIALDATA","label":"Merge cores per slide","patterns":[],"r":10.8,"region":"output","rx":10.8,"w":21.6,"x":288.0,"y":722.6},{"groups":["tma","wsi"],"h":28.8,"id":"PUBLISH_SPATIALDATA","label":"Publish SpatialData","patterns":[],"r":10.8,"region":"output","rx":10.8,"w":21.6,"x":655.4,"y":719.0},{"groups":["tma","wsi"],"h":28.8,"id":"QC_METRICS","label":"QC metrics","patterns":[],"r":10.8,"region":"qc","rx":10.8,"w":21.6,"x":943.6,"y":809.0},{"groups":["tma","wsi"],"h":28.8,"id":"QC_REPORT","label":"QC report","patterns":[],"r":10.8,"region":"qc","rx":10.8,"w":21.6,"x":1054.6,"y":809.0},{"groups":["tma","wsi"],"h":28.8,"id":"COMPARE_SEGMENTATIONS","label":"Compare methods","patterns":[],"r":10.8,"region":"qc","rx":10.8,"w":21.6,"x":1165.6,"y":809.0},{"groups":["tma"],"h":21.6,"id":"MERGE_REPORT","label":"Slide report","patterns":[],"r":10.8,"region":"qc","rx":10.8,"w":21.6,"x":1276.6,"y":812.6}],"regions":[{"id":"preprocessing","label":"Preprocessing"},{"id":"store","label":"SpatialData"},{"id":"segmentation","label":"Segmentation"},{"id":"features","label":"Cell features"},{"id":"output","label":"Output"},{"id":"qc","label":"Quality control"}],"title":"CosciaLab/histo","version":"1.0","width":1716} CosciaLab/histo - - -1 - - - -2 - - - -3 - - - -4 - - - -5 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Channel projection - -Illumination (BaSiCPy) - -Merge cores per slide - -QC metrics - -InstanSeg - -SpatialData + patches - -Cellpose-SAM - -Stitch + register (Ashlar) - -QCreport - -Publish SpatialData - -Link nucleus ↔ cell - -Comparemethods - -TMA dearray (Coreograph) - -Background subtraction - -Quantify per cell - -Slidereport - - -Whole slide - -Tissue microarray - -Optional step -created with nf-metro v2.1.0 + + +1 + + + +2 + + + +3 + + + +4 + + + +5 + + + +6 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +Channel projection + +Illumination (BaSiCPy) + +Merge cores per slide + +QC metrics + +InstanSeg + +SpatialData + patches + +Quantify per cell + +Nimbus scores + +VirTues embeddings + +Cellpose-SAM + +Stitch + register (Ashlar) + +QC report + +Publish SpatialData + +Link nucleus ↔ cell + +Compare methods + +TMA dearray (Coreograph) + +Background subtraction + +Slide report + + +Whole slide + +Tissue microarray + +Optional step +created with nf-metro v2.1.0 diff --git a/docs/output.md b/docs/output.md index d5dd806..05ced6e 100644 --- a/docs/output.md +++ b/docs/output.md @@ -6,7 +6,7 @@ This document describes the output produced by the pipeline. ## What runs -Three example routes; the metro map in the [README](https://github.com/CosciaLab/histo/blob/dev/README.md#steps) draws the whole-slide and TMA ones. Everything else is +Three example routes; the metro map in the [README](https://github.com/CosciaLab/histo/blob/dev/README.md#what-it-does) draws the whole-slide and TMA ones. Everything else is off by default. Each column's segmentation is an example: any methods and targets fit any route. Read down a column to get one run's process list, in order. The QC steps and @@ -129,6 +129,9 @@ HTML report then, so `{sample}_ashlar_qc/{sample}_ashlar_report.pdf` is where to - `shapes/{m}_cytoplasm` (both targets): each cell minus its linked nuclei, for cells with non-empty cytoplasm only, indexed by their cell ids. - `tables/{m}_table`: one row per cell, or per nucleus in a nuclei-only run. Below. + - `tables/{m}_nimbus` (`use_nimbus`): Nimbus scores, one row per cell. See [Nimbus scores](#nimbus-scores). + - `tables/{m}_virtues` (`use_virtues`): VirTues embeddings, one row per cell. See [VirTues embeddings](#virtues-embeddings). + - `shapes/virtues_niches`, `tables/virtues_niches_table`, `tables/virtues_tissue` (`use_virtues`): 128 µm tissue squares and their embeddings, and one embedding per store. - `{slide}_merged.zarr/` and `{slide}_merge_manifest.json` - **Dearrayed slides only**, instead of per-core stores: every core's elements in one store, and the manifest of what was merged. @@ -193,6 +196,90 @@ Refer to the [SpatialData docs](https://spatialdata.scverse.org/en/stable/) for `PUBLISH_SPATIALDATA` copies the store here, and exists only for that: it runs after the last step that writes to the store. +#### Nimbus scores + +`use_nimbus` adds `tables/{m}_nimbus` for each method: the same cells as `{m}_table`, one column per +marker, each value a confidence in [0, 1] that the marker is positive in that cell. + +```python +sdata["cellpose_nimbus"][:, "CD3"].X +``` + +- `X`: float32, cells by markers. NaN for a channel with no nonzero pixel, or a cell covering no + pixel centre. +- `var_names`: the marker names, in `nimbus_channels` order when given, else marker-sheet order. +- `obs`: `region`, `slide`, `core_id` and `cell_id` where present, copied from `{m}_table`. +- `uns['nimbus']`: how the scores were made. + +| `uns['nimbus']` key | Meaning | +| ------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | +| `nimbus_version` | Nimbus-Inference version. | +| `weights` | Weights file. | +| `weights_sha256` | sha256 of the weights file. | +| `channels` | Markers scored. | +| `factors` | Per-channel normalisation factor (0.999 quantile). | +| `unscored` | Channels with no nonzero pixel; their columns are NaN. | +| `pixel_size` | µm per pixel given by `pixel_size`. | +| `model_um_per_px` | µm per model pixel (1.0). Provisional; see [decisions](https://github.com/CosciaLab/histo/blob/dev/docs/decisions.md#learned-features). | +| `magnification` | `10 * model_um_per_px / pixel_size`. | +| `tile_size` | Tile edge, in image pixels (2048 model pixels). | +| `margin` | Context added around each tile, in image pixels. | +| `halo` | Model halo measured at start-up, in model pixels. | +| `min_window` | Smallest window, in image pixels (1056 model pixels). | +| `test_time_aug` | Always `true`. | +| `device` | `cpu` or `cuda`. | + +The same keys are published as `learned_features/{sample}_{m}_nimbus.json`, so provenance can be read without +opening the store. + +#### VirTues embeddings + +`use_virtues` adds three kinds of table, each row a 512-number embedding: + +- `tables/{m}_virtues`, for each method: the same cells as `{m}_table`. +- `shapes/virtues_niches` and `tables/virtues_niches_table`: non-overlapping 128 × 128 µm squares + with at least 30% tissue, one row each, with `tissue_fraction` in `obs`. Neither exists when no + square qualifies. +- `tables/virtues_tissue`: one row per store (a core on a TMA, else the image): the mean of the kept + squares, with `n_niches` in `obs`. NaN when no square is kept, or when tissue segmentation found no + tissue in the store; its cells are still embedded. + +```python +sdata["cellpose_virtues"].X # cells x 512, float16 +``` + +- `X`: float16. NaN for a cell covering no pixel at 1 µm/px, counted in `n_cells_without_pixel`. +- `var_names`: `virtues_0` to `virtues_511`. The columns have no marker meaning. +- `obs`: `region`, `slide`, `core_id` and `cell_id` where present, copied from `{m}_table`. The + cell table's region is `{m}_cells` and its instance key `cell_id`; the squares' is `niche_id`. +- `uns['virtues']`: how the embeddings were made, the same on all of them. + +| `uns['virtues']` key | Meaning | +| ------------------------ | ---------------------------------------------------------------------- | +| `virtues_commit` | VirTues code commit. | +| `weights` | Weights file (`sp32`). | +| `weights_sha256` | sha256 of the weights file. | +| `esm_model` | ESM-2 model that embeds each marker's sequence. | +| `uniprot_release` | UniProt release of the sequences. | +| `channels` | Marker name to `uniprot_id`, for channels embedded. | +| `unembedded` | Channels without an ID, left out. | +| `stats` | Per marker: `uniprot_id`, `cap`, `mean`, `sd`, `tissue_pixels`. | +| `pixel_size` | µm per pixel given by `pixel_size`. | +| `model_um_per_px` | µm per model pixel (1.0). | +| `crop_size`, `crop_step` | Crop edge (128) and step between a cell's crops (42), in model pixels. | +| `patch_size` | Patch edge (8), in model pixels. | +| `padding` | Zeros added round the image edge (120), in model pixels. | +| `tile_size` | Tile edge (2048), in model pixels. | +| `batch_size` | Crops per GPU batch. | +| `device` | `cuda`. | +| `n_cells` | Cells per method. | +| `n_cells_without_pixel` | Cells per method with a NaN row. | +| `n_niches_kept` | Squares kept. | +| `n_niches_dropped` | Squares dropped for too little tissue. | + +Also published to `learned_features/`: `{sample}_virtues.json` with these keys, and, unless +`virtues_stats` is given, `{slide}_virtues_stats.json` with the statistics computed, one per slide. + #### From 1.x | 1.x | 2.0 | diff --git a/docs/pipeline_paths.mmd b/docs/pipeline_paths.mmd index 34a8e0b..87a28ee 100644 --- a/docs/pipeline_paths.mmd +++ b/docs/pipeline_paths.mmd @@ -6,13 +6,16 @@ %%metro marker: PROJECT_CHANNELS | circle, #cccccc %%metro marker: LINK_COMPARTMENTS | circle, #cccccc %%metro marker: COMPARE_SEGMENTATIONS | circle, #cccccc +%%metro marker: NIMBUS | circle, #cccccc +%%metro marker: VIRTUES | circle, #cccccc %%metro marker_legend: circle, #cccccc | Optional step -%%metro grid: preprocessing | 0,0 -%%metro grid: store | 1,0 -%%metro grid: segmentation | 2,0 -%%metro grid: output | 2,1 -%%metro grid: qc | 0,1,1,2 -%%metro legend: bl +%%metro grid: preprocessing | 0,0,1,2 +%%metro grid: store | 2,0 +%%metro grid: features | 0,1 +%%metro grid: segmentation | 1,1,1,2 +%%metro grid: output | 0,2 +%%metro grid: qc | 1,2,1,2 +%%metro legend: 60,290 graph LR subgraph preprocessing [Preprocessing] @@ -32,23 +35,26 @@ graph LR end subgraph segmentation [Segmentation] - + %%metro direction: RL + %%metro entry: top | wsi, tma PROJECT_CHANNELS([Channel projection]) SEGMENT_PATCH_CELLPOSE([Cellpose-SAM]) SEGMENT_PATCH_INSTANSEG([InstanSeg]) LINK_COMPARTMENTS([Link nucleus ↔ cell]) - AGGREGATE([Quantify per cell]) PROJECT_CHANNELS -->|wsi, tma| SEGMENT_PATCH_CELLPOSE SEGMENT_PATCH_CELLPOSE -->|wsi, tma| LINK_COMPARTMENTS SEGMENT_PATCH_INSTANSEG -->|wsi, tma| LINK_COMPARTMENTS - LINK_COMPARTMENTS -->|wsi, tma| AGGREGATE end - subgraph output [Output] + subgraph features [Cell features] %%metro direction: RL - %%metro entry: right | wsi, tma - %%metro exit: left | wsi, tma + AGGREGATE([Quantify per cell]) + NIMBUS([Nimbus scores]) + VIRTUES([VirTues embeddings]) + end + + subgraph output [Output] MERGE_SPATIALDATA([Merge cores per slide]) PUBLISH_SPATIALDATA([Publish SpatialData]) @@ -56,7 +62,6 @@ graph LR end subgraph qc [Quality control] - %%metro direction: RL QC_METRICS([QC metrics]) QC_REPORT([QC report]) COMPARE_SEGMENTATIONS([Compare methods]) @@ -70,15 +75,25 @@ graph LR BACKSUB -->|wsi, tma| TO_SPATIALDATA TO_SPATIALDATA -->|wsi, tma| PROJECT_CHANNELS TO_SPATIALDATA -->|wsi, tma| SEGMENT_PATCH_INSTANSEG + LINK_COMPARTMENTS -->|wsi, tma| AGGREGATE + LINK_COMPARTMENTS -->|wsi, tma| NIMBUS + LINK_COMPARTMENTS -->|wsi, tma| VIRTUES AGGREGATE -->|wsi| PUBLISH_SPATIALDATA + NIMBUS -->|wsi| PUBLISH_SPATIALDATA + VIRTUES -->|wsi| PUBLISH_SPATIALDATA AGGREGATE -->|tma| MERGE_SPATIALDATA + NIMBUS -->|tma| MERGE_SPATIALDATA + VIRTUES -->|tma| MERGE_SPATIALDATA PUBLISH_SPATIALDATA -->|wsi, tma| QC_METRICS - %% Two lines, two rows: left to right, then back right to left through Output and QC. + %% Two lines, three rows: left to right, back right to left, then left to right again. %% Grey stations are optional steps. Grouped stations: %% COREOGRAPH COREOGRAPH_DETECT, COREOGRAPH_SELECT, COREOGRAPH %% TO_SPATIALDATA TO_SPATIALDATA, SET_CHANNEL_NAMES, MAKE_IMAGE_PATCHES %% AGGREGATE RESOLVE, AGGREGATE, WRITE_SEGMENTATIONS + %% NIMBUS NIMBUS + %% VIRTUES VIRTUES_HISTOGRAM, VIRTUES_STATS, VIRTUES, WRITE_FEATURES (one write for both models) %% QC_METRICS QC_METRICS, QC_IMAGES %% Schematic, not wiring: QC reads the store alongside publishing, not after it. + %% Schematic: Nimbus and VirTues run after AGGREGATE; drawn beside it as per-cell outputs. %% Edges left out are described in docs/CONTRIBUTING.md#what-the-map-leaves-out. diff --git a/docs/superpowers/plans/2026-11-07-segmentation-benchmark.md b/docs/superpowers/plans/2026-11-07-segmentation-benchmark.md new file mode 100644 index 0000000..de10c6a --- /dev/null +++ b/docs/superpowers/plans/2026-11-07-segmentation-benchmark.md @@ -0,0 +1,363 @@ +# cpsam_v2 and Segmentation Benchmark Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Cellpose defaults to `cpsam_v2` from a new image, and a SLURM-array benchmark scores +168 preprocessing settings against manual masks, ending in a ~13-slide `.pptx`. + +**Architecture:** Part A bumps every sopa module to `josenimo/sopa:2.3.0-1` (2.3.0 plus baked +`cpsam_v2`), defaults `pretrained_model`, and guards against missing weights. Part B is a +package `tools/segmentation_benchmark/`: `prepare` (Mac) normalises three datasets to one crop +layout, `run` (cluster, in the image) does one setting per array task, `report` (Mac) makes +tables, figures and montages for the deck. + +**Tech Stack:** Python (numpy, scipy, scikit-image, tifffile, pandas, matplotlib, roifile), +pytest via `uv run --frozen --group dev pytest tests/unit`, sopa 2.3.0, cellpose 4.2.1.1, +Docker buildx, SLURM + Apptainer, Nextflow/nf-test for Part A. + +**Spec:** `docs/superpowers/specs/2026-11-07-segmentation-benchmark-design.md`. Read it first. + +## Global Constraints + +- Read CLAUDE.md. Branch `feat/segmentation-benchmark`; never `git push`. Commit titles under + ~60 chars, ending with the `Co-Authored-By` line. Small single-concern commits. +- Pushing `docker.io/josenimo/sopa:2.3.0-1` to Docker Hub is cleared. Never run `sbatch`/`srun`; + write the command, the user submits. Never touch `NXF_SINGULARITY_CACHEDIR`. +- Data lives outside the repo, in `$BENCH = /Users/jnimoca/Jose_BI/3_Projects/Segmentation_Benchmark` + (Mac) and the user's cluster scratch. Never commit images, masks or results. +- Model: `cpsam_v2`, `diameter=30`, no rescaling. Cell plane = every non-DNA channel. +- Today's defaults: `max`, low percentile 1, high 99.9, `projection_sigma` 1, `gaussian_sigma` 1, + `clip_limit` 0.2, flow 2, cellprob −6. +- Array layout, fixed: indices 0–143 cells on raw-channel datasets, 144–155 cells on TissueNet, + 156–167 nuclei on all datasets. +- IoU thresholds `(0.5, 0.6, 0.7, 0.8, 0.9)`; F1 at 0.5 is primary; per-threshold + `ap = tp / (tp + fp + fn)` (cellpose's definition), matching at `iou >= t`. +- Scoring is our own ~30 lines of numpy, not `cellpose.metrics`: it keeps cellpose and torch + out of the test environment. At IoU ≥ 0.5 matches are unique, so no Hungarian step is needed. + +## Review Focus + +1. A crop with no true or no predicted objects: F1 is 0 when only one side is empty, NaN when + both are, and NaN crops are counted, not averaged. Test in Task 4. +2. A marker that is flat in a crop (`percentile_bounds` returns None) is left out, as in the + pipeline; if every cell marker is flat, the cell plane is zeros, not a crash. Test in Task 6. +3. A resubmitted array task: an existing `results/N.csv` skips the task; a stale `N.csv.tmp` is + overwritten. Test in Task 8. +4. ImageJ ROI types other than polygon/freehand (oval, rectangle, composite) rasterise or fail + naming the crop and type; overlaps are logged per crop. Test in Task 7. +5. The Tonsil DNA channel: chosen as the channel brightest inside `GT_nuclei`, asserted to be + the last (DAPI); a mismatch fails. Test in Task 7. + +--- + +## Part A: cpsam_v2 in the pipeline + +### Task 1: Build and push `josenimo/sopa:2.3.0-1` + +**Files:** + +- Create: `/Users/jnimoca/Jose_BI/2_Infrastructure/PY47_test_SOPA/docker/Dockerfile.2.3.0-1` + (outside the repo; not committed) + +**Produces:** image `docker.io/josenimo/sopa:2.3.0-1`, linux/amd64, with +`/opt/cellpose_models/cpsam_v2`. + +- [ ] **Step 1:** Download `https://huggingface.co/mouseland/cellpose-sam/resolve/main/cpsam_v2` + to the scratchpad; record its `sha256`. +- [ ] **Step 2:** Write the Dockerfile: `FROM docker.io/josenimo/sopa:2.3.0`, `curl` the file + into `${CELLPOSE_LOCAL_MODELS_PATH}/cpsam_v2`, `sha256sum -c` against the recorded hash, + `chmod a+r`. Header comment: why it exists, one line. If the base lacks `curl`, use + `python -c "urllib.request.urlretrieve(...)"`. +- [ ] **Step 3:** `docker buildx build --platform linux/amd64 -t docker.io/josenimo/sopa:2.3.0-1 -f docker/Dockerfile.2.3.0-1 --load docker/` +- [ ] **Step 4: Verify offline.** + `docker run --rm --platform linux/amd64 --network none docker.io/josenimo/sopa:2.3.0-1 python -c "from cellpose import models; m = models.CellposeModel(pretrained_model='cpsam_v2'); print(m.pretrained_model)"` + Expected: prints `/opt/cellpose_models/cpsam_v2`, no "Downloading", no "not found" warning. + Also `pip list` diff against 2.3.0 is empty. +- [ ] **Step 5:** `docker push docker.io/josenimo/sopa:2.3.0-1`; report the digest to the user. + +### Task 2: Move modules to `sopa:2.3.0-1` + +**Files:** + +- Modify: `container` line in `modules/local/{aggregate,link_compartments,resolve,segment_patch,write_segmentations}/main.nf` +- Modify: `containers.tsv` (regenerated), `docs/CONTRIBUTING.md:158` + +- [ ] **Step 1:** Replace `josenimo/sopa:2.3.0"` with `josenimo/sopa:2.3.0-1"` in the five modules. +- [ ] **Step 2:** `tools/container_manifest.py`, then `tools/container_manifest.py --check`. Expected: exit 0. +- [ ] **Step 3:** CONTRIBUTING line 158: name `2.3.0-1` and that it adds `cpsam_v2`. +- [ ] **Step 4:** `prek run --all-files` and `nf-core pipelines lint`. Expected: pass. +- [ ] **Step 5:** Commit `Bump sopa image to 2.3.0-1 (cpsam_v2 weights)`. + +### Task 3: Default `cpsam_v2`, fail on missing weights + +**Files:** + +- Modify: `bin/segment_patch.py` (`METHOD_DEFAULTS`, new `check_weights`, call in `main`) +- Modify: `nextflow.config:71`, `nextflow_schema.json` (`pretrained_model`), `CHANGELOG.md`, + `docs/decisions.md` (the "Cellpose-SAM replaced Cellpose 3" paragraph) +- Test: `tests/unit/test_segment_patch.py` + +**Produces:** `check_weights(pretrained_model: str | None, models_dir: str | None) -> None`. + +- [ ] **Step 1: Failing tests** in `tests/unit/test_segment_patch.py`: + +```python +def test_cellpose_defaults_to_cpsam_v2(): + assert method_arguments({"method": "cellpose"})["pretrained_model"] == "cpsam_v2" + +def test_missing_weights_name_the_model(tmp_path): + with pytest.raises(ValueError, match=r"pretrained_model 'cpsam_v2' has no weights in .*CELLPOSE_LOCAL_MODELS_PATH"): + check_weights("cpsam_v2", str(tmp_path)) + +def test_weights_present_or_path_pass(tmp_path): + (tmp_path / "cpsam_v2").write_bytes(b"x") + check_weights("cpsam_v2", str(tmp_path)) + check_weights(str(tmp_path / "cpsam_v2"), None) # an existing path needs no models dir + +def test_unset_models_dir_fails_for_a_name(): + with pytest.raises(ValueError, match="CELLPOSE_LOCAL_MODELS_PATH is not set"): + check_weights("cpsam_v2", None) +``` + +- [ ] **Step 2:** `uv run --frozen --group dev pytest tests/unit/test_segment_patch.py -v`. Expected: 4 new FAIL. +- [ ] **Step 3:** Implement. `check_weights`: an existing path passes; otherwise the name must be a + file in `models_dir`. `main` calls it for cellpose with + `os.environ.get("CELLPOSE_LOCAL_MODELS_PATH")` before building the method. One-line "why" + comment: cellpose silently loads its default for an unknown name, then downloads. + `METHOD_DEFAULTS["cellpose"]["pretrained_model"] = "cpsam_v2"`, comment noting it is ours, + not sopa's. +- [ ] **Step 4:** Tests pass. +- [ ] **Step 5:** `nextflow.config`: `pretrained_model = 'cpsam_v2'`. Schema: add + `"default": "cpsam_v2"`, description "Cellpose weights: a name baked into the image + (`cpsam_v2`, `cpsam`) or a path". Let prek regenerate the params templates. +- [ ] **Step 6:** `nf-test test --tag stub,validation`. If a snapshot changes only by + `pretrained_model: cpsam_v2` in a spec, regenerate with `--update-snapshot` and check the diff + shows nothing else. +- [ ] **Step 7:** CHANGELOG: new `## Unreleased` section above v3.0.0 (the tag exists): "Cellpose + uses `cpsam_v2` (cellpose's own default); cell counts shift. `pretrained_model: cpsam` restores + the old model." `decisions.md`: one sentence after the Cellpose-SAM paragraph: `cpsam_v2` is the + default, following the cellpose developers; not benchmarked against `cpsam`. +- [ ] **Step 8:** prek, lint, pytest. Commit `Default Cellpose to cpsam_v2; fail on missing weights`. + +## Part B: the benchmark + +Package `tools/segmentation_benchmark/` (with `__init__.py`); tests in +`tests/unit/test_segmentation_benchmark.py`, importing `segmentation_benchmark.` +(conftest puts `tools/` on the path). Scripts that run as CLIs insert `bin/` on `sys.path`, as +`tools/benchmark_projection.py` does. + +### Task 4: Scoring + +**Files:** Create `tools/segmentation_benchmark/{__init__,scoring}.py` + +**Produces:** `IOU_THRESHOLDS = (0.5, 0.6, 0.7, 0.8, 0.9)`; +`score(true: np.ndarray, pred: np.ndarray) -> dict` with keys `n_true, n_pred, tp, fp, fn, f1, +ap_50, ap_60, ap_70, ap_80, ap_90, mean_ap` (`tp/fp/fn` at 0.5). + +- [ ] **Step 1: Failing tests:** + +```python +def square(labels, value, y, x, size=10): + labels[y:y + size, x:x + size] = value + +def test_identical_masks_score_one(): + t = np.zeros((50, 50), int); square(t, 1, 0, 0); square(t, 2, 20, 20) + s = score(t, t.copy()) + assert (s["tp"], s["fp"], s["fn"], s["f1"], s["mean_ap"]) == (2, 0, 0, 1.0, 1.0) + +def test_shifted_object_counts_by_iou(): + t = np.zeros((50, 50), int); square(t, 1, 0, 0) + p = np.zeros_like(t); square(p, 7, 0, 2) # IoU 80/120 = 0.667, labels need not match + s = score(t, p) + assert s["tp"] == 1 and s["ap_60"] == 1.0 and s["ap_70"] == 0.0 + +def test_one_side_empty_is_zero_both_empty_is_nan(): + t = np.zeros((50, 50), int); square(t, 1, 0, 0) + assert score(t, np.zeros_like(t))["f1"] == 0.0 + assert np.isnan(score(np.zeros_like(t), np.zeros_like(t))["f1"]) + +def test_split_cell_is_one_fn_two_fp(): + t = np.zeros((50, 50), int); square(t, 1, 0, 0, 20) + p = np.zeros_like(t); p[0:20, 0:10] = 1; p[0:20, 10:20] = 2 + s = score(t, p) + assert (s["tp"], s["fp"], s["fn"]) == (0, 2, 1) +``` + +- [ ] **Step 2:** Run; expect import FAIL. +- [ ] **Step 3:** Implement with overlap counts from `np.unique` over `(true, pred)` pixel pairs + (both > 0), object areas from `np.bincount`; `iou = inter / (area_t + area_p - inter)`; at + each threshold `tp = (iou >= t).sum()`. `f1 = 2tp / (2tp + fp + fn)`, NaN when the denominator + is 0. +- [ ] **Step 4:** Pass. **Step 5:** Commit `Benchmark: score masks by IoU matching`. + +### Task 5: Settings + +**Files:** Create `tools/segmentation_benchmark/settings.py`, `tools/segmentation_benchmark/settings.csv` (generated, committed) + +**Produces:** `TODAY: dict`; `build_settings() -> pd.DataFrame` with columns `index, target +("cells"|"nuclei"), scope ("raw"|"tissuenet"|"all"), projection_method, low_percentile, +projection_sigma, gaussian_sigma, clip_limit, flow_threshold, cellprob_threshold`; +`today_index(settings, target, scope) -> int`. CLI: `python settings.py --out settings.csv`. + +- [ ] **Step 1: Failing tests:** + +```python +def test_layout(): + s = build_settings() + assert len(s) == 168 and list(s["index"]) == list(range(168)) + assert (s[:144]["scope"] == "raw").all() and (s[144:156]["scope"] == "tissuenet").all() + assert (s[156:]["target"] == "nuclei").all() and (s[156:]["scope"] == "all").all() + +def test_today_is_in_every_block(): + s = build_settings() + for target, scope in [("cells", "raw"), ("cells", "tissuenet"), ("nuclei", "all")]: + row = s.loc[today_index(s, target, scope)] + assert (row["gaussian_sigma"], row["clip_limit"], row["flow_threshold"]) == (1, 0.2, 2) + +def test_committed_csv_matches(tmp_path): + committed = pd.read_csv(Path(settings.__file__).with_name("settings.csv")) + pd.testing.assert_frame_equal(committed, build_settings(), check_dtype=False) +``` + +- [ ] **Step 2–4:** Fail, implement with `itertools.product` over the spec's levels (raw block in + the spec's factor order), pass. TissueNet and nuclei rows carry `TODAY`'s projection values + (nuclei use them to build the nuclear plane; TissueNet ignores them). +- [ ] **Step 5:** Generate the CSV; commit `Benchmark: settings grid (168 array tasks)`. + +### Task 6: Preprocessing + +**Files:** Create `tools/segmentation_benchmark/preprocess.py` + +**Consumes:** `percentile_bounds`, `rescale`, `combine` from `bin/project_channels.py`. + +**Produces:** + +- `project(image: np.ndarray, nuclear: int, method: str, low: float, sigma: float, high: float = 99.9) -> np.ndarray`: + (2, Y, X) uint16, order `[cell, nuclear]`, the pipeline's order (rescale, Gaussian per channel, + combine, `* 65535 + 0.5`). +- `sopa_preprocess(image: np.ndarray, gaussian_sigma: float, clip_limit: float) -> np.ndarray`: + moved from `tools/benchmark_projection.py`, which then imports it. +- `pad_to(image: np.ndarray, size: int = 256) -> tuple[np.ndarray, tuple[int, int]]` (reflect, + bottom/right) and `unpad(labels, shape) -> np.ndarray` (crop, `relabel_sequential`). + +- [ ] **Step 1: Failing tests:** + - `test_project_matches_pipeline`: build a one-level store as `tests/unit/test_project_channels.py`'s + `store` fixture does (under 2000 px, no tissue mask, so the pipeline's percentiles come from + the full image), run `project_channels.project`, read `_projected`, and + `np.testing.assert_array_equal` against `project(...)` on the same array. + - `test_flat_marker_left_out_all_flat_gives_zeros`: one flat cell marker changes nothing + against the same image without it; all flat gives a zero cell plane. + - `test_pad_round_trip`: a 100×100 image pads to 256×256; `unpad` returns 100×100 labels + numbered 1..n. +- [ ] **Step 2–4:** Fail, implement, pass. Run `pytest tests/unit` in full (benchmark_projection + now imports from here). +- [ ] **Step 5:** Commit `Benchmark: pipeline-equal projection and padding`. + +### Task 7: `prepare` + +**Files:** Create `tools/segmentation_benchmark/prepare.py`; modify `pyproject.toml` (add +`roifile` to `dev`, with a one-line reason), `uv.lock` + +**Produces:** under `--out`, `crops///{image,cells,nuclei}.tif` (image C,Y,X as +stored; labels uint32) and `crops.csv` with columns `dataset, crop, platform, tissue, +pixel_size_um, channels ("|"-joined), nuclear (int), height, width, montage (bool)`. Functions: +`rois_to_labels(rois: list, shape: tuple[int, int]) -> tuple[np.ndarray, float]` (labels, +overlap share); `tonsil_nuclear_channel(image, nuclei) -> int`; one reader per dataset: +`read_crossplatform(root) / read_tonsil(root) / read_tissuenet(npz)`, each yielding +`(row: dict, image, cells, nuclei)`. + +- [ ] **Step 1: Fetch** (user steps where tokens are needed; document in the README, Task 8): + Tonsil via the Zenodo API (no token); Cross-platform with + `uvx --from synapseclient synapse get -r syn27624812 --downloadLocation $BENCH/raw/crossplatform` + (`SYNAPSE_AUTH_TOKEN`); TissueNet 1.1 zip downloaded by the user from datasets.deepcell.org. +- [ ] **Step 2: Inspect, then write findings into the module docstring:** Cross-platform crop + TIFF axes, dtype and whether channel names are in its metadata or only in + `Annotation Panel Table.xlsx` (if only there, add `openpyxl` to `dev`); which index is DAPI; + ROI types present. TissueNet test npz: confirm `X` is (N, 256, 256, 2) = (nuclear, membrane) + and which `y` channel is whole-cell, by comparing foreground areas; read `meta` for + platform/tissue. Pixel size: 0.5 µm/px for TissueNet, Table 2 of the paper for Cross-platform, + "unknown" for Tonsil. +- [ ] **Step 3: Failing tests:** + - `test_polygon_rois_rasterise`: two `roifile.ImagejRoi.frompoints` squares → labels 1, 2 with + the expected areas; overlap 0. + - `test_overlap_goes_to_later_roi_and_is_reported`: two overlapping squares → overlap share > 0, + overlapped pixels labelled 2. + - `test_unsupported_roi_names_type`: an ROI whose type cannot be rasterised raises naming it. + - `test_tonsil_dna_is_brightest_in_nuclei`: synthetic 3-channel image, channel 2 bright inside a + nuclear mask → 2. +- [ ] **Step 4–5:** Implement (rasterise with `skimage.draw.polygon` on `roi.coordinates()`; + `read_tonsil` asserts `tonsil_nuclear_channel == 6`); pass. +- [ ] **Step 6: Run** `uv run --frozen --group dev python tools/segmentation_benchmark/prepare.py --raw $BENCH/raw --out $BENCH/data`. + Report per dataset: crops, true cells, max overlap share. Montage crops: the first crop by name + of each Cross-platform platform (3), the first two Tonsil crops, the first TissueNet crop. +- [ ] **Step 7:** Commit `Benchmark: prepare datasets into one crop layout`. + +### Task 8: `run`, the SLURM script and the README + +**Files:** Create `tools/segmentation_benchmark/run.py`, `run_array.sbatch`, `README.md` + +**Consumes:** Tasks 4–7. + +**Produces:** `run.py --data DIR --setting-index N --out DIR [--gpu] [--limit-crops K] [--dataset NAME]` +writes `results/N.csv`: one row per crop, columns `index, target, dataset, crop, platform` + +`score()` keys + `seconds`; labels for montage crops to `labels/N/__.tif`. + +- [ ] **Step 1: Failing tests** (segmentation stubbed by monkeypatching `run.segment` to return + the true labels): + - `test_skips_existing_result`: an existing `results/3.csv` → returns without calling `segment`. + - `test_overwrites_stale_tmp_and_writes_atomically`: a stale `3.csv.tmp` → final `3.csv` has one + row per crop, F1 1.0; no `.tmp` left. + - `test_scope_selects_crops`: a `tissuenet`-scope setting reads only TissueNet crops; `raw` + excludes them. +- [ ] **Step 2–4:** Implement. `segment(image, channels, setting, gpu) -> labels` builds + `sopa.segmentation.methods.cellpose_patch(diameter=30, channels=..., pretrained_model="cpsam_v2", +flow_threshold=..., cellprob_threshold=..., gpu=gpu)` once per task and calls it per crop. + Cells on raw data: `project` → `sopa_preprocess` → segment `["cell", "nuclear"]`. TissueNet: + the stored (membrane, nuclear) planes, rescaled to uint16, no projection. Nuclei: the projected + nuclear plane only (TissueNet: its nuclear plane), `["nuclear"]`. Pad crops under 256 px. Pass. +- [ ] **Step 5: `run_array.sbatch`:** `--array=0-167%8`, `--gres=gpu:a40:1`, `--constraint=ceph` + (as `conf/mdc.config`), `--cpus-per-task=8`, `--mem=32G`, `--time` left as `TIME` placeholder + for the timing job to set, logs to `logs/%A_%a.out`. Body: + `apptainer exec --nv "$SIF" python tools/segmentation_benchmark/run.py --data "$DATA" --setting-index "$SLURM_ARRAY_TASK_ID" --out "$OUT" --gpu`, + with `SIF`, `DATA`, `OUT` required environment variables (fail if unset). +- [ ] **Step 6: Container smoke test (Mac, one tiny crop):** + `docker run --rm --platform linux/amd64 --network none -v $PWD:/repo -v $BENCH/data:/data -w /repo docker.io/josenimo/sopa:2.3.0-1 python tools/segmentation_benchmark/run.py --data /data --setting-index --out /tmp/out --dataset tonsil --limit-crops 1` + Expected: one row, F1 > 0. +- [ ] **Step 7: README** (~40 lines): the three steps with commands, data layout, tokens, the + timing job (`--array=` with `--limit-crops 20`), then the full array, then rsync + back. Commit `Benchmark: run one setting per SLURM array task`. + +### Task 9: Cluster runs (user submits) — gate + +- [ ] **Step 1:** Give the user: rsync of `$BENCH/data` and the repo to scratch; the image staging + command from `docs/usage.md`; the timing `sbatch` command. +- [ ] **Step 2:** From the timing log, set `--time` (crops × seconds per crop × 1.5); commit. +- [ ] **Step 3:** The full-array command. When done, the user rsyncs `results/` and `labels/` to + `$BENCH/results`. Check 168 result files; list missing indices for a resubmit. + +### Task 10: `report` + +**Files:** Create `tools/segmentation_benchmark/report.py` + +**Produces:** in `--out`: `summary.csv` (per setting × dataset: mean and SD of F1 and mean AP, +n crops, n NaN crops), `effects_.png` (mean Cross-platform F1 per level, each factor +marginalised), `interaction.png` (heatmap of the two factors with the largest effect range), +`platforms.png` (best vs today per platform/dataset), `montage_.png` (today vs best, +outlines on the projection preview), `headline.json` (best and today's rows, F1 difference). + +- [ ] **Step 1: Failing test** `test_summary_ranks_by_crossplatform_f1`: a fake `results/` of + three settings where setting 2 is best on Cross-platform but worst on TissueNet → + `headline.json` names 2. +- [ ] **Step 2–4:** Implement (matplotlib, read the dataviz skill first), pass. +- [ ] **Step 5:** Run on real results; look at every PNG. Commit `Benchmark: report tables and figures`. + +### Task 11: The deck + +- [ ] **Step 1:** Load the `anthropic-skills:pptx` skill. Build ~13 slides from Task 10's outputs + only, in the spec's order, to `$BENCH/segmentation_benchmark.pptx`. Caveats slide: Tonsil's + 100 px crops and small cells, possible training overlap, crop vs slide percentiles, fixed + diameter. +- [ ] **Step 2:** Render to images and check each slide by eye. Give the user the path. + +Adoption (new defaults, `decisions.md` rewrite, ROADMAP) is a separate change after the user +reads the deck. diff --git a/docs/superpowers/plans/2026-11-11-learned-features-nimbus.md b/docs/superpowers/plans/2026-11-11-learned-features-nimbus.md new file mode 100644 index 0000000..1ead65d --- /dev/null +++ b/docs/superpowers/plans/2026-11-11-learned-features-nimbus.md @@ -0,0 +1,601 @@ +# Learned features (Nimbus) Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** An optional `LEARNED_FEATURES` stage that writes a `{method}_nimbus` table of per-cell, +per-marker Nimbus scores into each store. It is built so KRONOS and VirTues can be added as further +models. + +**Architecture:** + +- `featureSpecs(params)` builds one spec per enabled model, as `segmentationSpecs` does. +- `LEARNED_FEATURES` runs after `SEGMENTATION`, with one `NIMBUS` task per store × segmentation + method. +- Each `NIMBUS` task runs a tiled runner (`bin/nimbus_cells.py`) and writes an h5ad. +- One `WRITE_FEATURES` task per store writes the tables in. +- QC, the comparison and the merge then read that store. +- `pixel_size` replaces `instanseg_pixel_size`, which stays as a deprecated alias. + +**Tech Stack:** Nextflow DSL2, nf-test, Python 3.12, spatialdata 0.8, anndata, Nimbus-Inference +0.0.5, torch, pytest. + +**Spec:** `docs/superpowers/specs/2026-11-11-learned-features-nimbus-design.md` + +## Global Constraints + +- **No network at run time.** Weights are baked into the image, and the image sets + `HF_HUB_OFFLINE=1`. +- **Image and pushing.** The image is `docker.io/josenimo/nimbus:0.0.5`. The user pushes it. + Agents never `docker push` or `git push`. +- **Schema.** Optional steps are schema booleans with `default: false`. Edit + `nextflow_schema.json` by hand. Never edit `assets/params_template*.yml`. +- **Stubs.** Every local module that creates a file has a `stub:` block. Update a stub in the same + commit as the outputs it mirrors. +- **Container manifest.** Regenerate `containers.tsv` with `tools/container_manifest.py` after + adding a module. +- **Errors in operators.** Use `error()`, not `assert`, inside channel operators. +- **Commits.** + - `git add` with explicit paths only. + - Titles under ~60 characters, and a body of a few lines or none. + - End with `Co-Authored-By: Claude Opus 5.5 `. + - If prek reformats a file, re-add it and commit again. +- **Comments.** Code comments are one line of "why". +- **Pinned values.** + - Quantile: 0.999, over nonzero pixels, once per store. + - Model scale: model px = image px × `pixel_size`. `magnification = 10 / pixel_size`, and + `model_magnification = 10`. + - Script constants, in model px: `TILE_MODEL_PX = 2048`, `MIN_WINDOW_MODEL_PX = 1056`, and + `MARGIN_EXTRA_MODEL_PX = 32`. The margin is `ceil((halo + 32) / pixel_size)` image px, where + `halo` is measured from the loaded model. + - Test-time augmentation is always on. + - Score columns are float32. + - The QC positivity threshold is 0.5. + - The tile-invariance tolerance with the real model is max abs 0.01. +- **The Mac.** Real containers run there only on a one-patch crop, under + `-profile docker,emulate_amd64,laptop`. +- **Release.** This is a minor release, 3.2.0, because the rename is a deprecation, not a removal. + +## Review Focus + +1. **Cells at tile and image edges.** Every row of `{method}_table` gets exactly one score row. A + cell is never dropped or scored twice, including in windows clipped and shifted at the image + border. Pinned in Task 5. +2. **Per-tile normalisation sneaking in.** Every window of a channel uses the store's single + factor. A channel without a factor is never handed to Nimbus, which would fall back to that + window's quantile. Pinned in Tasks 5 and 6. +3. **A channel with no nonzero pixel in a store**, such as a blank marker in one TMA core. Its + column is NaN and listed in `uns`. The run does not crash and does not stretch noise. Pinned in + Task 5. +4. **Tables out of step with their shapes**, such as after a `-resume` with changed segmentation. + `WRITE_FEATURES` refuses a row mismatch, and `WRITE_SEGMENTATIONS` removes a stale + `{method}_nimbus`. Pinned in Task 7. +5. **GPU asked for, none usable.** The task fails instead of falling back to CPU. And `V1.pt` + loads on a CPU-only node. Pinned in Tasks 1 and 7. + +--- + +### Task 1: Nimbus image spike, halo and parity fixture + +**Gate.** If the image check fails, or the magnification cannot be pinned, stop and report to the +user before Task 5. The fallback is a sopa-image export step, and choosing it needs their agreement. + +**Files:** + +- Create: `tools/containers/nimbus/Dockerfile` +- Create: `tools/containers/nimbus/README.md`, with the build, save-to-tar and verify commands in + five lines +- Create: `tools/make_nimbus_fixture.py`, which cuts the crop +- Create: `tools/nimbus_reference.py`, which produces the reference with upstream Nimbus +- Modify: `.gitignore`, adding `tests/unit/fixtures/nimbus_crop/`. The fixture is about 6 MB and is + generated, not committed. + +**Interfaces:** + +- Produces: the local image `docker.io/josenimo/nimbus:0.0.5`. +- Produces: the fixture `tests/unit/fixtures/nimbus_crop/`: + - `image.npy`: (2, 1280, 1280) uint16, from exemplar-001. Use one marker with many positive + cells and one sparse marker. + - `labels.npy`: int32. + - `factors.json`: upstream's normalisation dict. + - `reference_scores.csv`: columns `label` plus one per channel, from upstream `predict_fovs` + with `magnification = model_magnification = 10` and `test_time_aug=True`. At 1280 px this + takes upstream's valid tile-and-stitch path, as our windows will. +- Produces: findings, recorded in the SDD ledger and in the README. + - **Magnification.** The µm/px of Nimbus's "10x", from the paper, the README or the issues. + Either confirm "10x = 1 µm/px" with a citation, or record the value found and correct the spec + before Task 6. + - **Halo.** Load the valid model, run `nimbus.model(torch.rand(1, 2, 1024, 1024))`, and record + `(1024 - output_side) // 2`, after upstream's `crop_by`. The architecture predicts about 92. + - **CPU load.** Whether `V1.pt` loads on CPU without `map_location`. + +- [ ] **Step 1: Write the Dockerfile.** + - `FROM docker.io/josenimo/sopa:2.3.0`. + - Install `pip install --no-deps Nimbus-Inference==0.0.5`. + - Install the runtime imports the base lacks, at exact versions: alpineer, kornia, + opencv-python-headless, pyometiff, natsort and lmdb. + - Download `V1.pt` from HF `JLrumberger/Nimbus-Inference` into the package's `assets/` folder. + - `ENV HF_HUB_OFFLINE=1`. +- [ ] **Step 2: Build it.** + Run: `docker buildx build --platform linux/amd64 -t docker.io/josenimo/nimbus:0.0.5 tools/containers/nimbus` + Expected: the build succeeds. +- [ ] **Step 3: Check the import, CPU load and halo, offline.** Run inside the image with + `--network none`: + - Import Nimbus and print numpy's version. + - Construct `Nimbus(dataset=None, output_dir="", save_predictions=False, device="cpu", checkpoint="V1.pt")`. + - Call `load_checkpoint(padding="valid")`. + - Print the halo. + + Expected: numpy 2.x, no exception, and the halo printed. If the load fails on CUDA tensors, + record it. Task 6 then loads the state dict with `map_location`. + +- [ ] **Step 4: Make the fixture and the reference.** + - Cut the crop: `python -I tools/make_nimbus_fixture.py tests/unit/fixtures/nimbus_crop`. + Labels come from a cellpose run's `{method}_cells`. + - Run the reference in a numpy<2 environment: + `uv run --python 3.11 --with Nimbus-Inference==0.0.5 python -I tools/nimbus_reference.py tests/unit/fixtures/nimbus_crop`. + + Expected: `factors.json`, and `reference_scores.csv` with one row per label. + +- [ ] **Step 5: Commit** the Dockerfile, the README, both tools and `.gitignore`: + `Nimbus image spike and parity tools`. + +### Task 2: Correct stale version docs + +**Files:** + +- Modify: `nextflow.config`, setting `manifest.version` to `'3.1.0'`. +- Modify: `CHANGELOG.md`. + +- [ ] **Step 1: Date 3.0.0.** Change `## v3.0.0 - [unreleased]` to `## v3.0.0 - [2026-11-07]`. +- [ ] **Step 2: Add the 3.1.0 entry.** + - Add `## v3.1.0 - [2026-11-07]` above it, with an Added or Changed list. + - Derive the list from `git log --oneline v3.0.0..v3.1.0`: the site navigation and module pages + were restructured, and the metro map was redrawn. + - Move any 3.0.0 bullet that `git log v2.0.0..v3.0.0` shows was not in 3.0.0. + - Above it, add `## v3.2.0 - [unreleased]` with empty Added and Deprecated lists. +- [ ] **Step 3: Check the result.** + Run: `nextflow config . | grep -A3 manifest | grep version` and `prek run --all-files`. + Expected: `3.1.0`, and clean. +- [ ] **Step 4: Commit.** `Correct version and CHANGELOG for 3.0.0 and 3.1.0` + +### Task 3: `pixel_size`, with `instanseg_pixel_size` deprecated + +**Files:** + +- Modify: + - `nextflow_schema.json`. Add `pixel_size` to the generic group: number, `minimum: 0`, with the + description "µm per pixel of the image (OME PhysicalSizeX). Required by InstanSeg and Nimbus." + Keep `instanseg_pixel_size`, but mark it deprecated: description "Deprecated: use pixel_size", + and `hidden: true`. + - `nextflow.config`: `pixel_size = null`. + - `conf/test_exemplar00{1,2}.config`. + - `modules/local/utils.nf`. + - `subworkflows/local/segmentation/main.nf`. + - `subworkflows/local/utils_nfcore_histo_pipeline/main.nf`. + - `docs/usage.md`, and the `site/**` pages listed by + `git grep -l instanseg_pixel_size -- site`. +- Test: + - `tests/validate_params.nf.test`. + - `tests/pixel_size.nf.test` (new, `nextflow_function`). + - Every `tests/*.nf.test` that sets `instanseg_pixel_size` moves to `pixel_size`. + +**Interfaces:** + +- Produces: `pixelSize(Map args) -> Number or null` in `modules/local/utils.nf`. + - It returns `toNumber('pixel_size', args.pixel_size)` when set, else + `toNumber('instanseg_pixel_size', args.instanseg_pixel_size)`. + - When both are set and differ, it calls + `error("pixel_size (${a}) and the deprecated instanseg_pixel_size (${b}) differ; set only pixel_size.")`. + - Every pipeline read of a pixel size goes through it, including `segmentationSpecs`, where + `method_kwargs.pixel_size` keeps its key, and the InstanSeg memory helpers. +- Produces: in `validateParams`, a `log.warn` when `instanseg_pixel_size` is set, reading + "instanseg_pixel_size is deprecated; use pixel_size." The InstanSeg assert reads + `use_instanseg requires pixel_size`. + +- [ ] **Step 1: Write the failing tests.** + - `pixelSize`: + - `[pixel_size: 0.65]` gives 0.65. + - `[instanseg_pixel_size: '0.65']` gives 0.65, a number. + - `[pixel_size: 0.5, instanseg_pixel_size: 0.65]` fails, and stdout contains `differ; set only pixel_size`. + - `[:]` gives null. + - `validateParams` with `[use_instanseg: true, use_preprocessing: true]` fails with + `use_instanseg requires pixel_size`. +- [ ] **Step 2: Run them and confirm they fail.** + Run: `nf-test test tests/pixel_size.nf.test tests/validate_params.nf.test` + Expected: the new tests fail. +- [ ] **Step 3: Implement.** Move the tests and configs to `pixel_size`. +- [ ] **Step 4: Run the suites.** + Run: `nf-test test --tag validation && nf-test test --tag stub` + Expected: all pass. +- [ ] **Step 5: Update the CHANGELOG.** Under 3.2.0 Deprecated, note that `instanseg_pixel_size` + is now `pixel_size`, which is shared by InstanSeg and Nimbus. +- [ ] **Step 6: Commit.** `Add pixel_size; deprecate instanseg_pixel_size` + +### Task 4: Learned-features parameters, validation and `featureSpecs` + +**Files:** + +- Modify: + - `nextflow_schema.json`. Add a new `$defs` group, `learned_features`, titled "Learned + features", with `fa_icon` `fas fa-brain`, referenced in `allOf`. + - `nextflow.config`. + - `modules/local/utils.nf`. + - `subworkflows/local/utils_nfcore_histo_pipeline/main.nf`. +- Test: `tests/feature_specs.nf.test` (new) and `tests/validate_params.nf.test`. + +**Interfaces:** + +- Produces: `use_nimbus`, a boolean, default `false`. Its `help_text` reads: "**Requires:** + `pixel_size`, `segment_cells`, and `nimbus_channels` when `use_preprocessing` is false." +- Produces: `nimbus_channels`, of type `["string", "integer"]`, default `null`. +- Produces: `featureSpecs(Map args) -> List`. With `use_nimbus`, it returns + `[name: 'nimbus', model: 'nimbus', channels: getChannels(args.nimbus_channels, true), pixel_size: pixelSize(args), gpu: args.use_gpu ? true : false]`. + Otherwise it returns `[]`. +- Produces: `defaultNimbusChannels(List rows) -> List`, the `marker_name` of each row whose + `channel_role == 'marker'`. + +- [ ] **Step 1: Write the failing tests.** + - `featureSpecs`: + - `[:]` gives `[]`. + - `[use_nimbus: true, pixel_size: 0.65]` gives one spec: `name == 'nimbus'`, + `channels == null`, `pixel_size == 0.65`. + - `[use_nimbus: true, pixel_size: '0.65', nimbus_channels: 'CD3, CD45']` gives + `channels == ['CD3', 'CD45']`. + - `defaultNimbusChannels` on rows with the roles `dna`, `marker`, `autofluorescence` and + `marker` returns the two markers, in order. + - `validateParams` asserts these messages: + - `use_nimbus requires pixel_size`; + - `use_nimbus requires segment_cells`; + - `use_nimbus without use_preprocessing needs nimbus_channels`. +- [ ] **Step 2: Run them and confirm they fail.** + Run: `nf-test test tests/feature_specs.nf.test tests/validate_params.nf.test` + Expected: the new tests fail. +- [ ] **Step 3: Implement.** Add the schema entries, the defaults, both functions and the three + asserts. Also add a `log.warn` when `use_nimbus` is set without `use_gpu`: "use_nimbus without + use_gpu: same scores, but hours per whole slide on CPU." +- [ ] **Step 4: Run the tests.** + Run: `nf-test test --tag validation && nf-test test tests/feature_specs.nf.test` + Expected: all pass. The schema hook also passes. +- [ ] **Step 5: Commit.** `Add use_nimbus, nimbus_channels and featureSpecs` + +### Task 5: Tiled runner core, with no model + +**Files:** + +- Create: `bin/nimbus_cells.py`, holding the pure functions here and `main` in Task 6. +- Test: `tests/unit/test_nimbus_cells.py` + +**Interfaces:** + +- Consumes: `aggregate_compartments.rasterize(cell, shape, xy_min) -> np.ndarray`, 0/1 with holes + at 0. +- Produces: constants. `QUANTILE = 0.999`, `TILE_MODEL_PX = 2048`, `MIN_WINDOW_MODEL_PX = 1056` and + `MARGIN_EXTRA_MODEL_PX = 32`. +- Produces: `image_px(model_px: int, pixel_size: float) -> int` returns + `ceil(model_px / pixel_size)`. +- Produces: `assign_tiles(centroids: np.ndarray, tile_size: int) -> np.ndarray`, (n, 2) int tile + indices from (n, 2) xy. +- Produces: `tile_windows(bounds, tiles, tile_size, margin, min_window, image_shape) -> dict[tuple[int, int], tuple[int, int, int, int]]`. + It returns `(y0, y1, x0, x1)` per tile, built in four steps: + 1. Grow the tile to cover its owned cells' bounds. + 2. Grow it by `margin`. + 3. Where a side is shorter than `min_window`, extend it, shifting inward at the image border. + 4. Clip to the image. +- Produces: `label_window(geoms, labels, window) -> np.ndarray`, an int32 label image of every + geom intersecting the window. +- Produces: `normalisation_factors(image, channel_names, quantile=QUANTILE, max_pixels=50_000_000) -> dict[str, float | None]`. + - The image is (c, y, x), dask or numpy. + - The quantile is over the nonzero pixels of `image[c, ::s, ::s]`, where + `s = ceil(sqrt(h * w / max_pixels))`. + - A channel with no nonzero pixel gives `None`. +- Produces: `cell_means(labels, prediction, wanted) -> np.ndarray`, the mean over each wanted + label's pixels with `np.bincount`. NaN where a label has no pixel. +- Produces: `score_cells(image, geoms, cell_labels, channel_names, factors, predict, tile_size, margin, min_window) -> np.ndarray`. + - It returns float32, (n_cells, n_channels), in `geoms` order. Sizes are in image px. + - `predict(channel: str, normalised: np.ndarray, labels: np.ndarray) -> np.ndarray` returns a + probability map the shape of `normalised`. + - `normalised = clip(window / factors[channel], 0, 1)`. + - A channel whose factor is `None` is never passed to `predict`, and its column is NaN. + - A channel missing from `factors` raises `KeyError`. It never falls back to a per-window + quantile. + +- [ ] **Step 1: Write the failing tests.** Use shapely boxes on a synthetic image, and the fake + `predict = lambda ch, x, lab: x`, which makes a score the mean normalised intensity. + - `test_every_cell_scored_once_for_any_tile_size`: a 6×6 grid of boxes, many on tile edges, at + `tile_size` 64, 100 and 4096, with `min_window=0`. The results are equal at atol 1e-6, with no + NaN. + - `test_border_window_shifted_inward_to_min_window`: a 1000 px image, `tile_size=300` and + `min_window=600`. Every window side is at least 600 and lies within the image. + - `test_window_smaller_than_min_when_image_is`: a 400 px image gives windows of 400. + - `test_cell_on_image_border_is_whole`: a box touching x = 0 gets the hand-computed mean. + - `test_window_contains_neighbours`: a neighbour owned by the next tile is labelled. + - `test_every_window_gets_the_store_factor`: a recording `predict` sees normalised windows equal + to `clip(raw / factor, 0, 1)`, with the same factor in every window. + - `test_missing_factor_raises`: a channel absent from `factors` raises `KeyError`. + - `test_normalisation_deterministic_and_nonzero_only`: two calls are equal, and zeros do not + lower the quantile, checked against `np.quantile` of the nonzero values. + - `test_empty_channel_is_nan_column`: the factor is `None`, `predict` is never called for it, + its column is all NaN, and the others are finite. + - `test_cell_without_pixel_centre_is_nan`: a 0.2 px sliver gets NaN. +- [ ] **Step 2: Run them and confirm they fail.** + Run: `pytest tests/unit/test_nimbus_cells.py -v` + Expected: an ImportError, or failures. +- [ ] **Step 3: Implement.** `score_cells` reads each window one channel at a time with + `np.asarray(image[c, y0:y1, x0:x1])`, so it never holds a whole channel. +- [ ] **Step 4: Run the tests and the linter.** + Run: `pytest tests/unit/test_nimbus_cells.py -v && ruff check bin/nimbus_cells.py` + Expected: all pass. +- [ ] **Step 5: Commit.** `Nimbus runner: tiles, labels, normalisation` + +### Task 6: Nimbus predictor, CLI, parity and tile invariance + +**Files:** + +- Modify: `bin/nimbus_cells.py` +- Test: + - `tests/unit/test_nimbus_cells.py`, for the CLI table with the fake predictor. + - `tests/unit/test_nimbus_model.py`. It is skipped unless `nimbus_inference` imports and the + fixture exists. + +**Interfaces:** + +- Consumes: Task 5's functions, and Task 1's fixture and findings. +- Produces: `load_nimbus(device: str, batch_size: int = 4)`. It builds + `Nimbus(dataset=None, output_dir="", save_predictions=False, test_time_aug=True, model_magnification=10, device=device, checkpoint="V1.pt")`, + then calls `load_checkpoint(padding="valid")`. Add `map_location` only if Task 1 found it needed. +- Produces: `model_halo(nimbus) -> int`, the halo measured as in Task 1. +- Produces: `nimbus_predictor(nimbus, pixel_size: float, batch_size: int = 4) -> Callable`. Its + `predict` mirrors the per-channel body of upstream `utils.predict_fovs`: + 1. `prepare_binary_mask(labels)`. + 2. A cv2 resize of image and mask to `round(side * pixel_size)`, skipped when `pixel_size == 1`. + 3. `prepare_input_data(img, binary_mask=mask)`. + 4. `test_time_aug(input, channel, nimbus, normalization_dict={channel: 1.0}, batch_size=batch_size)`, + called unchanged as upstream does. + 5. A resize back with `INTER_NEAREST`. +- Produces: the CLI. + + ```text + nimbus_cells.py --sdata S --method M --channels C1,C2 --pixel-size F --device cpu|cuda + --output M_nimbus.h5ad --provenance M_nimbus.json + ``` + + - **Reads:** the image named by the store's `cell_segmentation_image` attribute, `{M}_cells`, + and `{M}_table`'s obs. + - **Normalisation:** factors from `normalisation_factors` on that image, once per store. + - **Sizes:** in image px, `tile = image_px(TILE_MODEL_PX, F)`, + `margin = image_px(model_halo(nimbus) + MARGIN_EXTRA_MODEL_PX, F)` and + `min_window = image_px(MIN_WINDOW_MODEL_PX, F)`. + - **Rows:** `{M}_table.obs_names`. Shapes are reindexed to them. + - **Output:** a `TableModel` with `region` `{M}_cells`, `region_key` `region` and `instance_key` + `cell_id`. + - `obs`: `region`, `slide`, `core_id` and `cell_id`, copied from `{M}_table`. + - `var_names`: the channels, in the order given. + - `X`: float32. + - **Provenance:** `uns['nimbus']` records: + - `nimbus_version`, `weights` (`V1.pt`) and `weights_sha256`; + - `channels`, `factors` and `unscored`; + - `pixel_size` and `magnification`; + - `tile_size`, `margin`, `halo` and `min_window`; + - `test_time_aug` and `device`. + + The provenance JSON is the same dict. + + - **Errors:** an unknown channel exits 1 and names the store's channels. + +- [ ] **Step 1: Write the failing tests.** + - `test_cli_table_layout`: a tiny store, built as in `tests/unit/test_aggregate_compartments.py`, + run through `main` with an injected fake predictor and halo. Asserts that `obs_names` equal + the table's, `var_names` equal the channels, `X.dtype == float32`, and that the `uns['nimbus']` + keys are present. + - `test_unknown_channel_exits_naming_channels`. + - `test_parity_with_upstream`, model test: `score_cells` on the fixture with + `nimbus_predictor(load_nimbus("cpu"), 1.0)`, factors from `factors.json`, a tile of 4096 and + the measured margin. The crop is one window, so it takes the valid path, as the reference did. + Asserts `assert_allclose(ours, reference, atol=1e-4)`. + - `test_tile_invariance_real_model`, model test: the same fixture at `tile_size=256`, so many + windows, each of at least `min_window`, against `tile_size=4096`. Asserts max abs difference + of 0.01 or less. Print the max and the mean, for the ledger. +- [ ] **Step 2: Run them and confirm they fail.** + Run: `pytest tests/unit/test_nimbus_cells.py -v` + Expected: the new tests fail. +- [ ] **Step 3: Implement** `load_nimbus`, `model_halo`, `nimbus_predictor`, `build_table` and `main`. +- [ ] **Step 4: Run the tests on the host, then the model tests in the image.** + Run: `pytest tests/unit/test_nimbus_cells.py -v` + Expected: pass, with the model tests skipped. + Run: `docker run --rm --platform linux/amd64 --network none -v "$PWD":/repo -w /repo docker.io/josenimo/nimbus:0.0.5 python -m pytest tests/unit/test_nimbus_model.py -v -s` + Expected: pass. + **Gate.** If tile invariance fails, stop and report the numbers. Do not raise the tolerance. +- [ ] **Step 5: Commit.** `Nimbus runner: predictor, CLI, parity and tiles` + +### Task 7: `NIMBUS` and `WRITE_FEATURES` modules + +**Files:** + +- Create: + - `modules/local/nimbus/main.nf`, `meta.yml` and `environment.yml`. The environment pins + python 3.12 and pip `Nimbus-Inference==0.0.5`. + - `bin/write_features.py`. + - `modules/local/write_features/main.nf`, `meta.yml` and `environment.yml`, copied from + `write_segmentations`. +- Modify: `bin/write_segmentations.py`. `RESERVED` becomes + `^(cellpose|instanseg)_(cells|nuclei|cytoplasm|table|nimbus)$`. +- Modify: `conf/base.config`, adding `withName: NIMBUS { cpus = 4 }`. +- Modify: `conf/gpu.config`. The selector becomes `'SEGMENT_PATCH_(CELLPOSE|INSTANSEG)|NIMBUS'`. + `NIMBUS` keeps the base memory and does not take Cellpose's GPU sizing block. +- Test: `tests/unit/test_write_features.py` + +**Interfaces:** + +- Produces: `NIMBUS`. + - Input: `tuple val(meta), path(sdata_path), val(method), val(spec)`. + - Output: `tuple val(meta), val(method), val(spec), path("${method}_nimbus.h5ad"), path("${method}_nimbus.json")`, + and `path "versions.yml"`. + - Directives: labels `process_medium` and `process_long`; tag + `"${meta.sample}:${method}:nimbus"`; container `docker.io/josenimo/nimbus:0.0.5`. + - It runs the same `gpu_check` and `device` lines as `SEGMENT_PATCH`. + - `versions.yml` records `nimbus-inference` and `torch`. + - The stub touches both outputs. +- Produces: `write_features(sdata_path: Path, tables: list[Path]) -> None`. For each + `{method}_{model}.h5ad`: + 1. It raises `ValueError`, naming both tables, unless `obs_names` equal those of + `tables/{method}_table` (read with `anndata.read_zarr`). + 2. It removes `tables/{method}_{model}` by path if present, then calls + `write_segmentations.reconsolidate`. + 3. It writes with `write_segmentations.write_element`. +- Produces: `WRITE_FEATURES`. + - Input: `tuple val(meta), path(sdata_path), path(tables)`. + - Output: `tuple val(meta), path(sdata_path)` and `versions.yml`. + - Directives: label `process_low`; container `docker.io/josenimo/sopa:2.3.0`. + - Its stub lists the staged tables, as `WRITE_SEGMENTATIONS`' does. + +- [ ] **Step 1: Write the failing tests.** + - `test_writes_table_and_uns`. + - `test_refuses_row_mismatch`: a reordered or shortened h5ad raises an error, and the store is + unchanged. + - `test_rerun_is_idempotent`. + - `test_write_segmentations_removes_stale_nimbus`. +- [ ] **Step 2: Run them and confirm they fail.** + Run: `pytest tests/unit/test_write_features.py -v` + Expected: the new tests fail. +- [ ] **Step 3: Implement the scripts, both modules and the config.** +- [ ] **Step 4: Run the tests and regenerate the manifest.** + Run: `pytest tests/unit -q && tools/container_manifest.py && tools/container_manifest.py --check` + Expected: all pass, and `containers.tsv` has a `josenimo/nimbus:0.0.5` row. +- [ ] **Step 5: Commit.** `Add NIMBUS and WRITE_FEATURES modules` + +### Task 8: `LEARNED_FEATURES` subworkflow and wiring + +**Files:** + +- Create: `subworkflows/local/learned_features/main.nf` and `meta.yml` +- Modify: + - `workflows/histo.nf`. + - `conf/modules.config`, publishing `NIMBUS` `*.json` to `${params.outdir}/learned_features/`. + - `docs/pipeline_paths.mmd`. +- Test: `tests/nimbus.nf.test` (new) + +**Interfaces:** + +- Consumes: `featureSpecs`, `defaultNimbusChannels`, `NIMBUS` and `WRITE_FEATURES`. +- Produces: `LEARNED_FEATURES(ch_sdata, ch_markers, specs, methods)`. + - It takes `[meta, sdata]` per store, the marker sheets, the `featureSpecs` list and the + segmentation methods. + - It emits `sdata` as `[meta, sdata]`, and `versions`. + - Keys are `meta.sdata_dir.toString()`, as in `SEGMENTATION`. + - The marker sheet joins only when some spec has `channels == null`. + - An empty default channel list fails with + `error("Sample '${meta.sample}': no marker channels for nimbus. Set nimbus_channels, or mark channels 'marker' in the marker sheet.")`. + - When there is a sheet, `nimbus_channels` names that are not in it fail with an `error()` that + names the sample and the names. + - Rows branch on `spec.model`, with `nimbus:` only for now. + - Outputs group per store with `groupKey(sdata_dir, methods.size() * specs.size())`, sorted by + file name, then join back to the store for `WRITE_FEATURES`. +- Changes `histo.nf`: + - `def feature_specs = featureSpecs(params)`. + - `ch_featured` is `LEARNED_FEATURES.out.sdata` when `feature_specs` is non-empty, else + `ch_segmented`. + - `QC`, `COMPARE_SEGMENTATIONS`, the TMA `groupTuple` and `PUBLISH_SPATIALDATA` read + `ch_featured`. + +- [ ] **Step 1: Write the failing tests** in `tests/nimbus.nf.test`, with profile `test,laptop`, + `-stub`, and tags `stub` and `pipeline`. + - `test("one method: one NIMBUS, one WRITE_FEATURES, QC after it")`, with `use_nimbus = true` + and `pixel_size = 0.65`. QC's trace `start` comes after `WRITE_FEATURES`' `complete`. + - `test("two methods: a NIMBUS per method, one write")`, adding `use_instanseg` with + `instanseg_channels = "DAPI"`. + - `test("TMA: one NIMBUS per core")`, with `tests/tma.nf.test`'s params. + - `test("use_nimbus off runs neither process")`. + - `test("nimbus_channels naming a missing channel stops the run")`. +- [ ] **Step 2: Run them and confirm they fail.** + Run: `nf-test test tests/nimbus.nf.test` + Expected: failures. +- [ ] **Step 3: Implement.** +- [ ] **Step 4: Run the stub suite and lint.** + Run: `nf-test test --tag stub && nf-core pipelines lint` + Expected: all pass, with no new lint failures. +- [ ] **Step 5: Re-render the metro map** with the command in `docs/CONTRIBUTING.md#metro-map`. + Ask the user to look at the svg in the final report. +- [ ] **Step 6: Commit.** `Wire LEARNED_FEATURES after segmentation` + +### Task 9: Documentation and release notes + +**Files:** + +- Modify: `docs/output.md`, `docs/usage.md`, `docs/decisions.md`, `CITATIONS.md`, `CHANGELOG.md` + and `ROADMAP.md`. +- Create: `site/modules/nimbus.md`, and add it to the module list in `site/myst.yml`. Write for + bench scientists: plain language, with a table of what goes in and what comes out. +- Run: the site's parameter-reference generator (see `site/build.sh`). + +- [ ] **Step 1: Write `docs/output.md`.** Cover the `{method}_nimbus` table: `X`, `var`, `obs` and + the `uns['nimbus']` keys. Add a snippet: + + ```python + sdata["cellpose_nimbus"][:, "CD3"].X + ``` + + Also cover `learned_features/*.json`. + +- [ ] **Step 2: Write `docs/usage.md`.** Cover `pixel_size`, a GPU recommendation, test-time + augmentation fixed on, and per-core normalisation on TMAs, with its trade-off. +- [ ] **Step 3: Add a "Learned features" section to `docs/decisions.md`.** Cover these points: + - a stage after segmentation, with one table per model; + - tile windows at model scale, with the margin from the measured halo and the minimum window, + and why tiling changes nothing Nimbus computes (the spec's list, the measured invariance); + - per-store normalisation and why; + - test-time augmentation fixed on, upstream code unchanged; + - cells only; + - one pixel size; + - weights baked in. +- [ ] **Step 4: Update the release notes.** + - `CITATIONS.md`: the Nimbus paper, with authors, title, venue and DOI, as found in Task 1. + - `CHANGELOG.md`, 3.2.0 Added: Nimbus. + - `ROADMAP.md`: Nimbus out of 3.4. Under Longer term, add a slide-wide Nimbus normalisation + option and the removal of `instanseg_pixel_size` at the next major release. +- [ ] **Step 5: Build the site.** + Run: `site/build.sh` and `prek run --all-files` + Expected: it builds with no broken links, and the checks are clean. +- [ ] **Step 6: Commit.** `Document Nimbus scores and pixel_size` + +### Task 10: QC chapter (cuttable) + +**Files:** + +- Modify: `bin/qc_metrics.py`, `bin/qc_report.py` and `conf/modules.config`. `QC_METRICS` ext.args + adds `--nimbus-table ${meta.method}_nimbus` when `params.use_nimbus`. +- Test: `tests/unit/qc/test_qc_metrics.py` and `tests/unit/qc/test_qc_report.py` + +**Interfaces:** + +- Produces: `nimbus_metrics(X, markers, threshold=0.5) -> dict`, giving + `{marker: {"fraction_positive": float, "median": float}}`. It is NaN-aware, and an all-NaN + marker gives `None` values. +- Produces: `collect(..., nimbus_table: str | None = None)` adds `metrics["nimbus"]`. +- Produces: `nimbus_section(nimbus: dict) -> str`, a `table()` with each marker's percentage + positive and median. `build` appends it when `"nimbus" in metrics`. + +- [ ] **Step 1: Write the failing tests.** + - [0.1, 0.6, 0.9] gives a fraction of 2/3 and a median of 0.6. + - An all-NaN column gives `None`. + - The report contains "Nimbus" and each marker when the key is present, and neither when it is + absent. +- [ ] **Step 2: Run them and confirm they fail.** + Run: `pytest tests/unit/qc -q` +- [ ] **Step 3: Implement.** +- [ ] **Step 4: Run the tests.** + Run: `pytest tests/unit -q && nf-test test --tag stub` + Expected: all pass. +- [ ] **Step 5: Commit.** `QC: Nimbus positivity per marker` + +### Task 11: Real-data checks + +No code. Record the results in the SDD ledger and the final report. + +- [ ] **Step 1: Mac CPU run.** A one-patch exemplar-001 crop, following CONTRIBUTING's "On the + Mac". Expected: success, and `cellpose_nimbus` in the store. CD45 scores are higher in the top + decile of `CD45_mean` than in the bottom decile. +- [ ] **Step 2: Propose the cluster runs, without submitting them.** + - Exemplar-001 with `use_nimbus` and `use_gpu`. + - The Mac crop on GPU, for a CPU vs GPU comparison at atol 1e-3. + + Include the image pre-staging commands for `josenimo/nimbus:0.0.5`. The user pushes and submits. diff --git a/docs/superpowers/plans/2026-11-24-learned-features-virtues.md b/docs/superpowers/plans/2026-11-24-learned-features-virtues.md new file mode 100644 index 0000000..95aac55 --- /dev/null +++ b/docs/superpowers/plans/2026-11-24-learned-features-virtues.md @@ -0,0 +1,606 @@ +# Learned features (VirTues) Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** With `use_virtues`, every store gains `{method}_virtues` (per cell), `virtues_niches` +with `virtues_niches_table` (per 128 µm tissue square) and `virtues_tissue` (per store): 512-number +VirTues embeddings. + +**Architecture:** + +- After segmentation, a CPU `VIRTUES_HISTOGRAM` per store feeds a `VIRTUES_STATS` per slide, which + writes the slide's clip, mean and SD per marker (`virtues_stats.json`). +- One GPU `VIRTUES` task per store runs our tiled runner (`bin/virtues_cells.py`). It calls + upstream's encoder unchanged; the averaging into cells, squares and tissue is ours. +- `WRITE_FEATURES` stays the only writer, now also for shapes and for tables that are not per + method. + +**Tech Stack:** Nextflow DSL2, nf-test, Python 3.11 or 3.12, numpy, shapely, spatialdata, anndata, +PyTorch with FlashAttention 2, `virtues` at `d2c25e1`, ESM-2 (`fair-esm`), pytest. + +**Spec:** `docs/superpowers/specs/2026-11-24-learned-features-virtues-design.md`. Its "Settled with +you" list is the user's decisions; do not reopen them. + +## Global Constraints + +- **No network at run time.** Weights, ESM-2 and UniProt sequences are baked into the image, which + sets `HF_HUB_OFFLINE=1`. +- **Images.** `docker.io/josenimo/virtues:d2c25e1-2` for `VIRTUES`; `docker.io/josenimo/sopa:2.3.0` + for `VIRTUES_HISTOGRAM`, `VIRTUES_STATS` and `WRITE_FEATURES`. The user pushes images. Agents + never `docker push`, `git push`, `sbatch` or `srun`; they write the command for the user. +- **`bin/virtues_stats.py` imports no torch**, so it runs in the sopa image. +- **Schema.** Optional steps are booleans with `default: false`. Edit `nextflow_schema.json` by + hand. Never edit `assets/params_template*.yml`. +- **Stubs.** Every module that creates a file has a `stub:` block, updated in the same commit as + its outputs. +- **Manifest.** Regenerate `containers.tsv` with `tools/container_manifest.py` after adding a + module. +- **Errors in operators.** `error()`, never `assert`. +- **Commits.** `git add` with explicit paths. Titles under ~60 characters, a body of a few lines or + none, ending `Co-Authored-By: Claude Opus 5.5 `. If prek reformats, re-add + and commit again. +- **Comments.** One line of "why". +- **Pinned values.** + - Model scale: 1.0 µm/px. Model grid `floor(n_image × pixel_size)` per axis; model pixel `k` + covers image interval `[k / pixel_size, (k + 1) / pixel_size)`. + - Crops 128 px, patches 8 px (16 × 16 per crop), crop step 42, padding 120 px, tile 2048 model + px, embedding size 512, GPU batch 32 crops (upstream's `chunk_size`). + - Statistics: quantile 0.99 (numpy default `linear` method), 65 536 histogram bins (uint16), + population SD, statistics file `format: 1`. + - Blur: 3 × 3 Gaussian, sigma 1.0, applied after standardisation. + - Niches: kept when tissue fraction ≥ 0.30. + - Output `X`: float16. Accumulation: float32 sums, float64 weights. +- **Licence.** Only the `sp32` weights. Never copy spora-bench code (CC BY-NC-ND). Upstream + `virtues` and spora-io are MIT; their functions are called, not copied, except the one test + reference in Task 4, which cites the commit. +- **Order.** Building the image is quick; converting it to a `.sif` for the cluster takes the user + about 2 hours. Never wait for it: after Task 1's local build, Tasks 2 to 10 proceed. Only Task 11 + needs the cluster check to have passed. + +## Review Focus + +1. **A cell or square near a tile edge or the image edge.** It gets exactly the crops upstream + would give it, so its row is identical for any tile size. Pinned in Task 4. +2. **A store with no tissue square kept** (a tiny or nearly empty TMA core). No niche files are + written, the tissue row is NaN with `n_niches = 0`, and the run goes on. Pinned in Tasks 4 and 6. +3. **A marker that is constant or absent over a slide's tissue** (SD 0, or no tissue pixels). The + statistics task fails naming the slide and marker, instead of writing NaN or infinity that the + GPU task would turn into garbage. Pinned in Task 3. +4. **Backsub in front of VirTues.** If backsub drops the `uniprot_id` column or writes a float + image, the run stops with a message saying so, instead of embedding nothing or histogramming + floats. Facts from Task 1; pinned in Tasks 3 and 8. +5. **GPU only where needed.** `VIRTUES` gets a GPU; `VIRTUES_HISTOGRAM` and `VIRTUES_STATS` do + not, so the statistics never queue for GPUs. Pinned in Task 7. + +--- + +### Task 1: VirTues image spike and upstream facts + +**Gate.** If the image cannot import `flash_attn` and run the forward pass on a cluster GPU, stop +and report before Task 11; work on Tasks 2 to 10 continues meanwhile. If backsub writes a float image or drops extra marker-sheet columns, +record it and report before Task 8; the user decides. + +**Files:** + +- Create: `tools/containers/virtues/Dockerfile`. +- Create: `tools/containers/virtues/README.md`: build, save-to-tar, cluster check, in a few lines. +- Create: `tools/containers/virtues/check_image.py`, run inside the image. + +**Interfaces:** + +- Produces: the local image `docker.io/josenimo/virtues:d2c25e1-2`, with these environment + variables, read by Task 5: + - `VIRTUES_WEIGHTS=/opt/virtues/sp32/model.safetensors` + - `VIRTUES_UNIPROT=/opt/uniprot/human_sprot_isoforms.fasta` + - `VIRTUES_UNIPROT_RELEASE`: the `X-UniProt-Release` header of the download + - `VIRTUES_COMMIT=d2c25e1` + - `VIRTUES_SRC=/opt/virtues-src`, the repository checkout, including `assets/example_dataset` + (40 MB), for parity + - `TORCH_HOME=/opt/torch`, holding the ESM-2 `esm2_t30_150M_UR50D` weights + - `HF_HUB_OFFLINE=1` +- Produces: findings in the SDD ledger and the README: + - torch, CUDA, FlashAttention, spatialdata versions in the image; + - the shape and dtype of `encoder_output.patch_summary_tokens` per crop; + - our ESM-2 embedding of each ID in `assets/example_dataset/marker_embeddings/` against the + bundled `.pt`: max abs difference; + - backsub: its output image dtype, and whether its `--marker-output` CSV keeps a column it does + not know (read its source in its container, `modules/nf-core/backsub`). + +- [ ] **Step 1: Write the Dockerfile.** + - Base: `pytorch/pytorch:2.5.1-cuda12.4-cudnn9-runtime`. Add the FlashAttention 2 wheel matching + its torch, CUDA, Python and C++ ABI from the Dao-AILab GitHub releases (start from + `flash_attn-2.7.4.post1+cu12torch2.5cxx11abiFALSE`). If no wheel matches, pick another base and + wheel pair; never compile FlashAttention. + - `pip install --no-deps` `virtues` from `git+https://github.com/bunnelab/virtues@d2c25e1` and + spora-io at `ef15868`, then their runtime imports at exact versions (`fair-esm`, `omegaconf`, + `safetensors`, `einops` and whatever the import check shows missing). + - spatialdata, anndata and geopandas at the versions in `docker.io/josenimo/sopa:2.3.0` + (`docker run --rm docker.io/josenimo/sopa:2.3.0 pip list`), so both images read the same store. + - Bake `virtues-sp32/model.safetensors` from HF `bunnelab/virtues`, ESM-2 150M via + `esm.pretrained.esm2_t30_150M_UR50D()`, and + `https://rest.uniprot.org/uniprotkb/stream?format=fasta&includeIsoform=true&query=(organism_id:9606)+AND+(reviewed:true)`. +- [ ] **Step 2: Build it.** + Run: `docker buildx build --platform linux/amd64 -t docker.io/josenimo/virtues:d2c25e1-2 tools/containers/virtues` + Expected: success. +- [ ] **Step 3: Check offline on the Mac.** `check_image.py --cpu-only` with `--network none`: + imports `virtues`, spatialdata and `esm`; loads the safetensors into + `MultiplexVirtues(prior_bias_embeddings=...)` with `strict=True`; compares ESM-2 embeddings + with the bundled `.pt`. `flash_attn` is not imported on the Mac. + Expected: no exception; ESM difference printed. +- [ ] **Step 4: Write the cluster check for the user.** `check_image.py` without `--cpu-only` also + imports `flash_attn`, runs `compute_cell_tokens` on the bundled example core as notebook 2 + does, and prints the token shape. Write the `apptainer exec --nv` command and the image + staging commands in the README. The user pushes, stages and submits. + Expected (from the user): it runs and prints the shapes. +- [ ] **Step 5: Record the backsub facts** from its source. +- [ ] **Step 6: Commit** the three files: `VirTues image spike`. + +### Task 2: Parameters, `uniprot_id`, validation and `featureSpecs` + +**Files:** + +- Modify: `nextflow_schema.json` (learned features group), `nextflow.config`, + `assets/schema_marker.json`, `modules/local/utils.nf`, + `subworkflows/local/utils_nfcore_histo_pipeline/main.nf`. +- Create: `tests/stub_data/markers_virtues.csv`: `tests/stub_data/markers.csv` plus a + `uniprot_id` column, `P08246` for ELANE and `P11215` for CD11B, empty for the DNA rows. +- Test: `tests/feature_specs.nf.test`, `tests/validate_params.nf.test`, + `tests/validate_virtues_markers.nf.test` (new). + +**Interfaces:** + +- Produces: `use_virtues` (boolean, `false`; help text lists the requirements) and + `virtues_stats` (string, `format: file-path`, `exists: true`, `pattern: "^\\S+\\.json$"`, + `hidden: true`, default `null`). +- Produces: marker sheet column `uniprot_id`: string, default `null`, `meta: uniprot_id`, pattern + `^([OPQ][0-9][A-Z0-9]{3}[0-9]|[A-NR-Z][0-9]([A-Z][A-Z0-9]{2}[0-9]){1,2})(-[0-9]+)?$`, error + message "uniprot_id must be a UniProt accession, optionally with an isoform suffix (e.g. P08575 or + P08575-8)". +- Produces: `featureSpecs` appends, with `use_virtues`, + `[name: 'virtues', model: 'virtues', channels: null, pixel_size: pixelSize(args), stats: args.virtues_stats ?: null, gpu: args.use_gpu ? true : false]`. +- Produces in `utils.nf`: `virtuesChannels(List rows) -> List>`, `[marker_name, +uniprot_id]` of each row with a non-empty `uniprot_id`, in sheet order; and + `virtuesUnembedded(List rows) -> List`, the other rows' `marker_name`. +- Produces: `validateVirtuesMarkers(rows, where, stats = null)` in the utils subworkflow, called + from the marker-sheet loop when `params.use_virtues`, with `stats` parsed by `JsonSlurper` from + `params.virtues_stats` when set. It checks the rows backsub keeps + (`params.use_backsub ? rows.findAll { !it.remove } : rows`). +- Messages (asserted verbatim in tests): + - `use_virtues requires use_gpu: VirTues runs on FlashAttention, which has no CPU path.` + - `use_virtues requires use_preprocessing: UniProt IDs come from the marker sheet, which pre-stitched input does not have.` + - `use_virtues requires use_tissue_segmentation: intensity statistics are computed over tissue pixels.` + - `use_virtues requires segment_cells: VirTues embeds cells, so there must be a cell segmentation.` + - `use_virtues requires pixel_size (microns per pixel of the image): VirTues runs at 1 µm per pixel.` + - `virtues_stats is set but use_virtues is not.` + - `${where}: use_virtues needs a uniprot_id on at least one marker row; a channel is embedded only when it has one.` + - `${where}: DNA stains are not embedded; remove the uniprot_id from: ${names}.` + - `${where}: uniprot_id must be unique. Repeated: ${ids}.` + - `${where}: virtues_stats has no statistics for: ${names}.` + - `${where}: virtues_stats records a different uniprot_id for: ${name} (sheet ${a}, stats ${b}).` + +- [ ] **Step 1: Write the failing tests.** + - `featureSpecs`: `[use_virtues: true, pixel_size: 0.65]` gives one spec with `model == +'virtues'`, `channels == null`, `stats == null`; with `virtues_stats: '/x/s.json'`, `stats == +'/x/s.json'`; with both `use_nimbus` and `use_virtues`, two specs, Nimbus first. + - `virtuesChannels` and `virtuesUnembedded` on four rows (dna without ID, two markers with IDs, + one marker without) give the two pairs in order and the other two names. + - `validateParams`: each of the six parameter messages, each from a params map that is valid + except for that one rule. + - `validateVirtuesMarkers`: each of the five sheet messages; a valid sheet passes; with + `use_backsub` a `remove: true` row's ID is ignored by every rule. + - The schema rejects `uniprot_id = CD3` and accepts `P08575-8` (follow + `tests/validate_marker_sheet_column.nf.test`'s way of running the schema). +- [ ] **Step 2: Run them and confirm they fail.** + Run: `nf-test test tests/feature_specs.nf.test tests/validate_params.nf.test tests/validate_virtues_markers.nf.test` +- [ ] **Step 3: Implement.** +- [ ] **Step 4: Run.** + Run: `nf-test test --tag validation && nf-test test tests/feature_specs.nf.test` + Expected: all pass; the schema hook passes. +- [ ] **Step 5: Commit.** `Add use_virtues, virtues_stats and uniprot_id` + +### Task 3: Model scale and slide statistics + +**Files:** + +- Create: `bin/virtues_stats.py`. +- Test: `tests/unit/test_virtues_stats.py`. + +**Interfaces:** + +- Produces constants: `MODEL_UM_PER_PX = 1.0`, `QUANTILE = 0.99`, `N_BINS = 65536`, + `STATS_FORMAT = 1`. +- Produces: `model_shape(image_yx: tuple[int, int], pixel_size: float) -> tuple[int, int]`. +- Produces: `resample_window(image, channel: int, y0: int, y1: int, x0: int, x1: int, pixel_size: float) -> np.ndarray`, + float32 `(y1 - y0, x1 - x0)` in model coordinates. `image` is `(c, y, x)` dask or numpy; it reads + only the image rows and columns it needs. Area-weighted and separable. Each output is a fixed-order + sum over its at most `ceil(1 / pixel_size) + 1` contributing input pixels per axis (rows, then + columns), in float64, vectorised over outputs. No matrix product: its summation order depends on + the window's shape, which would break bit-for-bit window independence. `pixel_size == 1.0` + returns the image values as float32. +- Produces: `tissue_mask(polygons, y0, y1, x0, x1, pixel_size) -> np.ndarray[bool]`, model pixel + `(r, c)` is tissue when its centre `((c + 0.5) / pixel_size, (r + 0.5) / pixel_size)` in image + coordinates is inside a polygon (`shapely.contains_xy`). +- Produces: `histogram(image, polygons, channels: list[int], pixel_size, rows: int = 2048) -> np.ndarray`, + int64 `(len(channels), N_BINS)`, over tissue pixels, values `np.rint` and clipped to + `[0, N_BINS - 1]`, in blocks of `rows` model rows. Raises `TypeError` naming the dtype unless + `image.dtype` is an unsigned integer. +- Produces: `stats_from_histogram(counts: np.ndarray) -> dict`, keys `cap`, `mean`, `sd`, + `tissue_pixels`. `cap` equals `np.quantile(pixels, 0.99)`; `mean` and `sd` are of + `log1p(min(v, cap))`, population SD, two-pass. Raises `ValueError` when there are no pixels or + `sd == 0`; the CLI turns it into a message naming slide and marker. +- Produces: `load_stats(path, channels: list[tuple[str, str]]) -> dict[str, dict]`, which checks + `format == STATS_FORMAT` and that each `(name, id)` is present with that ID, raising `ValueError` + naming what differs. +- Produces the CLI: + + ```text + virtues_stats.py histogram --sdata S --channels NAME:ID,... --pixel-size F --output SAMPLE_virtues_hist.npz + virtues_stats.py combine --slide SL --pixel-size F --output SL_virtues_stats.json H1.npz [H2.npz ...] + ``` + + - `histogram` reads the store's segmentation image (`resolve_segmentation.store_image_key`, + scale0 as `nimbus_cells.py` does) and `region_of_interest`. The npz holds `counts`, `markers`, + `uniprot_ids`, `sample`. Exits 1 naming the dtype for a non-integer image, and naming the + missing element when there is no `region_of_interest`. + - `combine` refuses inputs whose markers or IDs differ, sums counts, and writes + `{"format": 1, "slide": SL, "cores": [...], "model_um_per_px": 1.0, "pixel_size": F, +"markers": {name: {"uniprot_id", "cap", "mean", "sd", "tissue_pixels"}}}`. + +- [ ] **Step 1: Write the failing tests.** + - `test_resample_identity_at_one_um`. + - `test_resample_area_average`: pixel size 0.5, a 4 × 4 ramp gives the hand-computed 2 × 2 means. + - `test_resample_window_independent_bit_for_bit`: pixel size 0.65, random uint16 300 × 300; 20 + random windows equal (`np.array_equal`) the same region of the whole-image result. + - `test_resample_upsampling`: pixel size 2.0 gives a grid twice the size, each value its source + pixel. + - `test_tissue_mask_pixel_centres`: a square polygon covering image `[0, 10)` at pixel size 0.5 + marks model pixels 0 to 4. + - `test_stats_equal_numpy`: random tissue pixels from two "cores"; summed histograms give `cap` + equal to `np.quantile(pooled, 0.99)`, and `mean`, `sd` equal to `np.mean`, `np.std` of + `np.log1p(np.minimum(pooled, cap))`, rtol 1e-12. + - `test_histogram_only_tissue`: pixels outside the polygon change nothing. + - `test_float_image_refused`, `test_constant_marker_refused`, `test_no_tissue_refused`. + - `test_combine_refuses_mismatched_markers`, `test_load_stats_id_mismatch`. +- [ ] **Step 2: Run and confirm failure.** `pytest tests/unit/test_virtues_stats.py -v` +- [ ] **Step 3: Implement.** +- [ ] **Step 4: Run.** `pytest tests/unit/test_virtues_stats.py -v && ruff check bin/virtues_stats.py` + Expected: pass. +- [ ] **Step 5: Commit.** `VirTues: model scale and slide statistics` + +### Task 4: Tiled runner core, with a fake encoder + +**Files:** + +- Create: `bin/virtues_cells.py` (pure functions here; model and CLI in Task 5). +- Test: `tests/unit/test_virtues_cells.py`. + +**Interfaces:** + +- Consumes: `resample_window`, `tissue_mask`, `model_shape` from Task 3. +- Produces constants: `CROP = 128`, `PATCH = 8`, `STEP = 42`, `PAD = 120`, `TILE = 2048`, + `BATCH = 32`, `NICHE_MIN_TISSUE = 0.30`, `BLUR_SIGMA = 1.0`. +- Coordinates: "padded" model coordinates, the model grid shifted by `PAD` on each side, as upstream + pads before cutting crops. +- Produces: `uniform_crops(h: int, w: int) -> list[tuple[int, int]]`, the sorted crop origins of + upstream `_get_uniform_crops(img, STEP, CROP)` for a padded image of `h × w`, without the image. +- Produces: `model_input(read_raw, stats, y0, y1, x0, x1, padded_shape) -> np.ndarray`, float32 + `(c, y1 - y0, x1 - x0)` in padded coordinates: + 1. raw values for one pixel more on each side, from `read_raw(c, y0, y1, x0, x1)` in model + coordinates; 0 outside the image (upstream's zero pad; beyond the pad too, which equals + torchvision's reflect border because the pad is wider than the blur radius); + 2. `(log1p(min(x, cap)) - mean) / sd` per channel; + 3. the 3 × 3 Gaussian (torchvision's kernel: `exp(-0.5 * (k / 1.0)**2)` for `k` in -1, 0, 1, + normalised), separable, keeping the interior. +- `read_input(y0, y1, x0, x1)` below is `model_input` bound to a store's `read_raw`, statistics + (arrays `cap`, `mean`, `sd` in channel order) and `padded_shape`; `read_tissue(y0, y1, x0, x1)` + is `tissue_mask` bound to `region_of_interest`, in model coordinates. +- Produces: `encode` protocol: `encode(crops: np.ndarray) -> np.ndarray`, `(n, c, 128, 128)` + float32 in, `(n, 16, 16, D)` float32 out. The test encoder returns each patch's mean per channel + (`D = c`). +- Produces: `CellSource(read_labels, centroids, bboxes)`, a dataclass. `read_labels(y0, y1, x0, +x1)` returns int32 labels `1..n` in padded coordinates, 0 for background; `centroids` and + `bboxes` are `(n, 2)` and `(n, 4)` (`y0, y1, x0, x1`) in padded coordinates. +- Produces: `label_reader(geoms, pixel_size) -> Callable`, for the CLI: pixel-centre rule as + `tissue_mask`, geoms in image coordinates; where cells overlap, the earlier geom wins, so a + pixel's label does not depend on the window. +- Produces: `cell_embeddings(read_input, sources: dict[str, CellSource], padded_shape, encode, tile=TILE, batch=BATCH) -> dict[str, tuple[np.ndarray, np.ndarray]]`, + per method `(emb float32 (n, D), weight float64 (n,))`, NaN rows where the weight is 0. + - A cell belongs to the tile (`tile × tile`, padded coordinates) holding its centroid, for each + method separately. + - Per tile, the crops are those of `uniform_crops` whose box meets an owned cell's bbox, for any + method; they are encoded once, in batches of `batch`, in upstream's sorted order. + - Per crop and method, the cell × patch pixel counts (`np.bincount` on `patch * (n + 1) + +label`) weight the patch tokens into float32 sums for that tile's owned cells only. Iterating + crops in global sorted order makes each cell's sums add in the same order for any tile size. +- Produces: `niche_embeddings(read_input, read_tissue, image_shape_model, encode, batch=BATCH) -> tuple[list[tuple[int, int]], np.ndarray, np.ndarray]`, + the kept squares' origins in model coordinates, their tissue fractions, and float32 + `(k, D)` embeddings, the mean of each square's 256 patch tokens. Squares are on a 128 px grid + from the model origin, only those fully inside the image, read through `model_input` at + `origin + PAD`. Kept when tissue fraction ≥ `NICHE_MIN_TISSUE`. Read one tile row at a time. +- Produces: `tissue_embedding(niches: np.ndarray) -> np.ndarray`, the mean of the rows; NaN `(D,)` + when there are none. + +- [ ] **Step 1: Write the failing tests.** Synthetic images and shapely boxes; the patch-mean + encoder; statistics with `cap` large, `mean = 0`, `sd = 1`. + - `test_crop_grid_equals_upstream`: a copy of upstream `_get_uniform_crops` from `d2c25e1` in + the test file (MIT, with a comment citing the commit), for shapes 128 × 128, 300 × 517 and + 1000 × 1000. + - `test_tiled_equals_whole_image_exactly`: 40 cells, many on tile edges, `tile` 64, 200 and + 4096; `np.array_equal`. + - `test_cell_matches_upstream_averaging`: a direct port of upstream's per-crop loop on the whole + padded image (in the test) gives the same rows, rtol 1e-6. + - `test_two_methods_equal_one_at_a_time`. + - `test_cell_without_pixel_is_nan`: a sliver between pixel centres. + - `test_overlap_earlier_cell_wins`. + - `test_model_input_window_independent`: windows at the image edge and inside equal the + whole-image result, including the zero pad and the blur. + - `test_niche_grid_and_threshold`: a 300 × 300 image gives 4 squares; a polygon covering 29% of + one square drops it, 31% keeps it. + - `test_niche_is_patch_mean`, `test_tissue_is_mean_of_kept_niches`, + `test_no_niche_gives_nan_tissue`. +- [ ] **Step 2: Run and confirm failure.** `pytest tests/unit/test_virtues_cells.py -v` +- [ ] **Step 3: Implement.** Never hold more than one window's input and labels at once. +- [ ] **Step 4: Run.** `pytest tests/unit/test_virtues_cells.py -v && ruff check bin/virtues_cells.py` +- [ ] **Step 5: Commit.** `VirTues runner: crops, tiles, cells, niches` + +### Task 5: Model, CLI, outputs and the parity tool + +**Files:** + +- Modify: `bin/virtues_cells.py`. +- Create: `tools/virtues_parity.py`, run in the image on a cluster GPU. +- Test: `tests/unit/test_virtues_cells.py` (CLI with the fake encoder); `tests/unit/test_virtues_model.py`, + skipped unless `virtues` and `flash_attn` import and CUDA is available. + +**Interfaces:** + +- Consumes: Tasks 1, 3, 4. +- Produces: `uniprot_sequences(fasta: Path, ids: list[str]) -> dict[str, str]`, from headers + `>sp|ACC|...`; raises `KeyError` naming the absent IDs. +- Produces: `load_virtues(weights: Path, sequences: list[str], device: str)`: ESM-2 embeddings + with upstream `ESMWrapper("esm2_t30_150M_UR50D", device).embed_sequence`, stacked in channel + order as `prior_bias_embeddings`; `MultiplexVirtues(prior_bias_embeddings=...)`; + `load_state_dict(safetensors.torch.load_file(weights))`; `.to(device).eval()`. +- Produces: `virtues_encoder(model, n_channels: int, device: str) -> encode`: calls + `model.encoder.forward_list(crops, [arange(n_channels)] * n, multiplex_mask=None)` under + `torch.no_grad()` and `torch.amp.autocast('cuda')`, returning `patch_summary_tokens` as float32 + numpy `(n, 16, 16, 512)`. +- Produces: `main(argv=None, encode=None) -> int`; tests inject `encode`, otherwise the model is + loaded. +- Produces the CLI: + + ```text + virtues_cells.py --sdata S --methods M1,M2 --channels NAME:ID,... --unembedded N1,N2 + --stats SL_virtues_stats.json --pixel-size F --device cuda + [--batch-size 32] [--outdir .] + ``` + + - Reads the segmentation image, `region_of_interest`, and per method `{M}_cells` and + `{M}_table`'s obs, as `nimbus_cells.py` does. Rows follow `{M}_table.obs_names`. + - Exits 1 naming them: an unknown channel, an ID not in the UniProt file, statistics that do not + match the channels (`load_stats`), a non-CUDA device. + - Writes `{M}_virtues.h5ad` per method; `virtues_niches.parquet` and `virtues_niches_table.h5ad` + only when a square is kept; `virtues_tissue.h5ad`; `virtues.json`. + - `{M}_virtues`: `TableModel.parse(..., region="{M}_cells", region_key="region", +instance_key="cell_id")`, `X` float16, `var_names` `virtues_0` … `virtues_511`, `obs` copied + (`region`, `slide`, `core_id`, `cell_id` where present). + - `virtues_niches`: square polygons in image coordinates (model origin ÷ `pixel_size`), index + `niche_0` … in grid order. `virtues_niches_table`: region `virtues_niches`, instance key + `niche_id`, `obs` `niche_id`, `tissue_fraction`, and `slide`, `core_id` from `{M}_table` where + present. + - `virtues_tissue`: 1 row, `obs` `slide`, `core_id`, `n_niches`; parsed without a region. + - `uns['virtues']` on every table and in `virtues.json`: `virtues_commit`, `weights`, + `weights_sha256`, `esm_model`, `uniprot_release`, `channels` (name → ID), `unembedded`, + `stats`, `pixel_size`, `model_um_per_px`, `crop_size`, `crop_step`, `patch_size`, `padding`, + `tile_size`, `batch_size`, `device`, `n_cells` and `n_cells_without_pixel` (per method), + `n_niches_kept`, `n_niches_dropped`. + +- Produces: `tools/virtues_parity.py OUT.json`: on the bundled example core, runs upstream exactly + as notebook 2 (spora-io standardiser with the blur, 120 px pad, `compute_cell_tokens`) at + `chunk_size` 32 and 8, and our `cell_embeddings` on the same raw image, mask and statistics + (written in the `virtues_stats.json` format). Reports per-cell cosine (min, median), max abs + difference, for upstream vs itself and ours vs upstream. + +- [ ] **Step 1: Write the failing tests.** + - `test_cli_outputs_layout`: a tiny store (as in `tests/unit/test_aggregate_compartments.py`) + with `region_of_interest`, two methods, `main(argv, encode=fake)`: row names, float16, + `var_names`, `uns` keys, niche polygon coordinates, the tissue table's single row. + - `test_cli_no_niche_writes_no_niche_files`. + - `test_unknown_uniprot_id_exits_naming_it`, `test_stats_mismatch_exits`. + - Model tests: `test_encoder_shape`, `test_determinism` (the same crops twice, equal). +- [ ] **Step 2: Run and confirm failure.** `pytest tests/unit/test_virtues_cells.py -v` +- [ ] **Step 3: Implement.** +- [ ] **Step 4: Run.** `pytest tests/unit -q` (model tests skipped). The model tests and the parity + tool run on the cluster in Task 11. +- [ ] **Step 5: Commit.** `VirTues runner: model, CLI and parity tool` + +### Task 6: Writer, segmentation writer and merge + +**Files:** + +- Modify: `bin/write_features.py`, `bin/write_segmentations.py`, `bin/merge_spatialdata.py`. +- Test: `tests/unit/test_write_features.py`, `tests/unit/test_merge_spatialdata.py`, the existing + `write_segmentations` tests. + +**Interfaces:** + +- Produces: `write_features(sdata_path: Path, tables: list[Path], shapes: list[Path] = ()) -> None`. + Each table's rows are checked by its region, before anything is touched: + - region `{M}_cells`: `obs_names` equal `tables/{M}_table`'s (Nimbus and VirTues cells); + - region a shapes file in this write: the instance key column equals that file's index, in + order; + - no region (`virtues_tissue`): no check; + - any other region: `ValueError` naming the table. + Then shapes and tables of the same names are removed by path, the store reconsolidated, shapes + written with the segmentation image's transformations (as `write_segmentations` does), then + tables. CLI: `--tables` and `--shapes`. +- Produces: `RESERVED` in `write_segmentations.py` becomes + `^((cellpose|instanseg)_(cells|nuclei|cytoplasm|table|nimbus|virtues)|virtues_(niches|niches_table|tissue))$`, + with `LEARNED_MODELS = ("nimbus", "virtues")`. +- Produces: `retarget_table` returns a table without `spatialdata_attrs` or with `region` `None` + unchanged; it is still renamed `{core}__{name}` by `merge`. + +- [ ] **Step 1: Write the failing tests.** + - `test_writes_niches_shapes_and_table`, `test_writes_unannotated_tissue_table`, + `test_niche_table_rows_must_match_shapes`, `test_nimbus_tables_still_checked_against_method_table`, + `test_rerun_is_idempotent` (with shapes). + - `test_write_segmentations_removes_stale_virtues_elements`: all four names. + - Replace `test_missing_attrs_refused` with `test_unannotated_table_copied_unchanged`; add + `test_tissue_table_renamed_per_core`. +- [ ] **Step 2: Run and confirm failure.** `pytest tests/unit/test_write_features.py tests/unit/test_merge_spatialdata.py -v` +- [ ] **Step 3: Implement.** +- [ ] **Step 4: Run.** `pytest tests/unit -q` +- [ ] **Step 5: Commit.** `Writer and merge: shapes and unannotated tables` + +### Task 7: Modules and configuration + +**Files:** + +- Create: `modules/local/virtues/`, `modules/local/virtues_histogram/`, + `modules/local/virtues_stats/`, each `main.nf`, `meta.yml`, `environment.yml`. +- Modify: `modules/local/write_features/main.nf` and `meta.yml`, `conf/base.config`, + `conf/gpu.config`, `conf/modules.config`, `containers.tsv`. + +**Interfaces:** + +- Produces: `VIRTUES_HISTOGRAM`: input `tuple val(meta), path(sdata_path), val(spec)`; output + `tuple val(meta), path("${meta.sample}_virtues_hist.npz")`, `versions.yml`; label `process_low`; + sopa image; tag `"${meta.sample}:virtues_histogram"`. +- Produces: `VIRTUES_STATS`: input `tuple val(slide), path(hists), val(spec)`; output + `tuple val(slide), path("${slide}_virtues_stats.json")`, `versions.yml`; label + `process_single`; sopa image. +- Produces: `VIRTUES`: input `tuple val(meta), path(sdata_path), val(methods), val(spec), path(stats)`; + output `tuple val(meta), path("*.{h5ad,parquet}")`, `tuple val(meta), path("virtues.json")`, + `versions.yml`; labels `process_medium`, `process_long`; the `VirTues` image; tag + `"${meta.sample}:virtues"`. The script runs `NIMBUS`' `gpu_check` and fails without + `task.accelerator` ("use_virtues: VIRTUES needs a GPU"). `versions.yml` records `virtues` + (`$VIRTUES_COMMIT`), `torch`, `flash_attn`. The stub touches each `${m}_virtues.h5ad`, + `virtues_niches.parquet`, `virtues_niches_table.h5ad`, `virtues_tissue.h5ad`, `virtues.json`. +- Each of the three stubs also writes `${task.accelerator ? 'gpu' : 'none'}` to `.accelerator` in + its work directory (not an output), for the stub tests. +- Produces: `WRITE_FEATURES` input `tuple val(meta), path(sdata_path), path(features)`; its script + passes `*.h5ad` as `--tables` and `*.parquet` as `--shapes`. +- Config: + - `conf/gpu.config` selector `'SEGMENT_PATCH_(CELLPOSE|INSTANSEG)|NIMBUS|VIRTUES'`. + - `conf/base.config`: `withName: 'VIRTUES' { cpus = 4 }`. + - `conf/modules.config`: publish `VIRTUES_STATS` JSON to `learned_features/`, and `VIRTUES`' + `virtues.json` as `${meta.sample}_virtues.json`. + +- [ ] **Step 1: Write the modules and config.** +- [ ] **Step 2: Regenerate and check the manifest.** + Run: `tools/container_manifest.py && tools/container_manifest.py --check && prek run --all-files` + Expected: a `josenimo/virtues:d2c25e1-2` row; clean. +- [ ] **Step 3: Commit.** `Add VIRTUES, VIRTUES_HISTOGRAM and VIRTUES_STATS` + +### Task 8: `LEARNED_FEATURES` wiring + +**Files:** + +- Modify: `subworkflows/local/learned_features/main.nf` and `meta.yml`, `docs/pipeline_paths.mmd`. +- Test: `tests/virtues.nf.test` (new); `tests/nimbus.nf.test` must still pass. + +**Interfaces:** + +- Consumes: Tasks 2 and 7. +- Changes in `LEARNED_FEATURES`: + - The unknown-model `error()` accepts `virtues`. Nimbus rows stay per method; VirTues gets one + row per store, with `methods` and the spec resolved as + `spec + [channels: virtuesChannels(rows), unembedded: virtuesUnembedded(rows)]`. + - An empty `virtuesChannels(rows)` fails with + `error("Sample '${meta.sample}': no marker row with a uniprot_id reached VirTues. With use_backsub, check that backsub kept the uniprot_id column.")`. + - Slide key: `meta.slide ?: meta.sample`. Histograms are grouped per slide with `groupTuple()` + (core counts are not known in advance, so it waits for every store). With `spec.stats`, the + statistics tasks are skipped and `file(spec.stats)` goes to every store. + - Statistics join back to stores with `combine(..., by: 0)` on the slide key, since a slide has + many stores. + - Per store, every model's outputs are grouped with + `groupKey(sdata_dir, n_outputs)`, where + `n_outputs = specs.sum { s -> s.model == 'virtues' ? 1 : methods.size() }`, each item a list of + files, flattened and sorted by name for `WRITE_FEATURES`. + - `VIRTUES_STATS` and `VIRTUES` versions are mixed in. + +- [ ] **Step 1: Write the failing tests** in `tests/virtues.nf.test` (profile `test,laptop`, + `-stub`, tags `stub`, `pipeline`), building the sample sheet as `tests/tma.nf.test` does with + `tests/stub_data/markers_virtues.csv`, and `use_virtues`, `use_gpu`, `use_tissue_segmentation`, + `pixel_size = 0.65`. + - `test("one method: histogram, stats, one VIRTUES, one write")`: one of each; QC starts after + `WRITE_FEATURES` ends; `learned_features/testslide_virtues_stats.json` and + `learned_features/testslide_virtues.json` published; `VIRTUES` in the versions file; `.accelerator` + is `gpu` for `VIRTUES` and `none` for the other two. + - `test("two methods: one VIRTUES for both")`, adding InstanSeg. + - `test("TMA: one stats task per slide, one VIRTUES per core")`, with `tests/tma.nf.test`'s + params: 4 histograms, 1 stats, 4 `VIRTUES`. + - `test("virtues_stats given: no statistics tasks")`, with a stats file written in setup. + - `test("with Nimbus: both models, one write per store")`. + - `test("use_virtues off runs none of the three")`. +- [ ] **Step 2: Run and confirm failure.** `nf-test test tests/virtues.nf.test` +- [ ] **Step 3: Implement.** If Task 1 found that backsub drops unknown columns, stop here and + report before choosing how to carry `uniprot_id` past it. +- [ ] **Step 4: Run.** `nf-test test --tag stub && nf-core pipelines lint` + Expected: pass; no new lint failures. +- [ ] **Step 5: Re-render the metro map** (`docs/CONTRIBUTING.md#metro-map`); list it in the final + report for the user to look at. +- [ ] **Step 6: Commit.** `Wire VirTues into LEARNED_FEATURES` + +### Task 9: Documentation and release notes + +**Files:** + +- Modify: `docs/usage.md`, `docs/output.md`, `docs/decisions.md`, `CITATIONS.md`, `CHANGELOG.md`, + `ROADMAP.md`, `site/myst.yml`. +- Create: `site/modules/virtues.md`; an example marker sheet with `uniprot_id` under `assets/` + if one exists for Nimbus, else in the page. + +- [ ] **Step 1: Write the docs** listed in the spec's "Docs and release", in plain language for + `site/`. `docs/output.md` gets a snippet: + + ```python + sdata["cellpose_virtues"].X # cells x 512, float16 + ``` + +- [ ] **Step 2: Release notes.** `CHANGELOG.md`: VirTues under Added in the next minor release + (`## v3.3.0 - [unreleased]` unless `nextflow.config` shows 3.2.0 still unreleased; then + under 3.2.0). `ROADMAP.md`: VirTues out of 3.4, KRONOS stays; add QC plots, per-tile tasks, a + crop-step parameter, pre-stitched input. `CITATIONS.md`: VirTues, ESM-2, UniProt, spora; the + `sp32` CC BY-NC 4.0 licence. +- [ ] **Step 3: Build.** `site/build.sh && prek run --all-files`. Expected: no broken links; clean. +- [ ] **Step 4: Commit.** `Document VirTues embeddings` + +### Task 10: QC chapter (cuttable) + +**Files:** + +- Modify: `bin/qc_metrics.py`, `bin/qc_report.py`, `conf/modules.config` (`QC_METRICS` ext.args + adds `--virtues-table ${meta.method}_virtues` when `params.use_virtues`). +- Test: `tests/unit/qc/test_qc_metrics.py`, `tests/unit/qc/test_qc_report.py`. + +**Interfaces:** + +- Produces: `virtues_metrics(uns: dict, method: str) -> dict`: channels used, `unembedded`, the + statistics per marker, cells embedded and without a pixel for `method`, squares kept and dropped. +- Produces: `virtues_section(v: dict) -> str`, facts only; `build` appends it when `"virtues" in +metrics`. + +- [ ] **Step 1: Write the failing tests**: the metrics from a hand-made `uns`; the report has + "VirTues" when present and not when absent. +- [ ] **Step 2: Run and confirm failure.** `pytest tests/unit/qc -q` +- [ ] **Step 3: Implement.** +- [ ] **Step 4: Run.** `pytest tests/unit -q && nf-test test --tag stub` +- [ ] **Step 5: Commit.** `QC: VirTues facts` + +### Task 11: Cluster checks + +No code. Write each command for the user, who submits it; record results in the SDD ledger and the +final report. + +- [ ] **Step 1: Model tests and parity.** `pytest tests/unit/test_virtues_model.py` and + `tools/virtues_parity.py` in the image on an A40. + **Gate.** Pass when ours vs upstream is within upstream vs itself; if upstream vs itself is + exactly zero, when every cell's cosine is ≥ 0.999 (report the max abs difference). Otherwise + stop and report the numbers; do not loosen the bar. +- [ ] **Step 2: Exemplar-001** with `use_virtues`, `use_gpu`, `use_tissue_segmentation`, the same + run twice (determinism within the parity bar), peak memory and `VIRTUES` time from the + trace, crops per second. +- [ ] **Step 3: Backsub comparison.** Exemplar-001 with and without `use_backsub`; per-cell cosine + of the same cells (matched by `cell_id`), reported without a threshold. +- [ ] **Step 4: Sizing.** From Step 2, propose `VIRTUES` time and memory in `conf/base.config`. diff --git a/docs/superpowers/specs/2026-11-07-segmentation-benchmark-design.md b/docs/superpowers/specs/2026-11-07-segmentation-benchmark-design.md new file mode 100644 index 0000000..c5d22eb --- /dev/null +++ b/docs/superpowers/specs/2026-11-07-segmentation-benchmark-design.md @@ -0,0 +1,121 @@ +# cpsam_v2 and a ground-truth segmentation benchmark + +ROADMAP 3.3 items 1 and 2. Resources (3.2) are out of scope. + +## Goal + +1. Cellpose segments with `cpsam_v2` by default. Not benchmarked against `cpsam`: we follow the + cellpose developers. +2. Defaults for the steps before the model, chosen by whole-cell F1 against manual masks, run + on the cluster GPUs. Results in a ~13-slide `.pptx`. + +Success: the pipeline passes lint and stub tests on the new image; the array completes; the deck +names a recommended setting with its F1 against today's defaults. + +## Part A: cpsam_v2 in the pipeline + +- **Image** `docker.io/josenimo/sopa:2.3.0-1`: `FROM docker.io/josenimo/sopa:2.3.0` plus one layer + that bakes `cpsam_v2` into `$CELLPOSE_LOCAL_MODELS_PATH` (`/opt/cellpose_models`). No pip + re-resolve, so packages are identical. Dockerfile kept beside the 2.3.0 one in + `2_Infrastructure/PY47_test_SOPA/docker/`. Built for `linux/amd64`, pushed to Docker Hub. +- **Default** `pretrained_model = 'cpsam_v2'` in `nextflow.config`, the schema and + `bin/segment_patch.py`'s `METHOD_DEFAULTS`. A path still selects other weights. +- **Guard.** cellpose warns and loads its default for an unknown name, which then tries to + download. `SEGMENT_PATCH` fails, naming the model, when a bare name has no file in + `$CELLPOSE_LOCAL_MODELS_PATH`. +- Every module on `josenimo/sopa:2.3.0` moves to `2.3.0-1`; regenerate `containers.tsv`. +- CHANGELOG (default model changes, cell counts shift); one line in `decisions.md`. + +## Part B: the benchmark + +`tools/segmentation_benchmark/`, three steps. Data stays outside the repo (TissueNet is +non-commercial; sizes). + +### Datasets + +| Dataset | Role | Crops | Notes | +| ------------------------------------------------------- | -------- | ---------------- | --------------------------------------------------- | +| Cross-platform mIF (Aleynick 2023, Synapse syn27624812) | decides | ~160, 400–800 px | Vectra, Ultivue/Axioscan, CODEX; ImageJ ROI masks | +| Tonsil mIF (Zenodo 22107836) | confirms | 10, 100 px | 7 channels; paired cell/nucleus labels | +| TissueNet 1.1, test split only | confirms | ~1,250, 256 px | already 2-channel; cpsam trained on its train split | + +### 1. `prepare` (Mac, network) + +Download, then write one layout per crop: `image.tif` (C, Y, X), `cells.tif`, `nuclei.tif` +(uint32 instance labels), and one `crops.csv` (dataset, crop, platform, tissue, pixel size, +channel names, nuclear channel). ImageJ ROIs become labels; overlapping pixels go to the later +ROI and the overlap share is logged per crop. TissueNet and Synapse may need account tokens +from the user's environment. The user rsyncs the output to cluster scratch. + +### 2. `run` (cluster GPU, in `sopa:2.3.0-1`, offline) + +`run --setting-index N` reads row N of `settings.csv`, segments every applicable crop with +`cpsam_v2`, scores it, and writes `results/N.csv`: one row per crop. Written to a temp file, +then renamed; a task whose result exists exits at once, so resubmitting the array reruns only +failures. Labels are kept for 6 fixed montage crops only. + +Preprocessing is the pipeline's code: `combine`, `percentile_bounds` and `rescale` from +`bin/project_channels.py`, then sopa's Gaussian, CLAHE and `cellpose_patch`, as +`tools/benchmark_projection.py` does now. Percentiles are taken on the crop (the pipeline uses +the whole slide). Cell channel: every non-DNA channel, as the default marker sheet. `diameter` +fixed at 30. Crops under 256 px are reflect-padded to 256 and cropped back. + +### Settings + +Cells, raw-channel datasets (144 settings): + +| Factor | Levels | Today | +| ---------------------------------------- | ------------------------------- | ----- | +| `projection_method` | max, mean | max | +| `projection_low_percentile` | 1, 50 | 1 | +| `projection_sigma` | 0, 1, 2 | 1 | +| `gaussian_sigma` | 0, 1, 2 | 1 | +| `clip_limit` | 0, 0.2 | 0.2 | +| (`flow_threshold`, `cellprob_threshold`) | (2, −6) sopa, (0.4, 0) Cellpose | sopa | + +The roadmap's "sum" is `mean` here: the pipeline offers max and mean, sum is mean times a +constant, and Cellpose normalises each image. +TissueNet gets the last three factors (12). Nuclei on the DNA channel, scored against nuclear +masks, get the same three (12). Array: 168 tasks, 1 GPU each. + +### Scoring + +cellpose `metrics.average_precision` per crop: F1 at IoU 0.5 (primary), mean AP over IoU +0.5–0.9, true and false positives, false negatives, predicted and true counts. Ranking: mean +F1 over Cross-platform crops, with its spread. Tonsil and TissueNet are reported beside it. + +### 3. `report` (Mac) + +From `results/*.csv`: `summary.csv` (per setting and dataset), one effect plot per factor, a +heatmap of the strongest pair, per-platform consistency, and montages of today's defaults +against the best setting. The deck is built only from these files. + +Deck: title; question and `cpsam_v2`; datasets; method; grid; headline; factor effects; +interaction; consistency; thresholds; nuclei; montages and caveats; recommended defaults. + +## Adoption + +A later, separate commit after the user reads the deck: defaults in config and schema; +`decisions.md`'s benchmark paragraph rewritten, not appended to; CHANGELOG; ROADMAP 3.3 items +1–2 done. + +## Tests + +- pytest: ROI to labels on a toy ROI; scoring on hand-made label pairs with known F1; + `settings.csv` row count; benchmark projection equals `bin/project_channels.py` on one input; + the missing-weights guard. +- Image: `docker run` lists `cpsam_v2` and loads it. No segmentation on the Mac. +- Pipeline: prek, `nf-core pipelines lint`, stub nf-tests. +- Cluster: a one-task job timing one setting before the full array. + +## User steps + +Git push and PR; account tokens for downloads; rsync to scratch; submit `sbatch`; stage the new +image in the shared cache. The Docker Hub push of `2.3.0-1` is cleared for Claude. + +## Risks + +- Cross-platform may be in cpsam's training data; check the Cellpose-SAM paper before trusting + it as held out. +- Tonsil's 100 px crops: border cells weigh heavily. Small cells (~11 px) against diameter 30. +- Crop percentiles differ from slide percentiles; the effect is reported, not removed. diff --git a/docs/superpowers/specs/2026-11-11-learned-features-nimbus-design.md b/docs/superpowers/specs/2026-11-11-learned-features-nimbus-design.md new file mode 100644 index 0000000..4fc0edf --- /dev/null +++ b/docs/superpowers/specs/2026-11-11-learned-features-nimbus-design.md @@ -0,0 +1,378 @@ +# 3.4: learned features, starting with Nimbus + +ROADMAP "3.4 onward". This adds an optional stage after segmentation. The stage runs per-cell +models on the image and the cells. Nimbus is the first model; KRONOS and VirTues plug into the +same stage later. + +## Goal + +With `use_nimbus`, each segmentation method gets a second table, `{method}_nimbus`. It holds one row +per cell, the same rows as `{method}_table`, with one column per marker. Each value is a Nimbus +confidence score in [0, 1]. + +Models are chosen as segmentation methods are: one `use_` flag each, and one spec per +enabled model. + +Success means all of the following hold: + +- pytest passes. +- The stub nf-tests pass with Nimbus on and off. +- A parity test shows the tiled runner matches upstream Nimbus on a crop. +- On exemplar-001 the scores separate known positive and negative populations. CD45 is one check. +- Peak memory does not grow with image size. +- CPU and GPU give the same scores within float tolerance. + +## Findings that shape the design + +Sources are the Nimbus-Inference 0.0.5 source, sopa 2.3.0, and the KRONOS, CORAL and VirTues +repositories, read on 2026-11-11. + +- **Nimbus licences.** The code and weights are MIT, and the weights are not gated (HF + `JLrumberger/Nimbus-Inference`, `V1.pt`). A local `V*.pt` in the package's `assets/` folder, with + `checkpoint="V1.pt"`, loads with no network call. +- **What Nimbus does.** It scores each channel on its own. The normalised channel and a binary + whole-cell mask go in; a pixel confidence map comes out. A cell's score is the mean over its + pixels. There is no marker vocabulary. It was trained on whole-cell masks. +- **Normalisation.** Each channel is divided by the 0.999 quantile of its nonzero pixels, then + clipped to [0, 1]. Upstream averages the quantile over up to 10 FOVs, picked by an unseeded + shuffle. +- **Rescaling.** Nimbus rescales by `model_magnification / magnification`, with defaults 10 and 20. + The repository does not say how many microns per pixel "10x" means. +- **Memory.** Upstream holds each whole channel in RAM. It tiles internally at an `input_shape` of + 1024 px. +- **Test-time augmentation.** It is on by default and costs several forward passes. Nimbus + advises turning it off on CPU. +- **sopa's wrapper is not tiled.** `sopa.aggregation.nimbus` (2.2.3+, experimental, no CLI) + rasterises one full-image mask and writes every channel as a full-size TIFF. It suits a TMA core, + not a whole slide. +- **Dependency clash.** Nimbus pins `numpy<2`. `josenimo/sopa:2.3.0` has numpy 2.5.4, torch 2.15 + and spatialdata 0.8.0. +- **Loading on CPU is unverified.** `torch.load` is called without `map_location`, so `V1.pt` may + fail to load on a CPU-only node. +- **KRONOS2.** The weights are CC-BY-NC-ND and gated, and the terms forbid redistribution. So they + cannot be baked into a shared image. KRONOS2 also needs marker names that match its 268-marker + vocabulary. +- **VirTues.** The `sp31` weights are MIT and ungated. It needs a CUDA GPU (flash-attn) and a + UniProt ID per channel. KRONOS2 gives one 768-d embedding per cell, and VirTues gives 512-d. + +## Approaches + +1. **Call `sopa.aggregation.nimbus`.** Least code, but memory grows with the image. That breaks + the reason the pipeline tiles. Rejected. +2. **Our own tiled runner, chosen.** One task runs per sample × segmentation method × model. It + loops over tile windows, as quantification does. It reuses Nimbus's own functions for input + preparation, inference and the per-cell mean. +3. **One task per tile, then a gather.** More throughput, but more graph and queue overhead. + Deferred: approach 2's tile function is the unit it would call, if exemplar runs are too slow. + +## Parameters + +**One pixel size for the pipeline.** `pixel_size` (number, µm per pixel, unset) replaces +`instanseg_pixel_size`. It is required with `use_instanseg` or `use_nimbus`, and is available to +later steps. + +`instanseg_pixel_size` is deprecated, not removed. v3.1.0 is released, so removing it would force a +4.0.0. A run that gives it gets a warning naming `pixel_size`, and its value is used. Giving both +with different values stops the run. Removal waits for the next major release. The change ships in +its own commit, before any Nimbus work, and the release stays a minor one (3.2.0). + +**A new schema group, "Learned features":** + +| Parameter | Type, default | Meaning | +| ----------------- | ---------------- | ------------------------------------------------------------------------------ | +| `use_nimbus` | boolean, `false` | Score marker positivity per cell with Nimbus. | +| `nimbus_channels` | string, unset | Markers to score. Unset means every `marker`-role channel in the marker sheet. | + +`use_gpu` also gives each Nimbus task a GPU. + +**Validation.** `validateParams` stops the run in each case below, with its own message: + +- `use_nimbus` without `pixel_size`. +- `use_nimbus` without `segment_cells`. Nimbus was trained on whole cells, so nucleus scores + would mislead. +- `use_nimbus` without a marker sheet and without `nimbus_channels`. + +A name in `nimbus_channels` that is not a channel of the image is caught per sample instead, in the +subworkflow, with `error()`. + +`use_nimbus` without `use_gpu` only warns. The warning says CPU gives the same scores but takes +hours per whole slide. CPU stays allowed for Mac tests and small TMAs. + +## Specs + +`featureSpecs(params)` in `modules/local/utils.nf` mirrors `segmentationSpecs`. It returns one map +per enabled model: + +```groovy +[name: 'nimbus', model: 'nimbus', channels: [...] or null, pixel_size: 0.65, gpu: true|false] +``` + +Channels left `null` are filled per sample from the marker sheet, as InstanSeg's are. A new model +is one more `if (args.use_)` block. + +## Graph + +A new subworkflow, `LEARNED_FEATURES`, runs after `SEGMENTATION`, and only when a model is enabled. +QC, `COMPARE_SEGMENTATIONS` and `MERGE_SPATIALDATA` then read its output store instead of +`SEGMENTATION`'s. With no model enabled, the graph is unchanged. + +```text +SEGMENTATION.out.sdata ──► NIMBUS (per store × segmentation method) + ──► WRITE_FEATURES (per store) ──► QC, COMPARE_SEGMENTATIONS, merge +``` + +**`NIMBUS`** runs once per store and segmentation method, on GPU with `use_gpu`. The store is only +read. + +- **Inputs:** the image and `{method}_cells`. +- **`{method}_nimbus.h5ad`:** the scores, with obs copied from `{method}_table`. +- **`{method}_nimbus.json`:** provenance. + +**`WRITE_FEATURES`** runs once per store, and is the only task that writes in this stage. + +- It writes each `{method}_{model}` table. +- It refuses to write if the rows differ from `{method}_table`'s `obs_names`. +- It removes an existing element by path before writing it, as `WRITE_SEGMENTATIONS` does. So a + retry and `-resume` give the same result. +- It runs strictly after `WRITE_SEGMENTATIONS`, and QC waits for it. Writes are never concurrent. + +**Stale feature tables.** `WRITE_SEGMENTATIONS` adds `{method}_nimbus` to its pipeline-owned names. +A rerun that rewrites a method's shapes therefore also removes feature tables built from the old +shapes. + +## Normalisation: per store + +Normalisation is per store: per core on a TMA, per image otherwise. A slide-wide factor would +remove differences between patients' cores; per core, each core is scored on its own terms. The +cost is known: in a core with no positive cells, noise is stretched to [0, 1] and can score as +signal. + +The method is as follows: + +- **Factor.** Inside `NIMBUS`, the factor per channel is the 0.999 quantile of nonzero pixels. +- **Determinism.** The quantile is exact over a fixed-stride subsample of the store's image, so it + is deterministic. +- **Methods agree.** Each segmentation method computes the factors again. They are identical, and + the step is cheap next to inference. +- **Empty channels.** A channel with no nonzero pixel is not scored. Its column is NaN, it is + logged, and it is listed in `uns`. + +A slide-wide option is a ROADMAP item, not a parameter now. + +## The `{method}_nimbus` table + +A `TableModel` that annotates `{method}_cells`, with the same cell ids as `{method}_table`. It +survives the TMA merge, which copies every table and retargets its region. + +- `X`: the scores, float32, cells × markers. NaN for an unscored channel, or for a cell that covers + no pixel centre. +- `var_names`: the marker names, in marker-sheet order. +- `obs`: `region`, `slide`, `core_id` and `cell_id`, copied from `{method}_table`. +- `uns['nimbus']` records: + - the package version, the weights file and its sha256; + - the channels and the normalisation factor of each; + - `pixel_size` and the magnification; + - the tile size, the margin, the halo and test-time augmentation; + - the device. + +**Why a table, not a layer.** A layer must share `{method}_table`'s `var`, which is marker × +statistic, so scores would be duplicated or padded with NaN. A table is also what viewers colour +cells by, so `cellpose_nimbus` / `CD3` is one selection in napari-spatialdata. + +## The tiled runner + +The runner is `bin/nimbus_cells.py`. Its pure functions are tested without the model. + +**Tiles and windows, sized at the model's scale.** The image is resized by `pixel_size` before +inference, so sizes are set in model pixels and converted with `/ pixel_size`. + +- **Tile.** The tile is 2048 model px. Each cell belongs to the tile holding its centroid. +- **Window.** It is the tile grown to cover its cells' bounds, plus a context margin. +- **Margin.** The margin is the model's halo plus 32, in model px. The halo is measured at start-up + as `(input_shape - output_shape) // 2` of the valid-padding model, about 92 px from the + architecture. The extra 32 covers the pooling phase and resize rounding. +- **Minimum window.** It is 1056 model px, so the valid path is always taken (see below). Windows + clipped at the image border are shifted inward to reach it, where the image is large enough. +- **Labels.** Every shape that intersects the window is rasterised with integer labels, because + neighbours shape the binary mask Nimbus sees. Only owned cells are scored, each exactly once. + +**Inference per window.** + +- The window is read one channel at a time and normalised with the store's factors. +- It then goes through Nimbus's `prepare_binary_mask`, `prepare_input_data`, `test_time_aug` and + `segment_mean`, the same calls upstream's `predict_fovs` makes. +- `magnification` is `10 / pixel_size`, which assumes the model's "10x" is 1 µm/px. The plan's + first task verifies this with the paper or the authors. + +**Why tiling changes nothing Nimbus computes.** Verified in the Nimbus 0.0.5 source: + +- **One global step, the per-channel factor.** It is computed once per store, before tiling, and + every window gets the same factor. A channel with no factor is never passed on: Nimbus would + quietly fall back to that window's own quantile, a per-tile normalisation. +- **No per-tile statistics in the model.** Its BatchNorm layers run in eval mode on fixed + statistics. Test-time augmentation averages within one input. +- **Context.** A margin at least the halo gives every owned cell's pixels the same receptive field + as whole-image inference. +- **One code path.** Upstream uses the reflect-padding model for inputs of 1024 px or less and + tile-and-stitch with the valid model above that. The two give different results, and each switch + reloads the weights from disk. The minimum window keeps every window on the valid path, as + whole-slide inference upstream would be. The exception is an image smaller than the minimum, + which upstream also runs on the reflect path. +- **Resize and pooling phase.** The window origin does not fall on the whole image's resize and + pooling grid, so equality is close, not exact. A test with the real model measures it: one + window against many small ones on the same crop. If the difference exceeds 0.01, the run stops + and checks in. + +**Same results on every device.** Test-time augmentation stays on, the Nimbus default, on CPU and +GPU alike. No other setting depends on the device. + +**Device.** The device comes from `task.accelerator`, as in `SEGMENT_PATCH`. A requested CUDA device +that is absent fails the task. + +`uns['nimbus']` also records the tile size, the margin and the measured halo. + +## Container + +The plan's first task is a spike. It builds `docker.io/josenimo/nimbus:0.0.5` FROM +`josenimo/sopa:2.3.0`: + +- It installs `Nimbus-Inference==0.0.5 --no-deps` plus its real runtime dependencies. +- It bakes `V1.pt` into `nimbus_inference/assets/`. +- It sets `HF_HUB_OFFLINE=1`. + +The spike passes when three things hold under numpy 2: + +1. Nimbus imports. +2. `V1.pt` loads on CPU. +3. On one exemplar-001 crop that fits a single window, our runner equals upstream `predict_fovs` + within 1e-4. Upstream runs in a plain numpy<2 environment. + +If the spike fails, the fallback is a sopa-image step that exports tile arrays for `NIMBUS` to +read. That doubles disk I/O but keeps the environments apart. Choosing it needs a short check-in. + +The Dockerfile goes in `tools/containers/nimbus/`. The image is listed in `containers.tsv`, and is +pre-staged as the sopa image is. + +## Resources + +- **Memory is flat.** `NIMBUS` holds one window × channel at a time. It uses `process_medium` and 4 + CPUs, as `SEGMENT_PATCH` does. +- **Time grows with area × channels.** Roughly hours per whole slide on CPU and minutes on an A40, + both unmeasured. So the time limit is generous, and 3.2's sizing replaces it. +- **GPU.** `conf/gpu.config` adds `NIMBUS` to the accelerator selector. + +## Extending to KRONOS and VirTues + +Every model follows the same contract: + +- **One flag and one spec.** Each model adds `use_` and one spec block. +- **One module per model.** Its input is `[meta, sdata, method, spec]`, plus any model-specific + extras. Its outputs are `{method}_{model}.h5ad` and `.json`, with the same rows as + `{method}_table`. +- **One table per model and method.** Scores have markers as `var`. Embeddings have dimensions as + `var` (`kronos_0` …). +- **Shared plumbing.** `LEARNED_FEATURES` branches on `spec.model`, as `SEGMENTATION` branches on + `spec.method`. `WRITE_FEATURES` writes whatever tables arrive. + +Adding a model touches about ten places: + +- `nextflow.config` and `nextflow_schema.json`: `use_` and its parameters, then + `assets/params_template*.yml` through the prek hook. +- `validateParams` (`utils_nfcore_histo_pipeline`): its requirements, and any channel check. +- `featureSpecs` (`modules/local/utils.nf`): its spec block. +- `LEARNED_FEATURES`: the model guard, its channel resolution, its `branch` entry and its mix into + `ch_scores`. +- Its module under `modules/local/`, with `meta.yml`, a stub and `versions.yml`. +- `conf/modules.config`, `conf/base.config`, `conf/gpu.config` and `conf/sizes.config`: publishing, + resources, accelerator and sizing. +- `containers.tsv` and `tools/container_manifest.py`: its image. +- `LEARNED_MODELS` in `bin/write_segmentations.py`. Forgetting it leaves a stale table from old + shapes after a re-segmentation with the model off. +- `CITATIONS.md`, `CHANGELOG.md`, `docs/output.md` and the site module page. + +Each later model needs decisions of its own, kept out of this release: + +- **KRONOS2:** a weights path supplied per user, not baked in, and a vocabulary check that fails + loudly. +- **VirTues:** a `uniprot_id` marker-sheet column, and a check that refuses to run without a GPU. + +## Tests + +**pytest**, in `tests/unit/test_nimbus_cells.py` and `test_write_features.py`. A fake model +returns the normalised input, so means are hand-computable. + +- **Ownership.** Every cell is scored exactly once, for any tile size. With the fake model, scores + are independent of tile size. +- **Windows.** Neighbours are present in the binary mask, and cells at the window edge are whole. +- **Normalisation.** The quantile is deterministic, and an empty channel gives a NaN column. +- **Writer.** It writes the table and `uns`, refuses a row mismatch, and is idempotent on rerun. + `WRITE_SEGMENTATIONS` removes a stale `{method}_nimbus`. +- **Specs.** `featureSpecs` and the default channels from the marker sheet. + +**nf-test:** + +- Stub runs: Nimbus with one method, with two methods, and on a TMA. +- With `use_nimbus` off, the graph is unchanged. +- Validation: each new `validateParams` rule, and the deprecated `instanseg_pixel_size` (warns; both differing stops). +- Every existing test that sets `instanseg_pixel_size` moves to `pixel_size`. + +**Container and real data.** + +- The parity test runs in the container on the Mac, on a one-patch crop, as CONTRIBUTING allows. +- The same crop runs on CPU on the Mac and on GPU on the cluster, and the scores are compared. +- Then exemplar-001 runs on the cluster. I propose the commands; you submit them. + +## Docs and release + +**Release.** The release is minor, 3.2.0. In `CHANGELOG.md`, Nimbus goes under Added and the +`instanseg_pixel_size` deprecation under Deprecated. The site tutorials and parameter pages move to +`pixel_size`, and the parameter reference is regenerated. + +**Stale version docs fixed first.** v3.0.0 and v3.1.0 are published releases (2026-11-07). On dev, +however: + +- `manifest.version` still says 2.0.0; +- the CHANGELOG lists 3.0.0 as unreleased; +- the CHANGELOG has no 3.1.0 entry. + +A separate commit sets the manifest to 3.1.0, dates 3.0.0, and adds 3.1.0 from +`git log v3.0.0..v3.1.0`. + +**Other docs:** + +- `docs/output.md`: the `{method}_nimbus` table, a snippet to read one marker's scores, and the + `uns` keys. +- `docs/usage.md`: `pixel_size`, a GPU recommendation, and the cost of test-time augmentation. +- `docs/decisions.md`, a "Learned features" entry covering: + - a stage after segmentation, with one table per model; + - tile windows; + - per-store normalisation and why; + - test-time augmentation fixed on; + - cells only; + - one pixel size. +- The `site/` module page for Nimbus. +- `CITATIONS.md` (Nimbus). +- `ROADMAP.md`: Nimbus out of 3.4; a slide-wide normalisation option added. +- `containers.tsv` and the metro map, re-rendered for a human to check. + +**A minimal QC chapter**, per marker: the fraction of cells scoring above 0.5 and the median score. +It goes in `_qc.json` and the report. It is the last task, so it can be cut. + +## Out of scope + +- Using the scores in cell filtering (3.0 item 1). +- Slide-wide normalisation. +- Nimbus fine-tuning. +- Saving per-pixel prediction maps. +- One task per tile. +- KRONOS and VirTues themselves. +- Reading the pixel size from OME metadata. + +## Settled in review (2026-11-11) + +1. Normalisation is per core on TMAs, to keep inter-patient differences. +2. Whole cells only. +3. One `pixel_size` for the pipeline; `instanseg_pixel_size` is deprecated, so the release stays minor. +4. GPU is recommended, and results are the same on CPU and GPU. +5. Scores go in a new table per method rather than a layer. +6. Tiles must not change Nimbus's maths: one global factor per store, a margin from the model's halo, and one code path. diff --git a/docs/superpowers/specs/2026-11-24-learned-features-virtues-design.md b/docs/superpowers/specs/2026-11-24-learned-features-virtues-design.md new file mode 100644 index 0000000..62d456a --- /dev/null +++ b/docs/superpowers/specs/2026-11-24-learned-features-virtues-design.md @@ -0,0 +1,332 @@ +# 3.4: learned features, VirTues + +ROADMAP "3.4 onward". VirTues is the second model in the `LEARNED_FEATURES` stage that Nimbus +added ([Nimbus design](2026-11-11-learned-features-nimbus-design.md)). It gives every segmented +cell, every 128 µm tissue square and every core or slide a 512-number embedding from a spatial +proteomics foundation model, so cells and regions can be clustered, compared across patients and +fed to classifiers. + +## Goal + +With `use_virtues`, each store gains: + +- `{method}_virtues`: one row per cell, the same rows as `{method}_table`, 512 columns. +- `virtues_niches` (squares) with `virtues_niches_table`: one row per 128 × 128 µm tissue square. +- `virtues_tissue`: one row per store (a core on a TMA, the image otherwise). + +Success for this release is engineering only; usefulness on real data is judged afterwards (see +"After the build"): + +- pytest and the stub nf-tests pass, with VirTues on and off and on a TMA. +- **Parity:** on the example core bundled in the VirTues repository, our runner's cell embeddings + differ from upstream `compute_cell_tokens` by no more than upstream differs from itself when only + its batch size (`chunk_size`) changes, both measured on the cluster GPU. If upstream's own + difference is zero (FlashAttention keeps crops apart, so it may be), the bar is a per-cell cosine + similarity of at least 0.999, with the largest absolute difference reported. Worse comes back to + you. +- Two GPU runs give the same embeddings within that same bar. +- The statistics computed from histograms equal a direct numpy computation. +- Peak memory does not grow with image size. + +## Findings that shape the design + +Read on 2026-11-24: `bunnelab/virtues` at `d2c25e1`, `bunnelab/spora-io`, HF `bunnelab/virtues`, +arXiv 2501.06039v2 and 2610.24002 (spora), spora docs. The Nature paper (s41586-026-10884-y) is +paywalled and was not read. + +- **Licences.** Code MIT. Weights ungated: `sp32` CC BY-NC 4.0 (the authors' academic default and + the benchmarked model), `sp31` MIT, `imc14` CC BY-NC 4.0. spora-bench is CC BY-NC-ND: do not + adapt its code. +- **GPU only.** `flash_attn.flash_attn_varlen_qkvpacked_func` is imported unconditionally. No CPU + path, no Mac path. The cluster's A40s (Ampere) support FlashAttention 2. +- **Model.** `sp32/model.safetensors`: 43.4 M parameters (encoder 34.6 M), float32, 174 MB. + `model_dim` 512, patch 8 px, crops 128 px. Upstream inference runs under fp16 autocast. +- **Marker identity.** Each channel needs a UniProt ID (isoform suffix allowed, e.g. `P08575-8`). + Its sequence is embedded by ESM-2 `esm2_t30_150M_UR50D`. The embeddings are a non-persistent + buffer, so any panel works without retraining. +- **DNA stains are not embedded upstream.** In the bundled example, `Iridium` channels have no ID + and are left out; a Histone H3 _antibody_ is embedded as `P68431`. +- **Resolution.** spora resamples every dataset to 1.0 µm/px. The resampling method for + multiplex images is not published. +- **Intensity recipe** (spora-io `std.py`, `standardize.py`): over tissue pixels only (a tissue + mask), clip each channel at its 0.99 quantile, `log1p`, z-score with mean and SD, then at + inference a 3 × 3 Gaussian blur (sigma 1). Statistics are computed before the blur. SD is the + population SD (from sum, sum of squares and count). The released weights were trained with the + cap **per image** (an IMC region, about a core) and mean and SD **per dataset**, often hundreds + of slides (`quantile_clipping_log1p/uq_0.99_image`, `stats_level="global"`). Per-slide + statistics (settled below) therefore depart from training; `virtues_stats` is the way back to + dataset-wide statistics. +- **Cell embeddings** (`virtues/utils/cell_tokens.py`): the image (padded by 120 px of zeros + before standardisation) is cut into 128 px crops every 42 px, plus extra crops flush with the + bottom and right edges. Each crop's 16 × 16 patch embeddings are averaged into each cell, + weighted by the cell's pixel count in each patch. Upstream keeps every crop's embeddings in + memory (~120 GB for a 2 × 2 cm slide) and loops in Python. +- **Crops are independent.** Attention never crosses crops, so a crop's embeddings depend only on + its own pixels. +- **Niche and tissue embeddings** (paper): niche = mean of a non-overlapping 128 px crop's patch + embeddings, crops under 30% tissue skipped; tissue = mean over all patches. + +## Approaches + +1. **Call upstream `compute_cell_tokens` per store.** Least code; memory grows with the image. + Rejected. +2. **Convert stores to spora format and run their tools.** Closest to upstream; copies every image + a second time, and the whole-dataset tool is CC BY-NC-ND. Rejected. +3. **Our tiled runner, one GPU task per store. Chosen.** Upstream's encoder is called unchanged; + only the averaging into cells, squares and tissue is ours, and parity checks it against 1. +4. **3 with one task per tile, then a gather.** Multiplies SLURM jobs. Deferred: 3's tile function + is the unit it would call. + +## Settled with you (2026-11-24) + +1. Statistics per **slide**, per marker, one set per input image; on a TMA all cores of a slide + share them. A deliberate break from Nimbus's per-core choice: cells stay comparable across + cores and patients. +2. Statistics over **tissue pixels** from `use_tissue_segmentation`, which `use_virtues` requires. +3. The 0.99 clip is per slide too, like mean and SD. +4. `virtues_stats` (advanced): one statistics file applied to every slide of a run, for freezing a + rerun or normalising a cohort. +5. Cell, niche **and** tissue embeddings. +6. Niches are squares (shapes) with a table. +7. A channel is embedded **if and only if** its marker-sheet row has a `uniprot_id`. No parameter. +8. DNA stains are never embedded; no Histone H3 mapping. +9. Weights: `sp32`. +10. Cells only, no nuclei, like upstream. +11. Embeddings stored as float16. +12. QC: facts only for now; plots after real-data validation. +13. Approach 3, on the condition that its cell embeddings match upstream within GPU rounding noise. +14. Usefulness on published and in-house data is tested after the build, in a separate + conversation. +15. `use_virtues` requires `use_gpu`, so the whole run is on GPU, segmentation included. Accepted: + simpler, faster; outlines differ slightly from a CPU run, and InstanSeg's GPU channel limit + applies (raising it from 10 to 15 is a separate change). +16. `use_virtues` requires `use_preprocessing`: pre-stitched input has no marker sheet. Support for + it goes on the ROADMAP. + +## Parameters and the marker sheet + +**Learned features group:** + +| Parameter | Type, default | Meaning | +| --------------- | ---------------- | ----------------------------------------------------------------------------- | +| `use_virtues` | boolean, `false` | Embed cells, 128 µm tissue squares and each core or slide with VirTues. | +| `virtues_stats` | path, unset | Advanced. A `virtues_stats.json` from an earlier run, applied to every slide. | + +`use_gpu` gives each `VIRTUES` task a GPU. + +**Marker sheet:** a new optional column `uniprot_id`. The schema checks the UniProt accession +format with an optional isoform suffix (`-N`), so a marker name typed into it is caught. + +**Validation** (`validateParams`, each with its own message). The run stops when `use_virtues` +is set and: + +- `use_gpu` is off (FlashAttention has no CPU path); +- `use_preprocessing` is off (no marker sheet, so no UniProt IDs); +- `use_tissue_segmentation` is off; +- `segment_cells` is off; +- `pixel_size` is unset; +- no marker-sheet row has a `uniprot_id`; +- a `dna`-role row has a `uniprot_id` ("DNA stains are not embedded"); +- two rows share a `uniprot_id`; +- `virtues_stats` lacks a marker that would be embedded, or records a different `uniprot_id` for it. + +`virtues_stats` without `use_virtues` stops too. An ID with a valid format but absent from the +bundled UniProt sequences fails the task, naming the ID. + +## Specs + +`featureSpecs` gains: + +```groovy +[name: 'virtues', model: 'virtues', channels: null, pixel_size: pixelSize(args), stats: path or null] +``` + +`LEARNED_FEATURES` resolves `channels` per sample from the marker sheet as +`[[marker_name, uniprot_id], ...]`, in sheet order. + +## Graph + +```text +SEGMENTATION.out.sdata ─► VIRTUES_HISTOGRAM (per store) + │ grouped by meta.slide ?: meta.sample + VIRTUES_STATS (per slide) ─► virtues_stats.json (published) + │ joined on slide +SEGMENTATION.out.sdata ─► VIRTUES (per store, every method at once) ─► WRITE_FEATURES (per store) +``` + +- With `virtues_stats`, the two statistics tasks are skipped and the file goes to every store. +- **Histograms read the store after segmentation**, not alongside it, so no task reads a store + another task is mutating. They are cheap next to `VIRTUES`. +- **One `VIRTUES` task per store, not per method.** The GPU pass does not depend on cell masks; + only the averaging does, and it is repeated per method in the same task. +- `WRITE_FEATURES` remains the only writer in the stage. + +## Statistics + +`VIRTUES_HISTOGRAM` (CPU) reads the image at model scale (below) and `region_of_interest`, +rasterised at 1 µm/px (pixel centre inside a polygon). Per embedded marker it writes the histogram +of tissue-pixel values rounded to integers (an error under half a count). Rounding applies only to +the histogram; the model sees unrounded values. + +`VIRTUES_STATS` sums a slide's histograms and computes, per marker: + +- `cap`: the 0.99 quantile, equal to `numpy.quantile(pixels, 0.99)` with numpy's default method; +- `mean`, `sd`: of `log1p(min(x, cap))` over tissue pixels, population SD; +- `tissue_pixels`. + +`virtues_stats.json`: format version, slide, cores, model pixel size, and per marker name the +`uniprot_id`, `cap`, `mean`, `sd`, `tissue_pixels`. Published to `learned_features/` and copied +into every table's `uns`. + +Histograms assume an integer image (Ashlar writes uint16). If the image is not integer at this +point (e.g. after backsub), the plan stops and checks in. + +## The tiled runner + +`bin/virtues_cells.py`. Pure functions are tested with a fake encoder. + +**Model scale, without a temporary image.** The image is resampled to 1 µm/px by separable +area-weighted averaging. Weights come from global pixel coordinates only, so any window with +enough input context computes identical values. The histogram task and `VIRTUES` share this +function. No resampled copy is written. + +**Input.** Per window: resample, standardise with the slide statistics (clip, `log1p`, z-score), +then blur, with upstream's 120 px zero padding at the true image edge and blur context from +neighbouring pixels elsewhere. + +**Cells.** + +- The crop grid is upstream's `_get_uniform_crops` applied once to the padded whole image. +- Cells are rasterised at 1 µm/px (pixel centre rule, deterministic order for overlaps). A cell is + owned by the 2048 px tile holding its centroid. +- A window embeds every global crop that touches its owned cells, so every cell sees exactly + upstream's crop set. Crops on tile borders are embedded by both neighbours; that is accepted + overhead. +- Per cell, the sums of weighted patch embeddings and weights are accumulated in float32, then + divided. A cell with no pixel at 1 µm/px gets a NaN row and is counted in QC. + +**Niches.** A separate pass over non-overlapping 128 px crops on a grid from the image origin. +Squares not fully inside the image are dropped. A square is kept when at least 30% of its pixels +are inside `region_of_interest`. Its embedding is the mean of its 256 patch embeddings. + +**Tissue.** The mean of the kept squares' embeddings, which equals the mean over their patches. + +**Marker embeddings.** Computed in the task from the bundled UniProt sequences with ESM-2, using +upstream's `compute_esm_embeddings` functions unchanged. + +**Device.** CUDA from `task.accelerator`, checked as in `NIMBUS`. fp16 autocast as upstream. + +## Outputs + +- **`{method}_virtues`:** `TableModel` annotating `{method}_cells`, rows identical to + `{method}_table`. `X` float16, cells × 512; `var_names` `virtues_0` … `virtues_511`; `obs` + copied (`region`, `slide`, `core_id`, `cell_id`). +- **`virtues_niches`:** square polygons, in the image's coordinate system. + **`virtues_niches_table`:** annotates them; `X` float16, squares × 512; `obs` with + `tissue_fraction`. +- **`virtues_tissue`:** one row, `X` float16 1 × 512, `obs` `slide`, `core_id`, `n_niches`. No + region annotation: one vector per store does not map onto `region_of_interest`'s polygons. +- **`uns['virtues']`** on each: commit, weights file and sha256, ESM-2 model, UniProt release, + channels used and channels without an ID, the statistics, pixel size, crop size and step, + padding, tile size, device, counts. +- **Published:** `virtues_stats.json` per slide; a provenance JSON per store. + +## Writer and merge + +- `WRITE_FEATURES` also writes shapes, and accepts tables that are not per method: their rows + must match the shapes they annotate (`virtues_niches_table`), or there is no check + (`virtues_tissue`). It still removes each element by path before writing. +- `bin/write_segmentations.py`: `virtues` joins `LEARNED_MODELS`, and `virtues_niches`, + `virtues_niches_table` and `virtues_tissue` become pipeline-owned, so a rewrite removes stale + ones. +- `bin/merge_spatialdata.py`: tables without a region annotation are copied and renamed per + core, like the others. Today an unannotated table raises. + +## Container + +The plan's first task is a spike, a gate as for Nimbus. Image `docker.io/josenimo/virtues:` +in `tools/containers/virtues/`: + +- a CUDA PyTorch base with a matching prebuilt FlashAttention 2 wheel, plus spatialdata; +- `virtues` at the pinned commit; +- baked: `sp32/model.safetensors`, ESM-2 150M weights, the UniProt human Swiss-Prot sequences + with isoforms (release recorded); +- `HF_HUB_OFFLINE=1`, no network at run time. + +It passes when the image imports `virtues`, `flash_attn` and spatialdata, loads the weights, and +runs the bundled notebook's cell-embedding cell on a cluster GPU. If it cannot be built, it comes +back to you. Listed in `containers.tsv` and the manifest; staged as the other images are. + +## Resources + +- `VIRTUES`: one A40, memory flat (one window at a time, crops batched on the GPU). Time is + unmeasured; estimate ~3 h for a 5 × 5 cm slide at 40 markers. The first cluster run measures + crops per second, and sizing follows. +- `VIRTUES_HISTOGRAM`: CPU, `process_low`. `VIRTUES_STATS`: `process_single`. +- `conf/gpu.config` adds `VIRTUES` to the accelerator selector; `maxForks` applies. +- Jobs: one `VIRTUES` and one histogram task per store, one statistics task per slide. + +## QC + +A facts-only chapter in `_qc.json` and the report: + +- channels used and channels without an ID; +- the slide statistics per marker; +- cells embedded, and cells with no pixel at 1 µm/px; +- squares kept and dropped. + +Last task, so it can be cut. + +## Tests + +**pytest** (`tests/unit/test_virtues_cells.py`, `test_virtues_stats.py`, writer and merge tests), +with a fake encoder whose patch embedding is the patch's mean input, so results are +hand-computable: + +- the crop grid equals upstream `_get_uniform_crops`; +- every cell is owned once; tiled equals whole-image exactly, for any tile size; +- resampling is window-independent, bit for bit; +- histogram statistics equal numpy on the pooled pixels; +- the niche grid, the 30% rule, and tissue = mean of the kept squares; +- writer: shapes and the new tables, idempotent; stale elements removed; merge copies the + unannotated table. + +**nf-test:** stub runs with VirTues on (one method, two methods, a TMA with stats grouped per +slide, `virtues_stats` given) and off (graph unchanged); each validation rule. + +**Cluster** (I propose the commands, you submit): + +- the container spike; +- parity on the bundled example core, its own mask and statistics supplied through the + `virtues_stats` format; +- determinism: the same core twice; +- exemplar-001 end to end, peak memory recorded; +- exemplar-001 with and without backsub, reporting how far the same cells' embeddings move. No + threshold; it feeds the real-data conversation. + +## Docs and release + +- `docs/usage.md`: the `uniprot_id` column with an example, DNA not embedded, the GPU and tissue + requirements, `virtues_stats`. +- `docs/output.md`: the three tables and the squares, how to read them, the `uns` keys. +- `docs/decisions.md`, "Learned features": slide statistics over tissue and why; one task per + store; the global crop grid and why tiles match upstream; DNA not embedded; float16; `sp32`. +- The `site/` module page in plain language; an example marker sheet with `uniprot_id`. +- `CITATIONS.md`: VirTues, ESM-2, UniProt, spora; the `sp32` licence. +- `CHANGELOG.md`: Added, in the next minor release. +- `ROADMAP.md`: VirTues out of 3.4, KRONOS stays; new items: QC plots, per-tile tasks, a crop-step + parameter, pre-stitched input. +- `containers.tsv`, and the metro map re-rendered for a human to check. + +## Out of scope + +Marker reconstruction and inpainting; the segmentation head; nuclei; `sp31` and `imc14`; +fine-tuning; QC plots; per-tile tasks; a crop-step parameter; pre-stitched input; raising +InstanSeg's GPU channel limit; KRONOS. + +## After the build + +A conversation with you on real-data validation: which datasets (published Orion +`lin2023high` and IF `klein2026explainable` from spora, your trusted annotated sets) and what +result counts as useful, e.g. a linear classifier on embeddings against one on mean intensities, +split by patient. diff --git a/docs/usage.md b/docs/usage.md index 5e901e0..5262bb4 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -3,7 +3,7 @@ ## Quick start ```bash -nextflow run CosciaLab/histo -r v2.0.0 \ +nextflow run CosciaLab/histo -r v3.2.0 \ -profile singularity,size_small,slurm \ -params-file params.yml ``` @@ -111,7 +111,7 @@ Paths must be absolute. Required: `input`, `outdir` and, unless `preprocessing_only`, at least one segmentation method. Cellpose also needs `cellpose_channels` or `use_projection`; InstanSeg needs -`instanseg_pixel_size`. Everything else has a default. Parameters removed in 2.0 stop the run at +`pixel_size`. Everything else has a default. Parameters removed in 2.0 stop the run at startup; see [output.md](https://github.com/CosciaLab/histo/blob/dev/docs/output.md#from-1x). **Booleans on the command line follow Nextflow's rule: a bare flag means true, and anything else @@ -121,26 +121,29 @@ not work and never did: Nextflow reads the flag on its own, sets it true, and th before the pipeline sees it, so `--use_backsub false` would perform background subtraction. The pipeline stops at startup rather than letting that happen, for every boolean it declares. -| Parameter | Default | Change it when | -| -------------------------- | -------------------- | ------------------------------------------------------------------------------------------------------ | -| `use_preprocessing` | `true` | Your image is already stitched. Then the samplesheet is one row per sample with a `data_path` column. | -| `preprocessing_only` | `false` | You only want stitched images. No segmentation, quantification or sample QC; Ashlar's QC stays. | -| `ashlar_args` | `--maximum-shift 30` | Stitching misaligns. | -| `use_backsub` | `false` | You have background channels to subtract. | -| `skip_reference_dna_check` | `false` | Ashlar or Coreograph should deliberately use a channel that is not `dna`. | -| `use_tma_dearray` | `false` | Your slide is a tissue microarray. Each core is then processed alone and the results merged per slide. | -| `tma_expected_cores` | none | With `use_tma_dearray`: how many cores the slide has. See [TMA dearray](#tma-dearray). | -| `tma_core_diameter_mm` | none | With `use_tma_dearray`: the core diameter in mm. | -| `use_cellpose` | `false` | At least one of `use_cellpose` and `use_instanseg`; both may be on. | -| `cellpose_channels` | none | Always, unless `use_projection`. Marker names, nuclear last, e.g. `"CD45 DNA_1"`. | -| `use_projection` | `false` | Cellpose should see many markers, not one. See below. | -| `use_instanseg` | `false` | You want InstanSeg. Needs `instanseg_pixel_size`; channels default from each sheet. | -| `segment_cells` | `true` | You want nuclei only. See [Methods and targets](#methods-and-targets). | -| `segment_nuclei` | `false` | You want nuclei, linked to their cells. | -| `use_gpu` | `false` | On the cluster: one GPU per segmentation patch. See [GPU segmentation](#gpu-segmentation). | -| `patch_width_pixel` | `2000` | Your slide is larger than a few TMA cores. See below. | -| `patch_overlap_pixel` | `100` | Set to roughly twice a cell diameter. | -| `use_tissue_segmentation` | `false` | Large empty areas you want skipped. | +| Parameter | Default | Change it when | +| -------------------------- | -------------------- | ----------------------------------------------------------------------------------------------------------- | +| `use_preprocessing` | `true` | Your image is already stitched. Then the samplesheet is one row per sample with a `data_path` column. | +| `preprocessing_only` | `false` | You only want stitched images. No segmentation, quantification or sample QC; Ashlar's QC stays. | +| `ashlar_args` | `--maximum-shift 30` | Stitching misaligns. | +| `use_backsub` | `false` | You have background channels to subtract. | +| `skip_reference_dna_check` | `false` | Ashlar or Coreograph should deliberately use a channel that is not `dna`. | +| `use_tma_dearray` | `false` | Your slide is a tissue microarray. Each core is then processed alone and the results merged per slide. | +| `tma_expected_cores` | none | With `use_tma_dearray`: how many cores the slide has. See [TMA dearray](#tma-dearray). | +| `tma_core_diameter_mm` | none | With `use_tma_dearray`: the core diameter in mm. | +| `pixel_size` | none | You use `use_instanseg`, `use_nimbus` or `use_virtues`: µm per pixel of your image (OME PhysicalSizeX). | +| `use_cellpose` | `false` | At least one of `use_cellpose` and `use_instanseg`; both may be on. | +| `cellpose_channels` | none | Always, unless `use_projection`. Marker names, nuclear last, e.g. `"CD45 DNA_1"`. | +| `use_projection` | `false` | Cellpose should see many markers, not one. See below. | +| `use_instanseg` | `false` | You want InstanSeg. Needs `pixel_size`; channels default from each sheet. | +| `segment_cells` | `true` | You want nuclei only. See [Methods and targets](#methods-and-targets). | +| `segment_nuclei` | `false` | You want nuclei, linked to their cells. | +| `use_nimbus` | `false` | You want a per-cell marker positivity score. Needs `pixel_size` and `segment_cells`. See [Nimbus](#nimbus). | +| `use_virtues` | `false` | You want 512-number embeddings per cell, tissue square and core. See [VirTues](#virtues). | +| `use_gpu` | `false` | On the cluster: one GPU per segmentation patch. See [GPU segmentation](#gpu-segmentation). | +| `patch_width_pixel` | `2000` | Your slide is larger than a few TMA cores. See below. | +| `patch_overlap_pixel` | `100` | Set to roughly twice a cell diameter. | +| `use_tissue_segmentation` | `false` | Large empty areas you want skipped. | Every parameter and its default is in two generated files. [assets/params_template_compact.yml](https://github.com/CosciaLab/histo/blob/dev/assets/params_template_compact.yml) has one line each: @@ -190,21 +193,22 @@ Cellpose takes a nuclear and a cell channel, but an mIF panel spreads cell bound markers, each on some cell types only. `--use_projection` builds the two channels from the marker sheet (see `segmentation` above) and segments those; quantification still reads every marker. -Each marker is rescaled between its 1st and 99.9th percentile (zero padding ignored), smoothed with -σ = 1 px, then combined per channel by maximum. Maximum keeps a marker found on one cell type at -full brightness; `projection_method: mean` dims it and loses those cells. On hazy raw images, +Each marker is rescaled between its 1st and 99.9th percentile (zero padding ignored), then +combined per channel by maximum. Maximum keeps a marker found on one cell type at full +brightness; `projection_method: mean` dims it and loses those cells. On hazy raw images, `projection_low_percentile: 50` removes the haze from the cell channel. -**Set the Cellpose thresholds when projecting.** Unset, sopa's `flow_threshold: 2`, -`cellprob_threshold: -6` and CLAHE (`clip_limit: 0.2`) tile the whole tissue into cells whatever -the image shows. Cellpose's own values follow the membranes: +**The Cellpose defaults suit projection.** `flow_threshold: 0.6`, `cellprob_threshold: -1`, no +CLAHE and no smoothing come from a +[benchmark](https://github.com/CosciaLab/histo/blob/dev/docs/decisions.md#segmentation-benchmark) +against manual outlines. sopa's own values (2, -6, CLAHE 0.2) tile the whole tissue into cells +whatever the image shows. The default cell channel already leaves out autofluorescence and +nuclear markers, which the benchmark favoured; keep them out when you set the `segmentation` +column. ```yaml use_cellpose: true use_projection: true -flow_threshold: 0.4 -cellprob_threshold: 0 -clip_limit: 0 ``` Check `qc/{sample}_projection.png` first when cells look wrong: it is what Cellpose saw, nuclear in @@ -287,7 +291,7 @@ a later run deleted ("projection removed by an earlier run"). Rerun those sample ### GPU segmentation -`use_gpu: true` gives each Cellpose and InstanSeg patch task one GPU. +`use_gpu: true` gives each Cellpose and InstanSeg patch task, and each Nimbus and VirTues task, one GPU. With `-profile …,slurm,mdc` that is an A40 (`--gres=gpu:a40:1`): every A40 node has Ceph, and the sopa image cannot run on the V100s. At most 16 patches per method run at once. Cellpose tasks get 1 CPU and 8 GB on `size_tiny` and `size_small`, else 2 CPUs and 16 GB; InstanSeg tasks keep their @@ -305,6 +309,56 @@ a queue wait: nextflow run /path/to/histo -profile laptop -stub -params-file params.yml ``` +### Nimbus + +`use_nimbus: true` scores every marker in every cell, per segmentation method. Output is in +[output.md](https://github.com/CosciaLab/histo/blob/dev/docs/output.md#nimbus-scores). + +- `pixel_size` is required, in µm per pixel. Nimbus rescales the image with it. +- `segment_cells` is required: Nimbus was trained on whole cells. +- Markers come from the marker sheet (`marker` role). `nimbus_channels` overrides them, and is + required for a stitched image with no sheet. +- Use `use_gpu`. CPU gives near-identical scores but a whole slide can take days, so it only warns. +- Test-time augmentation is always on, with the same setting on CPU and GPU. It costs several forward + passes per window. On exemplar-002, CPU and GPU scores differed by 5e-4 on average and 0.11 at most, + with the same share of positive cells per marker. Cellpose ran on CPU too, so part of that is from + slightly different cell outlines. NIMBUS took ~12 min per core on CPU against ~1 min on an A40. +- Tiling can shift scores: at 0.65 µm/px a tiled run differed from a whole-image run by up to 0.41 + (mean 0.011) on a test crop. See [decisions](https://github.com/CosciaLab/histo/blob/dev/docs/decisions.md#learned-features). +- Each channel is divided by its 0.999 quantile within one store: per core on a TMA, per image + otherwise. This keeps differences between patients' cores. In a core with no positive cells, noise + is stretched to [0, 1] and can score as signal. +- NIMBUS has its own cap of 16 tasks at once, separate from the segmentation patches. + +### VirTues + +`use_virtues: true` embeds every cell, every 128 µm tissue square and each core or slide, per +segmentation method. Output is in +[output.md](https://github.com/CosciaLab/histo/blob/dev/docs/output.md#virtues-embeddings). + +- Required, or the run stops at startup: `use_gpu`, `use_preprocessing`, `use_tissue_segmentation`, + `segment_cells` and `pixel_size`. With `use_gpu`, segmentation runs on the GPU too. +- Add a `uniprot_id` column to the marker sheet. A channel is embedded if and only if its row has + one, e.g. `P08246`; an isoform takes a suffix (`P08575-8`). IDs must be unique and the format is + checked. An ID missing from the bundled human Swiss-Prot sequences fails the task, naming it. + `tests/stub_data/markers_virtues.csv` is an example. +- DNA stains are not embedded: a `dna` row with an ID stops the run. +- Intensities are scaled with statistics per slide over tissue pixels, written to + `learned_features/{slide}_virtues_stats.json`. `virtues_stats` (advanced) takes one such file and + applies it to every slide, e.g. to freeze a rerun or scale a cohort alike; no statistics file is + then written. It must cover every embedded marker with the same `uniprot_id`, and is an error + without `use_virtues`. +- "standard deviation is zero (constant marker)" stops the run when at least 99% of a marker's tissue + pixels are 0, so its 0.99 cap is 0. Usually backsub removed the signal: check that marker's + `exposure` and `background`. Otherwise leave its `uniprot_id` empty. +- One `VIRTUES` task per store, one GPU. FlashAttention 2 needs an Ampere or newer GPU: `mdc` asks + for an A40; elsewhere, request one in your config. On a V100 the task fails in the model. +- Memory does not grow with image area; per-cell results take about 2 GB per million cells per + method. An exemplar-002 core (22 markers, A40): about 1 min, 3.5 GB peak. +- A core where tissue segmentation found no tissue still gets its cells embedded, with a warning; + a slide with no tissue at all stops with a message naming it. +- The weights (`sp32`) are CC BY-NC 4.0. + ### Fetching images On a well-connected Linux machine: @@ -344,6 +398,20 @@ ls "$NXF_SINGULARITY_CACHEDIR" rsync -av --ignore-existing ~/histo-download/singularity-images/ "$NXF_SINGULARITY_CACHEDIR/" ``` +Our own images (`docker.io/josenimo/sopa:2.3.0-1`, `docker.io/josenimo/nimbus:0.0.5`, +`docker.io/josenimo/virtues:d2c25e1-2`) are staged the same way. The Nimbus image is needed for +`use_nimbus` and the VirTues image for `use_virtues`; each has its weights inside. + +To build one SIF yourself, from a registry or a `docker save` tar, submit +`tools/build_sif.sbatch` after sourcing the histo `setup.sh`. It builds straight into +`$NXF_SINGULARITY_CACHEDIR` under the name Nextflow looks for, renames the file only once it is +verified, and refuses to replace an image already there. The log goes to the cache's `logs/` +(`--help` for options, including building elsewhere): + +```bash +sbatch tools/build_sif.sbatch docker.io/josenimo/nimbus:0.0.5 +``` + `--ignore-existing` rather than plain `rsync` is deliberate: an image already in the cache is one a colleague may have a job attached to right now, and replacing it mid-run is how you break someone else's week. diff --git a/modules/local/aggregate/main.nf b/modules/local/aggregate/main.nf index 3c03ea1..9655c60 100644 --- a/modules/local/aggregate/main.nf +++ b/modules/local/aggregate/main.nf @@ -3,7 +3,7 @@ process AGGREGATE { tag "${meta.sample}:${method}" conda "${moduleDir}/environment.yml" - container "docker.io/josenimo/sopa:2.3.0" + container "docker.io/josenimo/sopa:2.3.0-1" input: // sdata_path is only read; specs are this method's spec maps. shapes: {method}_cells.parquet, diff --git a/modules/local/link_compartments/main.nf b/modules/local/link_compartments/main.nf index 5ee04f6..680812f 100644 --- a/modules/local/link_compartments/main.nf +++ b/modules/local/link_compartments/main.nf @@ -3,7 +3,7 @@ process LINK_COMPARTMENTS { tag "${meta.sample}:${method}" conda "${moduleDir}/environment.yml" - container "docker.io/josenimo/sopa:2.3.0" + container "docker.io/josenimo/sopa:2.3.0-1" input: // one method's resolved cells and nuclei from RESOLVE diff --git a/modules/local/nimbus/environment.yml b/modules/local/nimbus/environment.yml new file mode 100644 index 0000000..8ab0fdc --- /dev/null +++ b/modules/local/nimbus/environment.yml @@ -0,0 +1,8 @@ +channels: + - conda-forge + - bioconda +dependencies: + - python=3.12 + - pip + - pip: + - Nimbus-Inference==0.0.5 diff --git a/modules/local/nimbus/main.nf b/modules/local/nimbus/main.nf new file mode 100644 index 0000000..6f2c2c9 --- /dev/null +++ b/modules/local/nimbus/main.nf @@ -0,0 +1,51 @@ +process NIMBUS { + label "process_medium" + label "process_long" + tag "${meta.sample}:${method}:nimbus" + + conda "${moduleDir}/environment.yml" + // Weights are baked into the image: no download at run time, and the cluster may be offline. + container "docker.io/josenimo/nimbus:0.0.5" + + input: + // sdata_path is only read; spec is a map from featureSpecs (modules/local/utils.nf). + tuple val(meta), path(sdata_path), val(method), val(spec) + + output: + tuple val(meta), val(method), val(spec), path("${method}_nimbus.h5ad"), path("${method}_nimbus.json") + path "versions.yml" + + script: + // use_gpu: fail here rather than let the backend fall back to CPU without a word. + def gpu_check = task.accelerator ? """python -c "import torch; torch.ones(1, device='cuda').sum().item()" || { echo 'use_gpu: CUDA is not usable in this task' >&2; exit 1; }""" : "" + // A flag, not a spec field: task.accelerator is the only source, so config and tool cannot disagree. + def device = task.accelerator ? "cuda" : "cpu" + """ + ${gpu_check} + nimbus_cells.py \\ + --sdata ${sdata_path} \\ + --method ${method} \\ + --channels '${spec.channels.join(',')}' \\ + --pixel-size ${spec.pixel_size} \\ + --device ${device} \\ + --output ${method}_nimbus.h5ad \\ + --provenance ${method}_nimbus.json + + cat <<-END_VERSIONS > versions.yml + "${task.process}": + nimbus-inference: \$(python -c "import importlib.metadata as m; print(m.version('nimbus-inference'))") + torch: \$(python -c "import torch; print(torch.__version__)") + END_VERSIONS + """ + + stub: + """ + touch ${method}_nimbus.h5ad ${method}_nimbus.json + + cat <<-END_VERSIONS > versions.yml + "${task.process}": + nimbus-inference: stub + torch: stub + END_VERSIONS + """ +} diff --git a/modules/local/nimbus/meta.yml b/modules/local/nimbus/meta.yml new file mode 100644 index 0000000..120c590 --- /dev/null +++ b/modules/local/nimbus/meta.yml @@ -0,0 +1,65 @@ +name: "nimbus" +description: Score each marker channel per cell with the Nimbus model, for the cells of one segmentation method; reads the store, writes an AnnData table and a provenance file. +keywords: + - nimbus + - marker + - spatialdata + - imaging +tools: + - "nimbus": + description: "Pre-trained deep learning model for marker activity classification in multiplexed images." + homepage: "https://github.com/angelolab/Nimbus-Inference" + documentation: "https://github.com/angelolab/Nimbus-Inference/blob/main/README.md" + tool_dev_url: "https://github.com/angelolab/Nimbus-Inference" + licence: + - "MIT" + identifier: "" +input: + - - meta: + type: map + description: | + Groovy Map containing sample information + e.g. [ id:'sample1', sample:'sample1' ] + - sdata_path: + type: directory + description: SpatialData Zarr store with the cells of the method; only read + pattern: "*.zarr" + - method: + type: string + description: Segmentation method whose {method}_cells and {method}_table are scored + - spec: + type: map + description: | + One feature spec from featureSpecs (modules/local/utils.nf) + e.g. [ name:'nimbus', model:'nimbus', channels:[...], pixel_size:0.5, gpu:false ] +output: + # main.nf declares no emit names: outputs are positional, in this order. + tables: + - - meta: + type: map + description: | + Groovy Map containing sample information + e.g. [ id:'sample1', sample:'sample1' ] + - method: + type: string + description: Segmentation method, passed through + - spec: + type: map + description: The feature spec, passed through + - "${method}_nimbus.h5ad": + type: file + description: Per-cell marker scores, one row per row of {method}_table + pattern: "*_nimbus.h5ad" + - "${method}_nimbus.json": + type: file + description: Provenance of the run + pattern: "*_nimbus.json" + versions: + - versions.yml: + type: file + description: File containing software versions + pattern: "versions.yml" +authors: + - "@josenimo" +maintainers: + - "@josenimo" diff --git a/modules/local/resolve/main.nf b/modules/local/resolve/main.nf index a27d309..c8a4a85 100644 --- a/modules/local/resolve/main.nf +++ b/modules/local/resolve/main.nf @@ -3,7 +3,7 @@ process RESOLVE { tag "${meta.sample}:${spec.name}" conda "${moduleDir}/environment.yml" - container "docker.io/josenimo/sopa:2.3.0" + container "docker.io/josenimo/sopa:2.3.0-1" input: // sdata_path is only read; parquets are one spec's patches, staged as 0.parquet, 1.parquet, ... diff --git a/modules/local/segment_patch/main.nf b/modules/local/segment_patch/main.nf index 3b183f9..45dd4fe 100644 --- a/modules/local/segment_patch/main.nf +++ b/modules/local/segment_patch/main.nf @@ -4,7 +4,7 @@ process SEGMENT_PATCH { conda "${moduleDir}/environment.yml" // Weights are baked into the image: no download at run time, and the cluster may be offline. - container "docker.io/josenimo/sopa:2.3.0" + container "docker.io/josenimo/sopa:2.3.0-1" input: // sdata_path is only read; spec is a map from segmentationSpecs (modules/local/utils.nf). diff --git a/modules/local/utils.nf b/modules/local/utils.nf index 56ef3c9..357459d 100644 --- a/modules/local/utils.nf +++ b/modules/local/utils.nf @@ -120,7 +120,7 @@ def segmentationSpecs(Map args) { channels: getChannels(args.instanseg_channels, true), method_kwargs: [ model_type: args.instanseg_model_type, - pixel_size: toNumber('instanseg_pixel_size', args.instanseg_pixel_size), + pixel_size: pixelSize(args), target: target, ].findAll { _k, v -> v != null }, method_kwargs_extra: args.instanseg_kwargs, @@ -150,6 +150,17 @@ def getChannels(channels, Boolean allow_null = false) { return channels.toString().split(/[ ,|]+/).findAll { it } } +// µm per pixel from pixel_size, or its deprecated alias instanseg_pixel_size; params cannot be +// reassigned, so every read goes through here. +def pixelSize(Map args) { + def a = toNumber('pixel_size', args.pixel_size) + def b = toNumber('instanseg_pixel_size', args.instanseg_pixel_size) + if (a != null && b != null && a != b) { + error("pixel_size (${a}) and the deprecated instanseg_pixel_size (${b}) differ; set only pixel_size.") + } + return a != null ? a : b +} + // Command-line values arrive as Strings and params cannot be reassigned, so numbers are parsed // where used: in arithmetic "3000" * 0.65 is string repetition, and in kwargs JSON a str for sopa. def toNumber(String name, value) { @@ -172,7 +183,7 @@ def toNumber(String name, value) { // to ~4 channels, then ~0.25 GB per channel (test7, dropbox run 00009); ~1.2x headroom. def instansegMemoryGB(int n_channels, patch_width, pixel_size) { patch_width = toNumber('patch_width_pixel', patch_width) - pixel_size = toNumber('instanseg_pixel_size', pixel_size) + pixel_size = toNumber('pixel_size', pixel_size) def megapixels = Math.pow(patch_width * pixel_size / 0.5, 2) / 1e6 return Math.ceil(2 + megapixels * instansegGBPerMegapixel(n_channels)) as int } @@ -183,7 +194,7 @@ def instansegGBPerMegapixel(int n_channels) { // Largest patch_width_pixel, in steps of 100, whose request stays within gigabytes. def instansegMaxPatchWidth(int n_channels, gigabytes, pixel_size) { - pixel_size = toNumber('instanseg_pixel_size', pixel_size) + pixel_size = toNumber('pixel_size', pixel_size) def megapixels = (gigabytes - 2) / instansegGBPerMegapixel(n_channels) return ((Math.sqrt(megapixels * 1e6) * 0.5 / pixel_size / 100) as int) * 100 } @@ -200,6 +211,46 @@ def defaultInstansegChannels(List rows, String target) { return rows.findAll { it.channel_role in roles }.collect { it.marker_name } } +// Marker names Nimbus scores when nimbus_channels is unset: the marker channels only. +def defaultNimbusChannels(List rows) { + return rows.findAll { it.channel_role == 'marker' }.collect { it.marker_name } +} + +// [marker_name, uniprot_id] of each row VirTues embeds, in sheet order. +def virtuesChannels(List rows) { + return rows.findAll { it.uniprot_id }.collect { [it.marker_name, it.uniprot_id] } +} + +// Marker names VirTues leaves out: the rows without a uniprot_id. +def virtuesUnembedded(List rows) { + return rows.findAll { !it.uniprot_id }.collect { it.marker_name } +} + +// One spec per learned-features model. +def featureSpecs(Map args) { + def specs = [] + if (args.use_nimbus) { + specs << [ + name: 'nimbus', + model: 'nimbus', + channels: getChannels(args.nimbus_channels, true), + pixel_size: pixelSize(args), + gpu: args.use_gpu ? true : false, + ] + } + if (args.use_virtues) { + specs << [ + name: 'virtues', + model: 'virtues', + channels: null, + pixel_size: pixelSize(args), + stats: args.virtues_stats ?: null, + gpu: args.use_gpu ? true : false, + ] + } + return specs +} + def argsCLI(String group = null, Map args = null) { args = args ?: params diff --git a/modules/local/virtues/environment.yml b/modules/local/virtues/environment.yml new file mode 100644 index 0000000..1c56c38 --- /dev/null +++ b/modules/local/virtues/environment.yml @@ -0,0 +1,8 @@ +channels: + - conda-forge +dependencies: + - python=3.12 + - pip + # Built from tools/containers/virtues; torch, flash-attn and ESM-2 weights are in the image, not conda. + - pip: + - torch==2.5.1 diff --git a/modules/local/virtues/main.nf b/modules/local/virtues/main.nf new file mode 100644 index 0000000..2857c92 --- /dev/null +++ b/modules/local/virtues/main.nf @@ -0,0 +1,56 @@ +process VIRTUES { + label "process_medium" + label "process_long" + tag "${meta.sample}:virtues" + + conda "${moduleDir}/environment.yml" + // Weights, ESM-2 and UniProt sequences are baked into the image: no download at run time. + container "docker.io/josenimo/virtues:d2c25e1-2" + + input: + // sdata_path is only read; spec.channels is [name, uniprot_id] pairs and spec.unembedded names, both resolved upstream. + tuple val(meta), path(sdata_path), val(methods), val(spec), path(stats) + + output: + tuple val(meta), path("*.{h5ad,parquet}") + tuple val(meta), path("virtues.json") + path "versions.yml" + + script: + // FlashAttention has no CPU path: fail here with a clear message instead of deep in the tool. + def gpu_check = task.accelerator ? """python -c "import torch; torch.ones(1, device='cuda').sum().item()" || { echo 'use_virtues: CUDA is not usable in this task' >&2; exit 1; }""" : """echo 'use_virtues: VIRTUES needs a GPU' >&2; exit 1""" + def channels = spec.channels.collect { "${it[0]}:${it[1]}" }.join(',') + """ + ${gpu_check} + virtues_cells.py \\ + --sdata ${sdata_path} \\ + --methods '${methods.join(',')}' \\ + --channels '${channels}' \\ + --unembedded '${spec.unembedded.join(',')}' \\ + --stats ${stats} \\ + --pixel-size ${spec.pixel_size} \\ + --device cuda \\ + --outdir . + + cat <<-END_VERSIONS > versions.yml + "${task.process}": + virtues: \$VIRTUES_COMMIT + torch: \$(python -c "import torch; print(torch.__version__)") + flash_attn: \$(python -c "import flash_attn; print(flash_attn.__version__)") + END_VERSIONS + """ + + stub: + def touches = methods.collect { "${it}_virtues.h5ad" }.join(' ') + """ + echo "${task.accelerator ? 'gpu' : 'none'}" > .accelerator + touch ${touches} virtues_niches.parquet virtues_niches_table.h5ad virtues_tissue.h5ad virtues.json + + cat <<-END_VERSIONS > versions.yml + "${task.process}": + virtues: stub + torch: stub + flash_attn: stub + END_VERSIONS + """ +} diff --git a/modules/local/virtues/meta.yml b/modules/local/virtues/meta.yml new file mode 100644 index 0000000..5c558e1 --- /dev/null +++ b/modules/local/virtues/meta.yml @@ -0,0 +1,62 @@ +name: "virtues" +description: Embed the cells, tiles, tissue and niches of one store with the VirTues model. +keywords: + - virtues + - spatialdata + - imaging +tools: + - "virtues": + description: "VirTues" + homepage: "https://github.com/bunnelab/virtues" + documentation: "https://github.com/bunnelab/virtues" + tool_dev_url: "https://github.com/bunnelab/virtues" + licence: + - "MIT" + identifier: "" +input: + - - meta: + type: map + description: | + Groovy Map containing sample information + e.g. [ id:'sample1', sample:'sample1' ] + - sdata_path: + type: directory + description: SpatialData Zarr store; only read + pattern: "*.zarr" + - methods: + type: list + description: Segmentation methods whose cells are embedded + - spec: + type: map + description: Resolved spec with channels, unembedded and pixel_size + - stats: + type: file + description: Slide statistics from VIRTUES_STATS + pattern: "*_virtues_stats.json" +output: + # main.nf declares no emit names: outputs are positional, in this order. + features: + - - meta: + type: map + description: Groovy Map containing sample information + - "*.{h5ad,parquet}": + type: file + description: Per-method cell tables, tissue table, niche shapes and table + pattern: "*.{h5ad,parquet}" + provenance: + - - meta: + type: map + description: Groovy Map containing sample information + - virtues.json: + type: file + description: Provenance of the run + pattern: "virtues.json" + versions: + - versions.yml: + type: file + description: File containing software versions + pattern: "versions.yml" +authors: + - "@josenimo" +maintainers: + - "@josenimo" diff --git a/modules/local/virtues_histogram/environment.yml b/modules/local/virtues_histogram/environment.yml new file mode 100644 index 0000000..8f249e3 --- /dev/null +++ b/modules/local/virtues_histogram/environment.yml @@ -0,0 +1,9 @@ +channels: + - conda-forge + - bioconda +dependencies: + - python=3.12 + - pip + - pip: + - sopa[cellpose,instanseg]==2.3.0 + - cellpose==4.2.1.1 diff --git a/modules/local/virtues_histogram/main.nf b/modules/local/virtues_histogram/main.nf new file mode 100644 index 0000000..f024d9a --- /dev/null +++ b/modules/local/virtues_histogram/main.nf @@ -0,0 +1,42 @@ +process VIRTUES_HISTOGRAM { + label "process_low" + tag "${meta.sample}:virtues_histogram" + + conda "${moduleDir}/environment.yml" + // virtues_stats.py imports no torch, so the sopa image is enough. + container "docker.io/josenimo/sopa:2.3.0-1" + + input: + // sdata_path is only read; spec.channels is a list of [name, uniprot_id] pairs, resolved upstream. + tuple val(meta), path(sdata_path), val(spec) + + output: + tuple val(meta), path("${meta.sample}_virtues_hist.npz") + path "versions.yml" + + script: + def channels = spec.channels.collect { "${it[0]}:${it[1]}" }.join(',') + """ + virtues_stats.py histogram \\ + --sdata ${sdata_path} \\ + --channels '${channels}' \\ + --pixel-size ${spec.pixel_size} \\ + --output ${meta.sample}_virtues_hist.npz + + cat <<-END_VERSIONS > versions.yml + "${task.process}": + sopa: \$(sopa --version) + END_VERSIONS + """ + + stub: + """ + echo "${task.accelerator ? 'gpu' : 'none'}" > .accelerator + touch ${meta.sample}_virtues_hist.npz + + cat <<-END_VERSIONS > versions.yml + "${task.process}": + sopa: stub + END_VERSIONS + """ +} diff --git a/modules/local/virtues_histogram/meta.yml b/modules/local/virtues_histogram/meta.yml new file mode 100644 index 0000000..013e81c --- /dev/null +++ b/modules/local/virtues_histogram/meta.yml @@ -0,0 +1,47 @@ +name: "virtues_histogram" +description: Per-core tissue intensity histograms of one store, the input of the slide statistics. +keywords: + - virtues + - spatialdata + - imaging +tools: + - "virtues": + description: "VirTues" + homepage: "https://github.com/bunnelab/virtues" + documentation: "https://github.com/bunnelab/virtues" + tool_dev_url: "https://github.com/bunnelab/virtues" + licence: + - "MIT" + identifier: "" +input: + - - meta: + type: map + description: | + Groovy Map containing sample information + e.g. [ id:'sample1', sample:'sample1' ] + - sdata_path: + type: directory + description: SpatialData Zarr store; only read + pattern: "*.zarr" + - spec: + type: map + description: Resolved spec with channels ([name, uniprot_id] pairs) and pixel_size +output: + # main.nf declares no emit names: outputs are positional, in this order. + hist: + - - meta: + type: map + description: Groovy Map containing sample information + - "${meta.sample}_virtues_hist.npz": + type: file + description: Histograms per channel, 65536 bins + pattern: "*_virtues_hist.npz" + versions: + - versions.yml: + type: file + description: File containing software versions + pattern: "versions.yml" +authors: + - "@josenimo" +maintainers: + - "@josenimo" diff --git a/modules/local/virtues_stats/environment.yml b/modules/local/virtues_stats/environment.yml new file mode 100644 index 0000000..8f249e3 --- /dev/null +++ b/modules/local/virtues_stats/environment.yml @@ -0,0 +1,9 @@ +channels: + - conda-forge + - bioconda +dependencies: + - python=3.12 + - pip + - pip: + - sopa[cellpose,instanseg]==2.3.0 + - cellpose==4.2.1.1 diff --git a/modules/local/virtues_stats/main.nf b/modules/local/virtues_stats/main.nf new file mode 100644 index 0000000..c216a6d --- /dev/null +++ b/modules/local/virtues_stats/main.nf @@ -0,0 +1,41 @@ +process VIRTUES_STATS { + label "process_single" + tag "${slide}:virtues_stats" + + conda "${moduleDir}/environment.yml" + // virtues_stats.py imports no torch, so the sopa image is enough. + container "docker.io/josenimo/sopa:2.3.0-1" + + input: + // hists are the per-core histograms of one slide; the statistics are slide-wide. + tuple val(slide), path(hists), val(spec) + + output: + tuple val(slide), path("${slide}_virtues_stats.json") + path "versions.yml" + + script: + """ + virtues_stats.py combine \\ + --slide ${slide} \\ + --pixel-size ${spec.pixel_size} \\ + --output ${slide}_virtues_stats.json \\ + ${hists} + + cat <<-END_VERSIONS > versions.yml + "${task.process}": + sopa: \$(sopa --version) + END_VERSIONS + """ + + stub: + """ + echo "${task.accelerator ? 'gpu' : 'none'}" > .accelerator + touch ${slide}_virtues_stats.json + + cat <<-END_VERSIONS > versions.yml + "${task.process}": + sopa: stub + END_VERSIONS + """ +} diff --git a/modules/local/virtues_stats/meta.yml b/modules/local/virtues_stats/meta.yml new file mode 100644 index 0000000..3d07d4e --- /dev/null +++ b/modules/local/virtues_stats/meta.yml @@ -0,0 +1,45 @@ +name: "virtues_stats" +description: Combine the histograms of one slide into the VirTues normalisation statistics. +keywords: + - virtues + - spatialdata + - imaging +tools: + - "virtues": + description: "VirTues" + homepage: "https://github.com/bunnelab/virtues" + documentation: "https://github.com/bunnelab/virtues" + tool_dev_url: "https://github.com/bunnelab/virtues" + licence: + - "MIT" + identifier: "" +input: + - - slide: + type: string + description: Slide name + - hists: + type: file + description: Per-core histograms of the slide + pattern: "*_virtues_hist.npz" + - spec: + type: map + description: Resolved spec with pixel_size +output: + # main.nf declares no emit names: outputs are positional, in this order. + stats: + - - slide: + type: string + description: Slide name + - "${slide}_virtues_stats.json": + type: file + description: Slide statistics (quantile and SD per channel) + pattern: "*_virtues_stats.json" + versions: + - versions.yml: + type: file + description: File containing software versions + pattern: "versions.yml" +authors: + - "@josenimo" +maintainers: + - "@josenimo" diff --git a/modules/local/write_features/environment.yml b/modules/local/write_features/environment.yml new file mode 100644 index 0000000..8f249e3 --- /dev/null +++ b/modules/local/write_features/environment.yml @@ -0,0 +1,9 @@ +channels: + - conda-forge + - bioconda +dependencies: + - python=3.12 + - pip + - pip: + - sopa[cellpose,instanseg]==2.3.0 + - cellpose==4.2.1.1 diff --git a/modules/local/write_features/main.nf b/modules/local/write_features/main.nf new file mode 100644 index 0000000..ccc8daf --- /dev/null +++ b/modules/local/write_features/main.nf @@ -0,0 +1,42 @@ +process WRITE_FEATURES { + label "process_low" + tag "${meta.sample}" + + conda "${moduleDir}/environment.yml" + container "docker.io/josenimo/sopa:2.3.0-1" + + input: + // Writes into the store after WRITE_SEGMENTATIONS; never in parallel with it (they race on its metadata). + tuple val(meta), path(sdata_path), path(features) + + output: + tuple val(meta), path(sdata_path) + path "versions.yml" + + script: + // Split by suffix; --shapes is left out when no niche was kept. + def files = features instanceof List ? features : [features] + def tables = files.findAll { it.name.endsWith('.h5ad') }.join(' ') + def shapes = files.findAll { it.name.endsWith('.parquet') }.join(' ') + """ + write_features.py \\ + --sdata ${sdata_path} \\ + --tables ${tables}${shapes ? " \\\n --shapes ${shapes}" : ''} + + cat <<-END_VERSIONS > versions.yml + "${task.process}": + sopa: \$(sopa --version) + END_VERSIONS + """ + + stub: + // Lists what was staged and from where, as WRITE_SEGMENTATIONS' stub does. + """ + for f in ${features instanceof List ? features.join(' ') : features}; do echo "\$f \$(readlink \$f)"; done > staged_inputs.txt + + cat <<-END_VERSIONS > versions.yml + "${task.process}": + sopa: stub + END_VERSIONS + """ +} diff --git a/modules/local/write_features/meta.yml b/modules/local/write_features/meta.yml new file mode 100644 index 0000000..be78319 --- /dev/null +++ b/modules/local/write_features/meta.yml @@ -0,0 +1,52 @@ +name: "write_features" +description: Write the learned-feature tables of one sample into its SpatialData store, in place, after checking their rows match the method table. +keywords: + - spatialdata + - zarr + - features + - write +tools: + - "sopa": + description: "Technology-invariant pipeline for image-based spatial omics." + homepage: "https://prism-oncology.github.io/sopa" + documentation: "https://prism-oncology.github.io/sopa" + tool_dev_url: "https://github.com/prism-oncology/sopa" + doi: 10.1038/s41467-024-48981-z + licence: + - "BSD-3-Clause" + identifier: "" +input: + - - meta: + type: map + description: | + Groovy Map containing sample information + e.g. [ id:'sample1', sample:'sample1' ] + - sdata_path: + type: directory + description: SpatialData Zarr store, modified in place + pattern: "*.zarr" + - features: + type: file + description: Tables (*.h5ad) and shapes (*.parquet) to write; the element name is the file stem + pattern: "*.{h5ad,parquet}" +output: + # main.nf declares no emit names: outputs are positional, in this order. + sdata: + - - meta: + type: map + description: | + Groovy Map containing sample information + e.g. [ id:'sample1', sample:'sample1' ] + - sdata_path: + type: directory + description: The same store, with the feature tables written + pattern: "*.zarr" + versions: + - versions.yml: + type: file + description: File containing software versions + pattern: "versions.yml" +authors: + - "@josenimo" +maintainers: + - "@josenimo" diff --git a/modules/local/write_segmentations/main.nf b/modules/local/write_segmentations/main.nf index c16e0b4..9c0550c 100644 --- a/modules/local/write_segmentations/main.nf +++ b/modules/local/write_segmentations/main.nf @@ -3,7 +3,7 @@ process WRITE_SEGMENTATIONS { tag "${meta.sample}" conda "${moduleDir}/environment.yml" - container "docker.io/josenimo/sopa:2.3.0" + container "docker.io/josenimo/sopa:2.3.0-1" input: // The only task that writes shapes and tables into the store (parallel writers race on its metadata). diff --git a/nextflow.config b/nextflow.config index 27173ce..a1bb172 100644 --- a/nextflow.config +++ b/nextflow.config @@ -34,6 +34,9 @@ params { // Ashlar -c and Coreograph --channel must point at a dna channel; true runs anyway, with a warning. skip_reference_dna_check = false + // µm per pixel; instanseg_pixel_size is its deprecated alias (pixelSize in utils.nf). + pixel_size = null + // Patchify options. Not sopa's 5000: InstanSeg's memory grows with patch area (instansegMemoryGB). patch_width_pixel = 2000 patch_overlap_pixel = 100 @@ -57,7 +60,7 @@ params { projection_method = 'max' projection_low_percentile = 1 projection_high_percentile = 99.9 - projection_sigma = 1 + projection_sigma = 0 // Segmentation targets; each enabled method segments each target segment_cells = true @@ -68,7 +71,7 @@ params { cellpose_channels = null flow_threshold = null cellprob_threshold = null - pretrained_model = null + pretrained_model = 'cpsam_v2' cellpose_kwargs = null // InstanSeg segmentation options @@ -78,6 +81,12 @@ params { instanseg_channels = null instanseg_kwargs = null + // Learned features + use_nimbus = false + nimbus_channels = null + use_virtues = false + virtues_stats = null + // QC report options. Other QC tuning goes through ext.args in conf/modules.config, not params. use_qc = true // Clustering and image crops cost minutes; the metrics alone cost seconds. @@ -318,7 +327,7 @@ manifest { mainScript = 'main.nf' defaultBranch = 'main' nextflowVersion = '!>=25.10.4' - version = '2.0.0' + version = '3.2.0' } // Nextflow plugins diff --git a/nextflow_schema.json b/nextflow_schema.json index 6e1b802..6386275 100644 --- a/nextflow_schema.json +++ b/nextflow_schema.json @@ -12,6 +12,11 @@ "description": "Define where the pipeline should find input data and save output data.", "required": ["input", "outdir"], "properties": { + "pixel_size": { + "type": "number", + "exclusiveMinimum": 0, + "description": "µm per pixel of the image (OME PhysicalSizeX). Required by InstanSeg and Nimbus." + }, "input": { "type": "string", "format": "file-path", @@ -322,16 +327,16 @@ "image_preprocessing": { "title": "Image preprocessing", "type": "object", - "description": "Image preprocessing applied before segmentation (Cellpose, InstanSeg). Unset: sopa's per-method defaults (they differ for InstanSeg).", + "description": "Image preprocessing applied before segmentation (Cellpose, InstanSeg). Unset: none for either method.", "default": "", "properties": { "gaussian_sigma": { "type": "number", - "description": "Parameter for scipy gaussian_filter (applied before running the segmentation method)" + "description": "Parameter for scipy gaussian_filter (applied before running the segmentation method). Unset: 0, no smoothing." }, "clip_limit": { "type": "number", - "description": "Parameter for skimage.exposure.equalize_adapthist (applied before running the segmentation method)" + "description": "Parameter for skimage.exposure.equalize_adapthist (applied before running the segmentation method). Unset: 0, no CLAHE." }, "clahe_kernel_size": { "type": "number", @@ -378,7 +383,7 @@ }, "projection_sigma": { "type": "number", - "default": 1.0, + "default": 0.0, "minimum": 0, "description": "Gaussian smoothing in pixels applied to each marker before combining; 0 for none." } @@ -422,15 +427,16 @@ }, "flow_threshold": { "type": "number", - "description": "Cellpose `flow_threshold` parameter" + "description": "Cellpose `flow_threshold` parameter. Unset: 0.6, from the segmentation benchmark." }, "cellprob_threshold": { "type": "number", - "description": "Cellpose `cellprob_threshold` parameter" + "description": "Cellpose `cellprob_threshold` parameter. Unset: -1, from the segmentation benchmark." }, "pretrained_model": { "type": "string", - "description": "Cellpose `pretrained_model` parameter" + "default": "cpsam_v2", + "description": "Cellpose weights: a name baked into the image (`cpsam_v2`, `cpsam`) or a path" }, "cellpose_kwargs": { "type": "string", @@ -448,7 +454,7 @@ "use_instanseg": { "type": "boolean", "description": "Segment with InstanSeg. May be combined with use_cellpose.", - "help_text": "**Requires:** `instanseg_pixel_size`, `instanseg_channels` when `use_preprocessing` is false, and `use_cellpose` or `use_instanseg` unless `preprocessing_only` is true. **Conflicts:** `use_gpu` on more than 10 channels." + "help_text": "**Requires:** `pixel_size`, `instanseg_channels` when `use_preprocessing` is false, and `use_cellpose` or `use_instanseg` unless `preprocessing_only` is true. **Conflicts:** `use_gpu` on more than 10 channels." }, "instanseg_model_type": { "type": "string", @@ -456,8 +462,9 @@ }, "instanseg_pixel_size": { "type": "number", - "description": "Image resolution in microns per pixel. Required: without it InstanSeg does not rescale and may find no cells", - "help_text": "**Ignored unless:** `use_instanseg` is true." + "description": "Deprecated: use pixel_size", + "help_text": "**Conflicts:** `pixel_size` with a different value.", + "hidden": true }, "instanseg_channels": { "type": ["string", "integer"], @@ -471,6 +478,39 @@ }, "fa_icon": "fas fa-tools" }, + "learned_features": { + "title": "Learned features", + "type": "object", + "description": "Parameters related to learned-features models, which score each segmented cell", + "default": "", + "properties": { + "use_nimbus": { + "type": "boolean", + "description": "Score per-cell marker positivity with Nimbus.", + "help_text": "**Requires:** `pixel_size`, `segment_cells`, and `nimbus_channels` when `use_preprocessing` is false." + }, + "nimbus_channels": { + "type": ["string", "integer"], + "description": "Channel(s) to score with Nimbus. Unset takes the `marker` channels from each sample's marker sheet. Required without a marker sheet (`use_preprocessing = false`). Use marker names, separated by space, comma or pipe characters.", + "help_text": "**Ignored unless:** `use_nimbus`." + }, + "use_virtues": { + "type": "boolean", + "description": "Embed each segmented cell with VirTues, a multiplex protein-marker foundation model.", + "help_text": "**Requires:** `use_gpu`, `use_preprocessing`, `use_tissue_segmentation`, `segment_cells`, `pixel_size`, and a `uniprot_id` on at least one marker-sheet row." + }, + "virtues_stats": { + "type": "string", + "format": "file-path", + "exists": true, + "pattern": "^\\S+\\.json$", + "hidden": true, + "description": "A `{slide}_virtues_stats.json` from an earlier run, applied to every slide instead of computing per-slide statistics.", + "help_text": "**Requires:** `use_virtues`." + } + }, + "fa_icon": "fas fa-brain" + }, "qc_report": { "title": "QC report", "type": "object", @@ -533,6 +573,9 @@ { "$ref": "#/$defs/instanseg" }, + { + "$ref": "#/$defs/learned_features" + }, { "$ref": "#/$defs/qc_report" } diff --git a/pyproject.toml b/pyproject.toml index 037468f..93abbe5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -51,6 +51,10 @@ dev = [ # bin/coreograph_*.py run in the Coreograph image, which ships both. "scikit-image>=0.22", "matplotlib>=3.8", + # tools/segmentation_benchmark/prepare.py reads the ImageJ ROI zips of the Cross-platform masks. + "roifile>=2026.2.10", + # prepare.py reads the CODEX channel names from the dataset's Annotation Panel Table.xlsx. + "openpyxl>=3.1", ] [tool.pytest.ini_options] diff --git a/site/FIGURES.md b/site/FIGURES.md index ed866d5..c63321e 100644 --- a/site/FIGURES.md +++ b/site/FIGURES.md @@ -15,6 +15,7 @@ Paper figures are reused only under CC BY 4.0, checked on the publisher page. - modules/tiling: `images/modules/tiling.svg` — two overlapping patches and a resolved cell, drawn for this site - modules/linking: `images/modules/linking.svg` — a linked and an unlinked nucleus, drawn for this site +- benchmark: `images/benchmark/old-vs-new.png`, `images/benchmark/thresholds.png` — from the benchmark results, `scripts/site_figures.py` in the lab's Segmentation_Benchmark folder ## Slots diff --git a/site/benchmark.md b/site/benchmark.md new file mode 100644 index 0000000..f5359e1 --- /dev/null +++ b/site/benchmark.md @@ -0,0 +1,101 @@ +# Segmentation benchmark + +Cellpose-SAM segments a prepared image, and the preparation is set by parameters: smoothing, +contrast enhancement, which channels form the cell image, and two thresholds. Until v3.2 these were +sopa's defaults or our guesses, never checked against cells drawn by hand. This benchmark checked +them, and the Cellpose defaults now come from it. + +% source: docs/decisions.md#segmentation-benchmark + +## What we did + +We segmented images that experts had outlined by hand, under 475 settings, and scored each +setting against the outlines. + +- **Data.** Three annotated sets, none used to train the model except as noted: + - Cross-platform mIF ([Aleynick et al. 2023](https://www.synapse.org/Synapse:syn27624812)): + 119 Vectra and 10 CODEX crops from 12 tissues. It decides. + - TissueNet 1.1, test split [@doi:10.1038/s41587-021-01094-0]: 1324 tiles from 19 sources. + It decides too, with a caveat: its training split trained Cellpose-SAM. + - Tonsil mIF ([Zenodo](https://zenodo.org/records/22107836)): 10 crops, partly annotated, so a + check only. +- **Score.** A predicted cell counts as found when it overlaps a drawn one by at least half + (IoU 0.5). F1 balances cells found against cells invented; 1 is perfect. We report the mean F1 + over crops, for whole cells and for nuclei. +- **Model.** `cpsam_v2` at diameter 30, as the pipeline runs it. +- **Round 1, 168 settings: preprocessing.** Combining markers (max, mean), the low percentile + (1, 50), projection smoothing and Gaussian blur (σ 0, 1, 2), CLAHE (off, 0.2), and two + threshold pairs: sopa's and Cellpose's. +- **Round 2, 307 settings: thresholds and channels.** With round 1's best preprocessing, a grid + of 7 `flow_threshold` × 8 `cellprob_threshold` values; three cell-channel choices (all, without + autofluorescence, without nuclear markers too); and CLAHE 0.01, a value common in the + literature. + +% source: tools/segmentation_benchmark/README.md +% source: docs/decisions.md#segmentation-benchmark + +## What we found + +:::{figure} images/benchmark/old-vs-new.png +:alt: Bar chart of mean F1 with the old and the new defaults for cells and nuclei on three datasets; the new defaults are higher on all six. + +Mean F1 with sopa's defaults and with the new ones. Cells on Cross-platform improve on 128 of 129 +crops, by 0.20 on average. +::: + +- **Smoothing hurts.** Each of projection smoothing and Gaussian blur lowered F1, and together + more. Cellpose-SAM normalises each image itself and needs no help. +- **CLAHE hurts.** At 0.2 and at 0.01: it helped only at thresholds that find too few cells, + where a lower `cellprob_threshold` does better. +- **`flow_threshold` barely matters from 0.6 up.** Values from 0.6 to 2 scored within 0.01. +- **`cellprob_threshold` matters, and targets disagree.** Cells do best between -3 and 0. Nuclei + on Cross-platform want -1 or less, on TissueNet 0 or more. +- **Max and percentile 1**, the existing projection defaults, were already best. +- **Autofluorescence in the cell image costs a little** (0.012 F1 on Vectra), nuclear markers + less (0.004). The default grouping leaves both out. + +:::{figure} images/benchmark/thresholds.png +:alt: Four heatmaps of mean F1 over flow_threshold and cellprob_threshold, for cells and nuclei on Cross-platform and TissueNet; a solid box marks 0.6 and -1. + +Mean F1 for each threshold pair. Solid box: the chosen pair; dashed: each panel's own best. +::: + +% source: docs/decisions.md#segmentation-benchmark + +## Why these defaults + +The pipeline has one threshold pair for cells and nuclei. Before round 2 ran, we fixed the rule: +take the pair whose largest shortfall from each target's own best is smallest, over cells and +nuclei on Cross-platform and TissueNet. That pair is 0.6 and -1, within 0.065 of the best +everywhere; TissueNet nuclei pay the most. + +| Parameter | Old (sopa) | New | +| -------------------------------------------------------------------- | ---------- | --- | +| [`flow_threshold`](inputs/parameters-full.md#flow_threshold) | 2 | 0.6 | +| [`cellprob_threshold`](inputs/parameters-full.md#cellprob_threshold) | -6 | -1 | +| [`clip_limit`](inputs/parameters-full.md#clip_limit) (CLAHE) | 0.2 | 0 | +| [`gaussian_sigma`](inputs/parameters-full.md#gaussian_sigma) | 1 | 0 | +| [`projection_sigma`](inputs/parameters-full.md#projection_sigma) | 1 | 0 | + +To reproduce a run from before v3.2, set the old values and `pretrained_model: cpsam` in your +params file. InstanSeg is unaffected. + +% source: bin/segment_patch.py:24-48 +% source: nextflow.config:60-63 + +## Limits + +- **Percentiles per crop.** The benchmark rescaled each crop on its own; the pipeline rescales on + the whole slide. +- **One model, one metric.** `cpsam_v2` at diameter 30, F1 at IoU 0.5. +- **Nuclear smoothing** helped nuclei at Cellpose's old thresholds and was not tested at the new + ones. +- **Your tissue may differ.** Check the "Segmentation overlay" of the + [QC report](outputs/reports.md) on your first run. + +## Read more + +- [The benchmark code](https://github.com/CosciaLab/histo/tree/dev/tools/segmentation_benchmark), + to rerun it on your own annotated crops. +- [decisions.md](https://github.com/CosciaLab/histo/blob/dev/docs/decisions.md#segmentation-benchmark). +- [Cellpose](modules/cellpose.md) and [Channel projection](modules/projection.md). diff --git a/site/getting-started/background.md b/site/getting-started/background.md index 36d1881..44285df 100644 --- a/site/getting-started/background.md +++ b/site/getting-started/background.md @@ -132,7 +132,7 @@ table is what you analyse. See [Outputs](../outputs/outputs.md). ### Pixel size -- **InstanSeg needs the pixel size from you** (`instanseg_pixel_size`); it does not read it from +- **InstanSeg needs the pixel size from you** (`pixel_size`); it does not read it from the image. - **Finding TMA cores reads it from the image.** Without it, core detection stops and asks for manual settings. diff --git a/site/getting-started/introduction.md b/site/getting-started/introduction.md index d2be048..0ba3670 100644 --- a/site/getting-started/introduction.md +++ b/site/getting-started/introduction.md @@ -25,15 +25,15 @@ It does this in two halves: The two halves meet at a single stitched OME-TIFF per sample. If your images were already stitched elsewhere, you can start from the second half. -% source: README.md#what-this-is -% source: README.md#steps +% source: README.md#credits +% source: README.md#what-it-does % source: docs/decisions.md#architecture The preprocessing half comes from [nf-core/mcmicro](https://github.com/nf-core/mcmicro), the analysis half from [nf-core/sopa](https://github.com/nf-core/sopa). The pipeline follows nf-core conventions but is not an nf-core pipeline. -% source: README.md#what-this-is +% source: README.md#credits ## Who it is for @@ -42,7 +42,6 @@ not program. You describe your experiment in two small tables and a short settin pipeline does the rest, on a computing cluster, without supervision. Images from 5 GB to 100 GB have run the same way, because segmentation works patch by patch. -% source: README.md#what-this-is % source: docs/decisions.md#architecture % source: conf/sizes.config @@ -69,7 +68,7 @@ compute spatial statistics such as neighbourhoods. It stops at a table of measur the starting point for that analysis in tools such as [scanpy](https://scanpy.readthedocs.io) or [squidpy](https://squidpy.readthedocs.io). -% source: README.md#steps +% source: README.md#what-it-does ## mIF today, H&E planned diff --git a/site/getting-started/step-by-step.md b/site/getting-started/step-by-step.md index de041ab..4c985e7 100644 --- a/site/getting-started/step-by-step.md +++ b/site/getting-started/step-by-step.md @@ -112,7 +112,7 @@ input: /data/myproject/sheets/samplesheet.csv outdir: /data/myproject/results use_instanseg: true -instanseg_pixel_size: 0.65 +pixel_size: 0.65 ``` - `input`: the samplesheet from step 3. @@ -135,7 +135,7 @@ keeps going when you log out: ```bash cd /path/to/my/working/folder tmux new -s histo -nextflow run CosciaLab/histo -r v2.0.0 \ +nextflow run CosciaLab/histo -r v3.2.0 \ -profile singularity,size_small,slurm \ -params-file params.yml ``` @@ -143,7 +143,7 @@ nextflow run CosciaLab/histo -r v2.0.0 \ What each part means: - `nextflow run CosciaLab/histo`: run this pipeline. -- `-r v2.0.0`: this version of it, so a rerun next year gives the same result. +- `-r v3.2.0`: this version of it, so a rerun next year gives the same result. - `-profile singularity,size_small,slurm`: run the software in Singularity containers, ask for resources sized for images up to about 50 GB, and send each step to the cluster's queue. See [Profiles](usage-guide.md#profiles); at the MDC add `mdc`. diff --git a/site/getting-started/usage-guide.md b/site/getting-started/usage-guide.md index 48f28c0..024ed5a 100644 --- a/site/getting-started/usage-guide.md +++ b/site/getting-started/usage-guide.md @@ -7,7 +7,7 @@ sheets and settings is under [Inputs](../inputs/inputs.md). ## The command ```bash -nextflow run CosciaLab/histo -r v2.0.0 \ +nextflow run CosciaLab/histo -r v3.2.0 \ -profile singularity,size_small,slurm \ -params-file params.yml ``` @@ -93,7 +93,7 @@ mkdir -p "$TMPDIR" # Stops a download at launch of a config this pipeline does not use. export NXF_OFFLINE=true -nextflow run CosciaLab/histo -r v2.0.0 \ +nextflow run CosciaLab/histo -r v3.2.0 \ -profile singularity,size_small,slurm \ -params-file params.yml ``` @@ -113,9 +113,6 @@ outdir: /data/myproject/results use_cellpose: true use_projection: true -flow_threshold: 0.4 -cellprob_threshold: 0 -clip_limit: 0 segment_nuclei: true patch_width_pixel: 3000 diff --git a/site/images/benchmark/old-vs-new.png b/site/images/benchmark/old-vs-new.png new file mode 100644 index 0000000..f07b063 Binary files /dev/null and b/site/images/benchmark/old-vs-new.png differ diff --git a/site/images/benchmark/thresholds.png b/site/images/benchmark/thresholds.png new file mode 100644 index 0000000..180f3e8 Binary files /dev/null and b/site/images/benchmark/thresholds.png differ diff --git a/site/index.md b/site/index.md index 4bc9701..d59a14d 100644 --- a/site/index.md +++ b/site/index.md @@ -6,8 +6,8 @@ dearray and background subtraction, then segmentation, quantification and a QC r unattended on a cluster, on images of any size. It follows nf-core conventions and is not affiliated with or endorsed by nf-core. -% source: README.md#what-this-is -% source: README.md#steps +% source: README.md#credits +% source: README.md#what-it-does :::{figure} ../docs/images/pipeline_paths.svg :class: col-page-right diff --git a/site/inputs/markers.md b/site/inputs/markers.md index 16f4b8f..24ade72 100644 --- a/site/inputs/markers.md +++ b/site/inputs/markers.md @@ -88,12 +88,16 @@ channel that is not `dna`, set [`skip_reference_dna_check`](parameters-full.md#s first `dna` channel is `nuclear`, and every `marker` whose compartment includes `membrane` or `cytoplasm` is `cell`. Once any row has a value, the column is the whole selection: blank rows are left out, the `dna` channel included. See [Many markers with Cellpose](parameters.md#many-markers-with-cellpose). +- **`uniprot_id`**: only with [`use_virtues`](parameters-full.md#use_virtues). The human UniProt ID of + the protein a marker shows, such as `P08246`; channels without one are not embedded. See + [VirTues](../modules/virtues.md). - **`filter`**, **`excitation_wavelength`**, **`emission_wavelength`**: for your records. % source: assets/schema_marker.json % source: docs/usage.md#inputs % source: subworkflows/local/utils_nfcore_histo_pipeline/main.nf:394-427 % source: bin/qc_metrics.py:320-322 +% source: docs/usage.md#virtues ## Background subtraction columns diff --git a/site/inputs/parameters.md b/site/inputs/parameters.md index bc419ac..c0c5061 100644 --- a/site/inputs/parameters.md +++ b/site/inputs/parameters.md @@ -7,7 +7,7 @@ input: /data/myproject/sheets/samplesheet.csv outdir: /data/myproject/results use_instanseg: true -instanseg_pixel_size: 0.65 +pixel_size: 0.65 ``` Every run needs `input` (the [samplesheet](samplesheet.md)) and `outdir` (where results go), and @@ -48,7 +48,7 @@ Pick one method or both. Unless `preprocessing_only`, at least one is needed. | Method | Set | Channels it reads | | ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------- | | [Cellpose](../modules/cellpose.md) | [`use_cellpose`](parameters-full.md#use_cellpose)`: true` and [`cellpose_channels`](parameters-full.md#cellpose_channels), e.g. `"CD45 DNA_1"`, nuclear last | the two you name, or two [projected](#many-markers-with-cellpose) ones | -| [InstanSeg](../modules/instanseg.md) | [`use_instanseg`](parameters-full.md#use_instanseg)`: true` and [`instanseg_pixel_size`](parameters-full.md#instanseg_pixel_size), your pixel size in µm | every `dna` and `marker` channel of the marker sheet | +| [InstanSeg](../modules/instanseg.md) | [`use_instanseg`](parameters-full.md#use_instanseg)`: true` and [`pixel_size`](parameters-full.md#pixel_size), your pixel size in µm | every `dna` and `marker` channel of the marker sheet | Then pick what to find. Cells are on by default. @@ -81,17 +81,14 @@ channels: ```yaml use_cellpose: true use_projection: true -flow_threshold: 0.4 -cellprob_threshold: 0 -clip_limit: 0 ``` - [`use_projection`](parameters-full.md#use_projection) builds the nuclear channel from the first `dna` channel and the cell channel from every `marker` whose compartment is `membrane` or `cytoplasm`. To choose by hand, use the marker sheet's [`segmentation` column](markers.md#optional-columns). -- **Keep the three thresholds.** Without them, Cellpose runs with settings that divide the whole - tissue into cells, whatever the image shows. +- The default grouping leaves autofluorescence and nuclear markers out of the cell channel, as + the [segmentation benchmark](../benchmark.md) favours. Keep them out when choosing by hand. - After the run, open `qc/{sample}_projection.png`, what Cellpose saw. If one marker is listed under `dominant` in `qc/{sample}_projection.json`, it drowns the others: set its `segmentation` to `none` and run again. diff --git a/site/modules/backsub.md b/site/modules/backsub.md index 358f60f..3e882dd 100644 --- a/site/modules/backsub.md +++ b/site/modules/backsub.md @@ -65,7 +65,7 @@ sheet: removed channels are gone and `channel_number` is renumbered. See backsub came as an optional step with the preprocessing half from nf-core/mcmicro. % source: https://github.com/SchapiroLabor/Background_subtraction#introduction -% source: README.md#what-this-is +% source: README.md#credits ## Read more diff --git a/site/modules/cellpose.md b/site/modules/cellpose.md index 5dab614..fc005cd 100644 --- a/site/modules/cellpose.md +++ b/site/modules/cellpose.md @@ -20,12 +20,13 @@ retraining. - [`segment_cells`](../inputs/parameters-full.md#segment_cells) and [`segment_nuclei`](../inputs/parameters-full.md#segment_nuclei): cells, nuclei or both. - [`flow_threshold`](../inputs/parameters-full.md#flow_threshold) and - [`cellprob_threshold`](../inputs/parameters-full.md#cellprob_threshold). Set them to Cellpose's - own values, `0.4` and `0`, with [`clip_limit`](../inputs/parameters-full.md#clip_limit) `0`: - left unset, sopa's values (2, -6 and contrast enhancement 0.2) tile the tissue into cells. + [`cellprob_threshold`](../inputs/parameters-full.md#cellprob_threshold), default `0.6` and + `-1`, set by the [segmentation benchmark](../benchmark.md). sopa's values, 2 and -6, tile the + tissue into cells. - Before the model: [`clip_limit`](../inputs/parameters-full.md#clip_limit) and [`clahe_kernel_size`](../inputs/parameters-full.md#clahe_kernel_size) (contrast enhancement), - [`gaussian_sigma`](../inputs/parameters-full.md#gaussian_sigma) (smoothing). + [`gaussian_sigma`](../inputs/parameters-full.md#gaussian_sigma) (smoothing). Both off by + default: in the benchmark each lowered F1. - [`pretrained_model`](../inputs/parameters-full.md#pretrained_model) and [`cellpose_kwargs`](../inputs/parameters-full.md#cellpose_kwargs) for other Cellpose options. - [`use_gpu`](../inputs/parameters-full.md#use_gpu): segment on a GPU; see diff --git a/site/modules/instanseg.md b/site/modules/instanseg.md index 0421024..5d65146 100644 --- a/site/modules/instanseg.md +++ b/site/modules/instanseg.md @@ -11,7 +11,7 @@ multiplex panel at once, however many there are. ## Parameters - [`use_instanseg`](../inputs/parameters-full.md#use_instanseg): turns InstanSeg on. -- [`instanseg_pixel_size`](../inputs/parameters-full.md#instanseg_pixel_size), required: your +- [`pixel_size`](../inputs/parameters-full.md#pixel_size), required: your image's pixel size in µm. InstanSeg rescales the image to its model's resolution with it; without it, a run could finish with few or no cells, so the pipeline stops at startup instead. - [`instanseg_channels`](../inputs/parameters-full.md#instanseg_channels): the markers it reads. diff --git a/site/modules/nimbus.md b/site/modules/nimbus.md new file mode 100644 index 0000000..677903c --- /dev/null +++ b/site/modules/nimbus.md @@ -0,0 +1,75 @@ +# Nimbus: marker positivity per cell + +## What it does + +Nimbus gives every cell a score between 0 and 1 for every marker. A score near 1 means the model +sees the marker as positive in that cell. You do not set a threshold per marker. + +% source: doi:10.1038/s41592-025-02826-9 +% source: modules/local/nimbus/main.nf + +## Parameters + +- [`use_nimbus`](../inputs/parameters-full.md#use_nimbus): turns Nimbus on. +- [`pixel_size`](../inputs/parameters-full.md#pixel_size), required: your image's pixel size in µm. + Nimbus rescales the image with it, so the pipeline stops at startup without it. +- [`segment_cells`](../inputs/parameters-full.md#segment_cells), required: Nimbus was trained on + whole cells, so nucleus-only runs are refused. +- [`nimbus_channels`](../inputs/parameters-full.md#nimbus_channels): the markers to score. By + default, every `marker` channel of the [marker sheet](../inputs/markers.md). Required for a + stitched image you bring yourself, which has no marker sheet. +- [`use_gpu`](../inputs/parameters-full.md#use_gpu): recommended. A CPU gives near-identical scores but + takes hours per whole slide. + +% source: nextflow_schema.json +% source: docs/decisions.md#learned-features + +## How it works + +For each marker, Nimbus takes that channel and a mask of the cells, and predicts for every pixel +how likely the marker is positive. A cell's score is the mean over its pixels. + +Each channel is first divided by its 0.999 quantile, then clipped to 0 to 1. The quantile is taken +per image, or per core on a tissue microarray. Per core keeps differences between patients, but a +core with no positive cells can score noise as signal. + +Large images are cut into [tiles](tiling.md) with a margin of surrounding context, so memory does +not grow with the image. Tiling can shift scores: on a test crop at 0.65 µm/px, tiled and whole-image +scores differed by up to 0.41 (mean 0.011), while a crop at 1 µm/px showed no difference. Scoring the +whole image at once matched the Nimbus authors' own code to within 1e-6 at both pixel sizes. +Test-time augmentation, which averages the model's answer over flipped copies of the input, is +always on, with the same setting on CPU and GPU. We have not yet compared CPU and GPU scores. + +% source: docs/decisions.md#learned-features +% source: bin/nimbus_cells.py + +**Inputs and outputs.** + +| In | Out | +| ------------------------------------ | ------------------------------------------------------- | +| The full image, one marker at a time | A table `{method}_nimbus` in the store, in `tables/`. | +| The cells of one segmentation method | One row per cell, one column per marker, values 0 to 1. | +| `pixel_size` | A JSON file of settings in `learned_features/`. | + +A column is empty (NaN) for a marker with no signal anywhere in the image. See +[The SpatialData store](../outputs/zarr.md). + +% source: docs/output.md#nimbus-scores + +## Open points + +- The model's magnification is set from your pixel size as `10 / pixel_size`. The authors never say + what "10x" means in µm per pixel, so this is provisional and may change. + +% source: docs/decisions.md#learned-features + +## Read more + +- Nimbus: [@doi:10.1038/s41592-025-02826-9]. +- [Nimbus on GitHub](https://github.com/angelolab/Nimbus-Inference). Code and weights are MIT. + +Version used: + +```{include} ../_generated/modules/nimbus.md + +``` diff --git a/site/modules/projection.md b/site/modules/projection.md index 219fd30..72e18cb 100644 --- a/site/modules/projection.md +++ b/site/modules/projection.md @@ -21,7 +21,8 @@ only those one marker labels. - [`projection_low_percentile`](../inputs/parameters-full.md#projection_low_percentile) and [`projection_high_percentile`](../inputs/parameters-full.md#projection_high_percentile), default 1 and 99.9: each marker's brightness range. -- [`projection_sigma`](../inputs/parameters-full.md#projection_sigma), default 1 px: smoothing. +- [`projection_sigma`](../inputs/parameters-full.md#projection_sigma), default 0: smoothing, off + since the [segmentation benchmark](../benchmark.md). - The [marker sheet](../inputs/markers.md) decides which marker goes where; see below. More in [Many markers with Cellpose](../inputs/parameters.md#many-markers-with-cellpose). @@ -34,7 +35,7 @@ More in [Many markers with Cellpose](../inputs/parameters.md#many-markers-with-c For each of the two output images, `nuclear` and `cell`, every marker in its group is: 1. rescaled to 0–1 between its own low and high percentile, with pixels of exactly 0 left out; -2. smoothed with a Gaussian; +2. smoothed with a Gaussian, if `projection_sigma` is above 0; 3. combined with the group's other markers, pixel by pixel, by maximum (or mean). The groups come from the marker sheet's `segmentation` column if any row has a value. Otherwise @@ -85,6 +86,8 @@ with metrics as support; there was no ground truth. floor below the background, and one dim marker then lit up the glass. - **Nuclear is the first `dna` channel**: the stitching reference, the best aligned, and free of the cell loss later cycles show. +- **No smoothing.** The later [segmentation benchmark](../benchmark.md), against manual outlines, + found that any `projection_sigma` lowered F1. % source: docs/decisions.md#channel-projection diff --git a/site/modules/virtues.md b/site/modules/virtues.md new file mode 100644 index 0000000..6be3525 --- /dev/null +++ b/site/modules/virtues.md @@ -0,0 +1,131 @@ +# VirTues: embeddings per cell and per tissue square + +## What it does + +VirTues is a foundation model for multiplex protein images. It gives each cell a list of 512 +numbers that summarise the cell and its surroundings, across all your markers. It does the same +for each 128 µm square of tissue, and once more for the whole core or image. You can cluster these +numbers, compare cells across patients, or give them to a classifier. They have no meaning one by one. + +% source: https://arxiv.org/abs/2501.06039 +% source: modules/local/virtues/main.nf + +## Parameters + +- [`use_virtues`](../inputs/parameters-full.md#use_virtues): turns VirTues on. +- [`use_gpu`](../inputs/parameters-full.md#use_gpu), required: the model has no CPU version. It needs + a recent NVIDIA GPU, such as an A40 or A100; older cards such as the V100 do not work. +- [`use_preprocessing`](../inputs/parameters-full.md#use_preprocessing), required: the marker sheet + gives the UniProt IDs, and a stitched image has no sheet. +- [`use_tissue_segmentation`](../inputs/parameters-full.md#use_tissue_segmentation), required: + intensities are scaled over tissue only. +- [`segment_cells`](../inputs/parameters-full.md#segment_cells), required: cells are embedded, not nuclei. +- [`pixel_size`](../inputs/parameters-full.md#pixel_size), required: your image's pixel size in µm. + The model works at 1 µm per pixel. +- `virtues_stats`, advanced (listed under hidden parameters in the [full list](../inputs/parameters-full.md)): a statistics file from an + earlier run, used for every slide instead of computing new ones. + +The pipeline stops at startup if one of these is missing. + +% source: nextflow_schema.json +% source: subworkflows/local/utils_nfcore_histo_pipeline/main.nf + +## The marker sheet + +The model needs to know which protein each channel shows. Add a `uniprot_id` column to the +[marker sheet](../inputs/markers.md) and fill it for each marker to embed: + +| channel_number | cycle_number | marker_name | channel_role | channel_compartment | uniprot_id | +| -------------- | ------------ | ----------- | ------------ | ------------------- | ---------- | +| 1 | 1 | DNA_6 | dna | nuclear | | +| 2 | 1 | ELANE | marker | cytoplasm | P08246 | +| 3 | 2 | DNA_7 | dna | nuclear | | +| 4 | 2 | CD11B | marker | membrane | P11215 | + +:::{dropdown} As CSV, to copy + +```csv +channel_number,cycle_number,marker_name,channel_role,channel_compartment,uniprot_id +1,1,DNA_6,dna,nuclear, +2,1,ELANE,marker,cytoplasm,P08246 +3,2,DNA_7,dna,nuclear, +4,2,CD11B,marker,membrane,P11215 +``` + +::: + +- A channel is embedded if its row has a `uniprot_id`, and only then. Leave it empty to skip a channel. +- Nuclear stains are never embedded. A `dna` row with an ID stops the run. +- Each ID may appear once. Use the human UniProt accession, e.g. `P08246`; an isoform ends in + `-2`, `-3` and so on. An ID not in the pipeline's copy of human Swiss-Prot stops the task and is named. + +% source: docs/usage.md#virtues +% source: assets/schema_marker.json + +## How it works + +Intensities are first scaled per marker, with numbers taken over the tissue pixels of the whole +slide: the 0.99 quantile caps each channel, then the log, then the mean and spread. On a tissue +microarray every core of a slide shares them, so cells stay comparable across cores. The numbers +are saved as `{slide}_virtues_stats.json` in `learned_features/`, unless you give `virtues_stats`. + +The image is then resampled to 1 µm per pixel and cut into 128 µm crops. The model embeds each +crop in patches of 8 µm, and a cell's numbers are the average over the patches it covers. Large +images are processed in [tiles](tiling.md) so memory does not grow with image area; the cell results +add about 2 GB per million cells for each segmentation method. Each cell gets +the same crops as a run on the whole image, and its numbers match the authors' own code. + +Each square is the average of its patches, and the whole core or image is the average of its +squares. A square is kept if at least 30% of it is tissue. + +The scaling differs from the model's training, which used statistics over whole datasets. Use +`virtues_stats` with one file for every slide to scale a cohort alike. + +% source: docs/decisions.md#learned-features +% source: bin/virtues_cells.py +% source: bin/virtues_stats.py + +**Inputs.** The full image (only channels with a `uniprot_id`), the cells of each segmentation +method, and the tissue outline. + +**Outputs.** + +- A table `{method}_virtues` per method: one row per cell, 512 columns. +- `virtues_niches` squares and their table `virtues_niches_table`. +- `virtues_tissue`: one row for the whole core or image. +- In `learned_features/`: a settings file per sample, and `{slide}_virtues_stats.json`. + +A cell with no pixel at 1 µm per pixel gets an empty row (NaN). A core or image with no square that +is 30% tissue has an empty `virtues_tissue` row. So does a core where tissue segmentation finds no +tissue; its cells are still embedded. See [The Zarr store](../outputs/zarr.md). + +% source: docs/output.md#virtues-embeddings + +## If the run stops at the statistics + +"standard deviation is zero" means that at least 99% of a marker's tissue pixels are 0, so the +marker carries no signal to scale. Usually background subtraction removed it: check that marker's +`exposure` and `background` in the marker sheet. Otherwise leave its `uniprot_id` empty. + +% source: docs/usage.md#virtues +% source: bin/virtues_stats.py + +## Open points + +- Whether the numbers help on your data has not yet been tested. +- The weights (`sp32`) are licensed CC BY-NC 4.0: academic and non-commercial use only. + +% source: docs/decisions.md#learned-features + +## Read more + +- VirTues: [@doi:10.1038/s41586-026-10884-y], and the + [preprint](https://arxiv.org/abs/2501.06039). The model code is MIT. +- [VirTues on GitHub](https://github.com/bunnelab/virtues). +- ESM-2, which turns each protein into a vector: [@doi:10.1126/science.ade2574]. + +Version used: + +```{include} ../_generated/modules/virtues.md + +``` diff --git a/site/myst.yml b/site/myst.yml index c0d2652..0e54002 100644 --- a/site/myst.yml +++ b/site/myst.yml @@ -46,10 +46,13 @@ project: - file: modules/tiling.md - file: modules/cellpose.md - file: modules/instanseg.md + - file: modules/nimbus.md + - file: modules/virtues.md - file: modules/projection.md - file: modules/linking.md - file: modules/quantification.md - file: modules/qc-report.md + - file: benchmark.md - file: mdc.md - title: Reference children: diff --git a/site/outputs/reports.md b/site/outputs/reports.md index c17141a..12864f8 100644 --- a/site/outputs/reports.md +++ b/site/outputs/reports.md @@ -233,7 +233,7 @@ For stitching and registration, see [Ashlar](../modules/ashlar.md#when-stitching | What you see | Likely cause | Where to look | | ---------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------- | -| Cells tile the whole tissue, ignoring membranes | Cellpose thresholds unset; see [Many markers with Cellpose](../inputs/parameters.md#many-markers-with-cellpose) | "Segmentation overlay"; `qc/{sample}_projection.png` | +| Cells tile the whole tissue, ignoring membranes | sopa's Cellpose thresholds (2, -6) or CLAHE set; see [Segmentation benchmark](../benchmark.md) | "Segmentation overlay"; `qc/{sample}_projection.png` | | Cellpose misses whole groups of cells | One bright marker dominates the projected cell channel | `dominant` in `qc/{sample}_projection.json` | | A TMA core is missing, or two cores are one | Wrong Coreograph downsample factor | `preprocessing/dearray/{slide}_tma_map.tif`; `dearray/sweep/{slide}_sweep_overlays.png` | | An empty patch inside tissue | Segmentation failed in that patch | "Cells per patch" | diff --git a/site/outputs/zarr.md b/site/outputs/zarr.md index c86313c..7ee06d6 100644 --- a/site/outputs/zarr.md +++ b/site/outputs/zarr.md @@ -106,10 +106,12 @@ names unique, for example with `anndata.concat(..., index_unique="-")`. ## Names the pipeline owns Shapes and tables named `{cellpose,instanseg}_{cells,nuclei,cytoplasm,table}` belong to the -pipeline: a run replaces those it writes and removes the rest. Do not give your own additions -these names. +pipeline: a run replaces those it writes and removes the rest. With VirTues, a run also replaces +`{cellpose,instanseg}_virtues`, `virtues_niches`, `virtues_niches_table` and `virtues_tissue`. Do +not give your own additions these names. % source: docs/output.md#spatialdata-directory +% source: bin/write_features.py ## Why Zarr diff --git a/site/references.bib b/site/references.bib index bf0e6de..a312eb1 100644 --- a/site/references.bib +++ b/site/references.bib @@ -182,3 +182,48 @@ @article{Chalfoun_2017 @article{Bankhead_2017, title={QuPath: Open source software for digital pathology image analysis}, volume={7}, ISSN={2045-2322}, url={http://dx.doi.org/10.1038/s41598-017-17204-5}, DOI={10.1038/s41598-017-17204-5}, number={1}, journal={Scientific Reports}, publisher={Springer Science and Business Media LLC}, author={Bankhead, Peter and Loughrey, Maurice B. and Fernández, José A. and Dombrowski, Yvonne and McArt, Darragh G. and Dunne, Philip D. and McQuaid, Stephen and Gray, Ronan T. and Murray, Liam J. and Coleman, Helen G. and James, Jacqueline A. and Salto-Tellez, Manuel and Hamilton, Peter W.}, year={2017}, month=Dec } @article{Preibisch_2009, title={Globally optimal stitching of tiled 3D microscopic image acquisitions}, volume={25}, ISSN={1367-4803}, url={http://dx.doi.org/10.1093/bioinformatics/btp184}, DOI={10.1093/bioinformatics/btp184}, number={11}, journal={Bioinformatics}, publisher={Oxford University Press (OUP)}, author={Preibisch, Stephan and Saalfeld, Stephan and Tomancak, Pavel}, year={2009}, month=Apr, pages={1463–1465} } + +@article{Rumberger_2025, + title = {Automated classification of cellular expression in multiplexed imaging data with Nimbus}, + volume = {22}, + issn = {1548-7105}, + url = {http://dx.doi.org/10.1038/s41592-025-02826-9}, + doi = {10.1038/s41592-025-02826-9}, + number = {10}, + journal = {Nature Methods}, + publisher = {Springer Science and Business Media LLC}, + author = {Rumberger, Josef Lorenz and Greenwald, Noah F. and Ranek, Jolene S. and Boonrat, Potchara and Walker, Cameron and Franzen, Jannik and Varra, Sricharan Reddy and Kong, Alex and Sowers, Cameron and Liu, Candace C. and Averbukh, Inna and Piyadasa, Hadeesha and Vanguri, Rami and Nederlof, Iris and Wang, Xuefei Julie and Van Valen, David and Kok, Marleen and Bendall, Sean C. and Hollmann, Travis J. and Kainmueller, Dagmar and Angelo, Michael}, + year = {2025}, + month = oct, + pages = {2161--2170} +} + +@article{Lin_2023, + title = {Evolutionary-scale prediction of atomic-level protein structure with a language model}, + volume = {379}, + issn = {1095-9203}, + url = {http://dx.doi.org/10.1126/science.ade2574}, + doi = {10.1126/science.ade2574}, + number = {6637}, + journal = {Science}, + publisher = {American Association for the Advancement of Science (AAAS)}, + author = {Lin, Zeming and Akin, Halil and Rao, Roshan and Hie, Brian and Zhu, Zhongkai and Lu, Wenting and Smetanin, Nikita and Verkuil, Robert and Kabeli, Ori and Shmueli, Yaniv and dos Santos Costa, Allan and Fazel-Zarandi, Maryam and Sercu, Tom and Candido, Salvatore and Rives, Alexander}, + year = {2023}, + month = mar, + pages = {1123--1130} +} + +@article{Wenckstern_2026, + title = {The Virtual Tissues foundation model resolves spatial proteomics across scales}, + volume = {657}, + issn = {1476-4687}, + url = {http://dx.doi.org/10.1038/s41586-026-10884-y}, + doi = {10.1038/s41586-026-10884-y}, + number = {8132}, + journal = {Nature}, + publisher = {Springer Science and Business Media LLC}, + author = {Wenckstern, Johann and Jain, Eeshaan and von Querfurth, Benedikt and Cheng, Yexiang and Vasilev, Kiril and Pariset, Matteo and Cheng, Phil F. and Liakopoulos, Petros and Michielin, Olivier and Wicki, Andreas and Gut, Gabriele and Bunne, Charlotte}, + year = {2026}, + month = aug, + pages = {744--754} +} diff --git a/site/tutorials/exemplar-001.md b/site/tutorials/exemplar-001.md index f79b3b4..e1905fc 100644 --- a/site/tutorials/exemplar-001.md +++ b/site/tutorials/exemplar-001.md @@ -87,7 +87,7 @@ input: /path/to/exemplars/samplesheet.csv outdir: /path/to/results/exemplar-001 use_instanseg: true -instanseg_pixel_size: 0.65 +pixel_size: 0.65 patch_width_pixel: 1500 ``` @@ -95,7 +95,7 @@ patch_width_pixel: 1500 - [`use_instanseg`](../inputs/parameters-full.md#use_instanseg) segments cells with [InstanSeg](../modules/instanseg.md). It reads every `dna` and `marker` channel of the marker sheet, so there are no channels to choose. -- [`instanseg_pixel_size`](../inputs/parameters-full.md#instanseg_pixel_size) is the size of +- [`pixel_size`](../inputs/parameters-full.md#pixel_size) is the size of one pixel in µm. For exemplar-001 it is 0.65, as recorded in the image's metadata. - [`patch_width_pixel`](../inputs/parameters-full.md#patch_width_pixel) cuts the image into 1500-pixel squares, here 3 × 2 patches, segmented side by side. See @@ -111,7 +111,7 @@ background subtraction, no TMA dearray. ## Run ```bash -nextflow run CosciaLab/histo -r v2.0.0 \ +nextflow run CosciaLab/histo -r v3.2.0 \ -profile singularity,size_small,slurm \ -params-file params.yml ``` diff --git a/site/tutorials/multiple-segmentations.md b/site/tutorials/multiple-segmentations.md index e9fd06e..ada35c0 100644 --- a/site/tutorials/multiple-segmentations.md +++ b/site/tutorials/multiple-segmentations.md @@ -21,7 +21,7 @@ Pick one or both **methods**: | ------------------------------------------ | -------------------------------------------------------------------------------------------------------------------- | | Cells from one membrane marker and DNA | `use_cellpose: true`, `cellpose_channels: "CD45 DNA_6"`, nuclear stain last | | Cells from many markers, with Cellpose | `use_cellpose: true`, `use_projection: true`; see [Many markers](../inputs/parameters.md#many-markers-with-cellpose) | -| Cells from every marker, no channel choice | `use_instanseg: true`, `instanseg_pixel_size` in µm per pixel | +| Cells from every marker, no channel choice | `use_instanseg: true`, `pixel_size` in µm per pixel | | A second opinion | Both. The QC then compares them | Then the **targets**. Cells are on by default. @@ -52,12 +52,9 @@ outdir: /path/to/results/exemplar-001-both use_cellpose: true use_projection: true -flow_threshold: 0.4 -cellprob_threshold: 0 -clip_limit: 0 use_instanseg: true -instanseg_pixel_size: 0.65 +pixel_size: 0.65 segment_nuclei: true patch_width_pixel: 1500 @@ -67,8 +64,6 @@ patch_width_pixel: 1500 built from the marker sheet ([Channel projection](../modules/projection.md)): `DNA_6` as nuclear, and every `marker` whose `channel_compartment` is `membrane` or `cytoplasm` as cell. `FOXP3` is nuclear, so it stays out. -- The three thresholds are Cellpose's own values. Left unset, sopa's defaults tile the whole - tissue into cells, whatever the image shows. - [`segment_nuclei`](../inputs/parameters-full.md#segment_nuclei) adds nuclei to the cells. Each nucleus is then [linked](../modules/linking.md) to its cell, and the cytoplasm is the cell minus its nuclei. @@ -83,7 +78,7 @@ patch_width_pixel: 1500 ## Run ```bash -nextflow run CosciaLab/histo -r v2.0.0 \ +nextflow run CosciaLab/histo -r v3.2.0 \ -profile singularity,size_small,slurm \ -params-file params.yml ``` diff --git a/site/tutorials/prestitched.md b/site/tutorials/prestitched.md index 1f56b0f..bcea010 100644 --- a/site/tutorials/prestitched.md +++ b/site/tutorials/prestitched.md @@ -53,9 +53,6 @@ use_preprocessing: false use_cellpose: true cellpose_channels: "CD45 DAPI" -flow_threshold: 0.4 -cellprob_threshold: 0 -clip_limit: 0 patch_width_pixel: 5000 ``` @@ -67,8 +64,6 @@ patch_width_pixel: 5000 [Channel projection](../modules/projection.md) is not available here: it needs the marker sheet. For [InstanSeg](../modules/instanseg.md), set [`instanseg_channels`](../inputs/parameters-full.md#instanseg_channels) for the same reason. -- The three thresholds are Cellpose's own values. Left unset, sopa's defaults tile the whole - tissue into cells, whatever the image shows. - `patch_width_pixel: 5000` assumes 25 000 × 25 000 pixels: 25 patches. See [Patch size](../inputs/parameters.md#patch-size). @@ -80,7 +75,7 @@ patch_width_pixel: 5000 ## Run ```bash -nextflow run CosciaLab/histo -r v2.0.0 \ +nextflow run CosciaLab/histo -r v3.2.0 \ -profile singularity,size_small,slurm \ -params-file params.yml ``` diff --git a/site/tutorials/stitching-only.md b/site/tutorials/stitching-only.md index 370bb4c..ea4cd61 100644 --- a/site/tutorials/stitching-only.md +++ b/site/tutorials/stitching-only.md @@ -90,7 +90,7 @@ preprocessing_only: true ## Run ```bash -nextflow run CosciaLab/histo -r v2.0.0 \ +nextflow run CosciaLab/histo -r v3.2.0 \ -profile singularity,size_small,slurm \ -params-file params.yml ``` diff --git a/site/tutorials/tma.md b/site/tutorials/tma.md index 19711a5..feb4b8b 100644 --- a/site/tutorials/tma.md +++ b/site/tutorials/tma.md @@ -88,7 +88,7 @@ tma_core_diameter_mm: 1.5 use_backsub: true use_instanseg: true -instanseg_pixel_size: 0.65 +pixel_size: 0.65 segment_nuclei: true patch_width_pixel: 2000 @@ -115,7 +115,7 @@ patch_width_pixel: 2000 ## Run ```bash -nextflow run CosciaLab/histo -r v2.0.0 \ +nextflow run CosciaLab/histo -r v3.2.0 \ -profile singularity,size_small,slurm \ -params-file params.yml ``` diff --git a/site/tutorials/wsi-backsub.md b/site/tutorials/wsi-backsub.md index 5a684e9..f4d48dd 100644 --- a/site/tutorials/wsi-backsub.md +++ b/site/tutorials/wsi-backsub.md @@ -81,9 +81,6 @@ use_backsub: true use_cellpose: true cellpose_channels: "CD45 DNA_1" -flow_threshold: 0.4 -cellprob_threshold: 0 -clip_limit: 0 patch_width_pixel: 8000 ``` @@ -93,8 +90,6 @@ patch_width_pixel: 8000 - [`cellpose_channels`](../inputs/parameters-full.md#cellpose_channels) gives [Cellpose](../modules/cellpose.md) one membrane marker and the DNA stain, nuclear stain last. A channel that `remove` drops cannot be used here; the run stops at the start if it is. -- The three thresholds are Cellpose's own values. Left unset, sopa's defaults tile the whole - tissue into cells, whatever the image shows. - `patch_width_pixel: 8000` assumes a stitched image of about 100 000 × 60 000 pixels: about 100 patches. See [Patch size](../inputs/parameters.md#patch-size). @@ -105,7 +100,7 @@ patch_width_pixel: 8000 ## Run ```bash -nextflow run CosciaLab/histo -r v2.0.0 \ +nextflow run CosciaLab/histo -r v3.2.0 \ -profile singularity,size_medium,slurm \ -params-file params.yml ``` diff --git a/subworkflows/local/learned_features/main.nf b/subworkflows/local/learned_features/main.nf new file mode 100644 index 0000000..ebe47f2 --- /dev/null +++ b/subworkflows/local/learned_features/main.nf @@ -0,0 +1,130 @@ +// Learned per-cell features for every spec (model) and segmentation method, then one write into the store per sample. + +include { NIMBUS } from '../../../modules/local/nimbus' +include { VIRTUES_HISTOGRAM } from '../../../modules/local/virtues_histogram' +include { VIRTUES_STATS } from '../../../modules/local/virtues_stats' +include { VIRTUES } from '../../../modules/local/virtues' +include { WRITE_FEATURES } from '../../../modules/local/write_features' +include { defaultNimbusChannels; virtuesChannels; virtuesUnembedded } from '../../../modules/local/utils' + +workflow LEARNED_FEATURES { + take: + ch_sdata // channel: [ val(meta), path(sdata) ] the store with segmentations written + ch_markers // channel: [ val(meta), path(csv) ] the channels each image has; empty without a marker sheet + specs // list: spec maps from featureSpecs(params), shared by every sample + methods // list: segmentation methods, each scored separately + + main: + def ch_versions = channel.empty() + + // Samples are keyed by meta.sdata_dir as a String, as in SEGMENTATION (a GString never equals a String). + + // remainder: true keeps a sample with no sheet (sheet is null), so given channels can still be checked when one exists. + def ch_sample_rows = ch_sdata + .join(ch_markers, remainder: true) + .map { meta, sdata, sheet -> [meta, sdata, sheet ? sheet.splitCsv(header: true) : null] } + + // Nimbus: one row per sample, method and spec. VirTues: one row per sample, carrying every method, + // since it embeds the image once and pools per method. Specs are shared objects: build new maps, never mutate one. + def ch_sample_specs = ch_sample_rows.flatMap { meta, sdata, rows -> + specs.collectMany { spec -> + if (spec.model == 'nimbus') { + // Unknown names would fail inside the task; fail here and say which. + if (rows != null && spec.channels) { + def missing = spec.channels - rows*.marker_name + if (missing) { + // error(), not assert: an assert inside an operator dies without its message. + error("Sample '${meta.sample}': nimbus_channels not in the marker sheet: ${missing.join(', ')}.") + } + } + def channels = spec.channels ?: defaultNimbusChannels(rows ?: []) + if (!channels) { + error("Sample '${meta.sample}': no marker channels for nimbus. Set nimbus_channels, or mark channels 'marker' in the marker sheet.") + } + return methods.collect { method -> [meta, sdata, method, spec + [channels: channels]] } + } + if (spec.model == 'virtues') { + def channels = virtuesChannels(rows ?: []) + if (!channels) { + error("Sample '${meta.sample}': no marker row with a uniprot_id reached VirTues. With use_backsub, check that backsub kept the uniprot_id column.") + } + return [[meta, sdata, methods, spec + [channels: channels, unembedded: virtuesUnembedded(rows)]]] + } + // A model with no branch here would be dropped and the store never written: fail instead. + error("Unknown learned-features model '${spec.model}'; add its branch to LEARNED_FEATURES.") + } + } + + // One branch per model; KRONOS and others add theirs here. The third item is a method for + // Nimbus and the list of methods for VirTues. + def ch_by_model = ch_sample_specs.branch { _meta, _sdata, _method, spec -> + nimbus: spec.model == 'nimbus' + virtues: spec.model == 'virtues' + } + + (ch_nimbus, versions) = NIMBUS(ch_by_model.nimbus) + ch_versions = ch_versions.mix(versions) + + // VirTues standardises intensities with slide-wide statistics: a TMA's cores share their slide's. + // Slide key below: meta.slide on a TMA core, else the sample; a String, as a GString never equals one. + def virtues_spec = specs.find { spec -> spec.model == 'virtues' } + + def ch_virtues_input + if (virtues_spec?.stats) { + // Given statistics replace both statistics tasks; the same file goes to every store. + ch_virtues_input = ch_by_model.virtues + .map { meta, sdata, store_methods, spec -> [meta, sdata, store_methods, spec, file(spec.stats)] } + } + else { + (ch_hists, versions) = VIRTUES_HISTOGRAM( + ch_by_model.virtues.map { meta, sdata, _methods, spec -> [meta, sdata, spec] } + ) + ch_versions = ch_versions.mix(versions) + + // No size given: the cores per slide are not known in advance, so this waits for every store. + def ch_slide_hists = ch_hists + .map { meta, hist -> [(meta.slide ?: meta.sample).toString(), hist] } + .groupTuple() + // Sorted by file name, so -resume does not depend on arrival order. + .map { slide, hists -> [slide, hists.sort(false) { hist -> hist.name }, virtues_spec] } + + (ch_stats, versions) = VIRTUES_STATS(ch_slide_hists) + ch_versions = ch_versions.mix(versions) + + // combine by: 0, not join: join pairs one row per key, and a slide has many stores. + ch_virtues_input = ch_by_model.virtues + .map { meta, sdata, store_methods, spec -> [(meta.slide ?: meta.sample).toString(), meta, sdata, store_methods, spec] } + .combine(ch_stats, by: 0) + .map { _slide, meta, sdata, store_methods, spec, stats -> [meta, sdata, store_methods, spec, stats] } + } + + (ch_virtues, _ch_virtues_provenance, versions) = VIRTUES(ch_virtues_input) + ch_versions = ch_versions.mix(versions) + + // Every model's outputs, as [meta, [files]]; the writer needs no more. A single glob match is a bare path. + def ch_outputs = ch_nimbus + .map { meta, _method, _spec, table, _provenance -> [meta, [table]] } + .mix(ch_virtues.map { meta, files -> [meta, files instanceof List ? files : [files]] }) + + // groupKey carries the output count, so a sample is written once all its outputs are in. + // Nimbus gives one table per method; VirTues one list of files per store. + def n_outputs = specs.sum { spec -> spec.model == 'virtues' ? 1 : methods.size() } + def ch_sample_outputs = ch_outputs + .map { meta, files -> [groupKey(meta.sdata_dir.toString(), n_outputs), files] } + .groupTuple() + // Flattened and sorted by file name, so the write order and -resume do not depend on arrival order. + .map { key, file_lists -> [key.toString(), file_lists.collectMany { files -> files }.sort { f -> f.name }] } + + // Outputs carry no store; take it back by sample. join: one row per sample on both sides. + def ch_to_write = ch_sdata + .map { meta, sdata -> [meta.sdata_dir.toString(), meta, sdata] } + .join(ch_sample_outputs) + .map { _sdata_dir, meta, sdata, files -> [meta, sdata, files] } + + (ch_written, versions) = WRITE_FEATURES(ch_to_write) + ch_versions = ch_versions.mix(versions) + + emit: + sdata = ch_written // channel: [ val(meta), path(sdata) ] with tables {method}_nimbus and {method}_virtues written + versions = ch_versions // channel: [ path(versions.yml) ] +} diff --git a/subworkflows/local/learned_features/meta.yml b/subworkflows/local/learned_features/meta.yml new file mode 100644 index 0000000..d9f5ba2 --- /dev/null +++ b/subworkflows/local/learned_features/meta.yml @@ -0,0 +1,55 @@ +# yaml-language-server: $schema=https://raw.githubusercontent.com/nf-core/modules/master/subworkflows/yaml-schema.json +name: "learned_features" +description: Score every segmented cell with learned models (Nimbus, VirTues) per segmentation method and write the outputs into the store once per sample +keywords: + - nimbus + - virtues + - features + - spatial + - imaging +components: + - nimbus + - virtues/histogram + - virtues/stats + - virtues + - write/features + - defaultnimbuschannels + - virtueschannels + - virtuesunembedded +input: + - ch_sdata: + type: file + description: | + Channel containing a SpatialData Zarr store with segmentations written. + Structure: [ val(meta), path(sdata_path) ] + - ch_markers: + type: file + description: | + Channel containing each sample's marker sheet, read for the default Nimbus channels + when nimbus_channels is unset and for the VirTues channels (rows with a uniprot_id). + May be empty otherwise. + Structure: [ val(meta), path(csv) ] + - specs: + type: list + description: | + Feature spec maps from featureSpecs(params) in modules/local/utils.nf. + - methods: + type: list + description: | + Segmentation methods; each is scored separately. +output: + - sdata: + type: file + description: | + Channel containing the SpatialData Zarr store with tables {method}_nimbus and + {method}_virtues written, and VirTues' niche and tissue elements when kept. + Structure: [ val(meta), path(sdata_path) ] + - versions: + type: file + description: | + Channel containing software versions. + Structure: [ path(versions.yml) ] +authors: + - "@josenimo" +maintainers: + - "@josenimo" diff --git a/subworkflows/local/segmentation/main.nf b/subworkflows/local/segmentation/main.nf index 786b98a..77187ac 100644 --- a/subworkflows/local/segmentation/main.nf +++ b/subworkflows/local/segmentation/main.nf @@ -9,7 +9,7 @@ include { RESOLVE } from '../../../modules/loca include { LINK_COMPARTMENTS } from '../../../modules/local/link_compartments' include { AGGREGATE } from '../../../modules/local/aggregate' include { WRITE_SEGMENTATIONS } from '../../../modules/local/write_segmentations' -include { defaultInstansegChannels; instansegMaxPatchWidth; instansegMemoryGB } from '../../../modules/local/utils' +include { defaultInstansegChannels; instansegMaxPatchWidth; instansegMemoryGB; pixelSize } from '../../../modules/local/utils' workflow SEGMENTATION { take: @@ -48,7 +48,7 @@ workflow SEGMENTATION { error("Sample '${meta.sample}': no channels for ${spec.name}. Set instanseg_channels, or give the marker sheet a 'dna' channel.") } // Memory per spec, as channel counts differ; conf/base.config reads spec.memory_gb. - def memory_gb = instansegMemoryGB(channels.size(), params.patch_width_pixel, params.instanseg_pixel_size) + def memory_gb = instansegMemoryGB(channels.size(), params.patch_width_pixel, pixelSize(params)) [meta, sdata, spec + [channels: channels, memory_gb: memory_gb], n_patches] } } @@ -60,11 +60,11 @@ workflow SEGMENTATION { .map { _meta, _sdata, spec, _n_patches -> spec.channels.size() } .unique() .subscribe { n_channels -> - def gigabytes = instansegMemoryGB(n_channels, params.patch_width_pixel, params.instanseg_pixel_size) + def gigabytes = instansegMemoryGB(n_channels, params.patch_width_pixel, pixelSize(params)) if (gigabytes > warn_gb) { log.warn "InstanSeg on ${n_channels} channels asks for ${gigabytes} GB per patch task (twice that on retry) " + - "at patch_width_pixel ${params.patch_width_pixel} and ${params.instanseg_pixel_size} µm/px. To stay under ${warn_gb} GB, " + - "set patch_width_pixel to ${instansegMaxPatchWidth(n_channels, warn_gb, params.instanseg_pixel_size)} or name fewer instanseg_channels." + "at patch_width_pixel ${params.patch_width_pixel} and ${pixelSize(params)} µm/px. To stay under ${warn_gb} GB, " + + "set patch_width_pixel to ${instansegMaxPatchWidth(n_channels, warn_gb, pixelSize(params))} or name fewer instanseg_channels." } } diff --git a/subworkflows/local/utils_nfcore_histo_pipeline/main.nf b/subworkflows/local/utils_nfcore_histo_pipeline/main.nf index fadfef8..bc68b6c 100644 --- a/subworkflows/local/utils_nfcore_histo_pipeline/main.nf +++ b/subworkflows/local/utils_nfcore_histo_pipeline/main.nf @@ -19,6 +19,8 @@ include { segmentationTargets } from '../../../modules/local/utils' include { defaultInstansegChannels } from '../../../modules/local/utils' include { getChannels } from '../../../modules/local/utils' include { instansegGpuMaxChannels } from '../../../modules/local/utils' +include { pixelSize } from '../../../modules/local/utils' +include { virtuesChannels } from '../../../modules/local/utils' /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -153,10 +155,17 @@ workflow PIPELINE_INITIALISATION { def sheets_by_sample = markerSheetsBySample(cycle_rows) // Every marker sheet column is declared as meta, so each row is [meta], hence it[0]. + // Parsed once: the same file is checked against every sample's sheet. + def virtues_stats = params.use_virtues && params.virtues_stats + ? new groovy.json.JsonSlurper().parse(new File(params.virtues_stats.toString())) + : null sheets_by_sample.each { sample, sheet -> def rows = samplesheetToList(sheet, "${projectDir}/assets/schema_marker.json").collect { it[0] } validateMarkersheet(rows, sample) checkReferenceChannels(rows, sample) + if (params.use_virtues) { + validateVirtuesMarkers(rows, "marker_sheet for sample '${sample}'", virtues_stats) + } } ch_markersheet = channel.fromList( @@ -348,7 +357,7 @@ def validateMarkersheet(rows, sample = null) { // Segmentation runs after backsub, so a removed channel is no longer in the image. def removed = rows.findAll { it.remove }.collect { it.marker_name } as Set - ['cellpose_channels', 'instanseg_channels'].each { param -> + ['cellpose_channels', 'instanseg_channels', 'nimbus_channels'].each { param -> def value = params[param] if (!(value instanceof CharSequence)) { return @@ -390,6 +399,44 @@ def validateMarkersheet(rows, sample = null) { return rows } +// VirTues embeds a channel only when it has a uniprot_id; checked on the rows backsub keeps. +def validateVirtuesMarkers(rows, where, stats = null) { + def kept = params.use_backsub ? rows.findAll { !it.remove } : rows + + if (!kept.any { it.uniprot_id }) { + error("${where}: use_virtues needs a uniprot_id on at least one marker row; a channel is embedded only when it has one.") + } + + def dna = kept.findAll { it.channel_role == 'dna' && it.uniprot_id }.collect { it.marker_name } + if (dna) { + error("${where}: DNA stains are not embedded; remove the uniprot_id from: ${dna}.") + } + + def repeated = kept + .findAll { it.uniprot_id } + .groupBy { it.uniprot_id } + .findAll { _id, group -> group.size() > 1 } + .keySet() + .sort() + if (repeated) { + error("${where}: uniprot_id must be unique. Repeated: ${repeated}.") + } + + if (stats != null) { + def recorded = stats.markers ?: [:] + def channels = virtuesChannels(kept) + def missing = channels.findAll { name, _id -> !recorded.containsKey(name) }.collect { name, _id -> name } + if (missing) { + error("${where}: virtues_stats has no statistics for: ${missing}.") + } + channels.each { name, id -> + if (recorded[name].uniprot_id != id) { + error("${where}: virtues_stats records a different uniprot_id for: ${name} (sheet ${id}, stats ${recorded[name].uniprot_id}).") + } + } + } +} + // Mirrors resolve_groups in bin/project_channels.py, so an empty group fails before stitching. def validateProjectionGroups(rows, where) { // Removed channels are gone from the image by the time it is projected. @@ -645,8 +692,13 @@ def validateParams(params) { // InstanSeg rescales to its training resolution; without it the objects are at the wrong scale // and the run succeeds with few or no cells. - assert !(params.use_instanseg && params.instanseg_pixel_size == null) : - "use_instanseg requires instanseg_pixel_size (microns per pixel of the image). Without it " + + // Called unconditionally so a conflicting pixel-size pair stops every run, not only InstanSeg's. + pixelSize(params) + if (params.instanseg_pixel_size != null) { + log.warn("instanseg_pixel_size is deprecated; use pixel_size.") + } + assert !(params.use_instanseg && pixelSize(params) == null) : + "use_instanseg requires pixel_size (microns per pixel of the image). Without it " + "InstanSeg does not rescale and may return no cells." // Channel roles come from the marker sheet, which pre-stitched input does not have. @@ -654,6 +706,40 @@ def validateParams(params) { "use_instanseg without use_preprocessing needs instanseg_channels: the default channels " + "come from the marker sheet. Name the channels, separated by space, comma or pipe." + // Nimbus scores each segmented cell, at the model's training resolution. + assert !(params.use_nimbus && pixelSize(params) == null) : + "use_nimbus requires pixel_size (microns per pixel of the image). Without it Nimbus " + + "cannot rescale to its training resolution." + assert !(params.use_nimbus && !('cells' in segmentationTargets(params))) : + "use_nimbus requires segment_cells: Nimbus scores cells, so there must be a cell segmentation." + assert !(params.use_nimbus && params.nimbus_channels == null && !params.use_preprocessing) : + "use_nimbus without use_preprocessing needs nimbus_channels: the default channels " + + "come from the marker sheet. Name the channels, separated by space, comma or pipe." + if (params.use_nimbus && !params.use_gpu) { + log.warn("use_nimbus without use_gpu: near-identical scores, but a whole slide can take days on CPU and may exceed the task time limit.") + } + + if (params.use_virtues) { + if (!params.use_gpu) { + error("use_virtues requires use_gpu: VirTues runs on FlashAttention, which has no CPU path.") + } + if (!params.use_preprocessing) { + error("use_virtues requires use_preprocessing: UniProt IDs come from the marker sheet, which pre-stitched input does not have.") + } + if (!params.use_tissue_segmentation) { + error("use_virtues requires use_tissue_segmentation: intensity statistics are computed over tissue pixels.") + } + if (!('cells' in segmentationTargets(params))) { + error("use_virtues requires segment_cells: VirTues embeds cells, so there must be a cell segmentation.") + } + if (pixelSize(params) == null) { + error("use_virtues requires pixel_size (microns per pixel of the image): VirTues runs at 1 µm per pixel.") + } + } + if (params.virtues_stats && !params.use_virtues) { + error("virtues_stats is set but use_virtues is not.") + } + if (params.preprocessing_only) { assert params.use_preprocessing : "preprocessing_only requires use_preprocessing: with " + "pre-stitched input there is nothing to run." diff --git a/tests/exemplar001.nf.test b/tests/exemplar001.nf.test index 6262ff6..01307d5 100644 --- a/tests/exemplar001.nf.test +++ b/tests/exemplar001.nf.test @@ -6,7 +6,7 @@ // --profile test_exemplar001,singularity,size_small,slurm // nf-test's --profile replaces the profile directive, so repeat test_exemplar001 (or use --profile=+...). // Property assertions, not snapshots: Cellpose output drifts with version and hardware. -// Both methods, cells and nuclei. 1.x baseline: 9,877 Cellpose cells (3717ea0, 2026-10-06). +// Both methods, cells and nuclei. nextflow_pipeline { @@ -36,8 +36,8 @@ nextflow_pipeline { def cells = methods.collectEntries { m -> [(m): slurp.parse(file("${zarr}/tables/${m}_table/X/zarr.json")).shape[0]] } - // PLACEHOLDER: set from the 2.0 cluster run; null skips the count check. - def baseline = [cellpose: null, instanseg: null] + // From the 3.2.0 cluster run (test14, 79c05cd, 2026-11-27). + def baseline = [cellpose: 15415, instanseg: 16455] def imageShape = slurp.parse(file("${zarr}/images/exemplar-001/s0/zarr.json")).shape def ran = workflow.trace.succeeded().collect { it.name } diff --git a/tests/exemplar002.nf.test b/tests/exemplar002.nf.test index 3d61798..ddb75df 100644 --- a/tests/exemplar002.nf.test +++ b/tests/exemplar002.nf.test @@ -6,7 +6,7 @@ // --profile test_exemplar002,singularity,size_small,slurm // Repeat test_exemplar002 in --profile: nf-test's --profile replaces the directive. // Cycle 1 (autofluorescence) is subtracted from cycles 2 and 3, then dropped by remove: 12 channels become 9. -// InstanSeg only, cells and nuclei. 1.x Cellpose baselines (DNA_1): 7472, 4779, 7604, 9678 cells (3717ea0). +// InstanSeg only, cells and nuclei. nextflow_pipeline { @@ -34,10 +34,10 @@ nextflow_pipeline { def coreMetrics = cores.collect { slurp.parse(file("$outputDir/qc/${it}_instanseg_qc.json")) } - // PLACEHOLDER: InstanSeg cells per core, set from the 2.0 cluster run; null skips the count check. + // InstanSeg cells per core, from the 3.2.0 cluster run (test14, 79c05cd, 2026-11-27). def baseline = [ - 'exemplar-002_core001': null, 'exemplar-002_core002': null, - 'exemplar-002_core003': null, 'exemplar-002_core004': null, + 'exemplar-002_core001': 9213, 'exemplar-002_core002': 16118, + 'exemplar-002_core003': 13689, 'exemplar-002_core004': 16634, ] def counts = cores.indices.collectEntries { i -> [(cores[i]): coreMetrics[i].cells.n_cells] } diff --git a/tests/feature_specs.nf.test b/tests/feature_specs.nf.test new file mode 100644 index 0000000..34da8f0 --- /dev/null +++ b/tests/feature_specs.nf.test @@ -0,0 +1,188 @@ +// One spec per learned-features model, built from params. + +nextflow_function { + + name "featureSpecs" + script "../modules/local/utils.nf" + function "featureSpecs" + tag "unit" + tag "validation" + + test("no model gives no specs") { + when { + function { + """ + input[0] = [:] + """ + } + } + then { + assert function.success + assert function.result == [] + } + } + + test("Nimbus with marker-sheet channels") { + when { + function { + """ + input[0] = [ use_nimbus: true, pixel_size: 0.65 ] + """ + } + } + then { + assert function.success + assert function.result.size() == 1 + assert function.result[0].name == 'nimbus' + assert function.result[0].model == 'nimbus' + assert function.result[0].channels == null + assert function.result[0].pixel_size == 0.65 + } + } + + test("Nimbus channels are split and pixel_size parsed") { + when { + function { + """ + input[0] = [ use_nimbus: true, pixel_size: '0.65', nimbus_channels: 'CD3, CD45' ] + """ + } + } + then { + assert function.success + assert function.result[0].channels == ['CD3', 'CD45'] + assert function.result[0].pixel_size == 0.65 + } + } + + test("VirTues has no channel list and no stats file by default") { + when { + function { + """ + input[0] = [ use_virtues: true, pixel_size: 0.65 ] + """ + } + } + then { + assert function.success + assert function.result.size() == 1 + assert function.result[0].name == 'virtues' + assert function.result[0].model == 'virtues' + assert function.result[0].channels == null + assert function.result[0].stats == null + assert function.result[0].pixel_size == 0.65 + } + } + + test("virtues_stats reaches the VirTues spec") { + when { + function { + """ + input[0] = [ use_virtues: true, pixel_size: 0.65, virtues_stats: '/x/s.json' ] + """ + } + } + then { + assert function.success + assert function.result[0].stats == '/x/s.json' + } + } + + test("Nimbus and VirTues together give two specs, Nimbus first") { + when { + function { + """ + input[0] = [ use_nimbus: true, use_virtues: true, pixel_size: 0.65 ] + """ + } + } + then { + assert function.success + assert function.result*.name == ['nimbus', 'virtues'] + } + } +} + +nextflow_function { + + name "defaultNimbusChannels" + script "../modules/local/utils.nf" + function "defaultNimbusChannels" + tag "unit" + tag "validation" + + test("only marker channels, in order") { + when { + function { + """ + input[0] = [ + [ marker_name: 'DAPI', channel_role: 'dna' ], + [ marker_name: 'CD3', channel_role: 'marker' ], + [ marker_name: 'AF488', channel_role: 'autofluorescence' ], + [ marker_name: 'CD45', channel_role: 'marker' ], + ] + """ + } + } + then { + assert function.success + assert function.result == ['CD3', 'CD45'] + } + } +} + +nextflow_function { + + name "virtuesChannels" + script "../modules/local/utils.nf" + function "virtuesChannels" + tag "unit" + tag "validation" + + test("rows with a uniprot_id give [name, id] pairs in sheet order") { + when { + function { + """ + input[0] = [ + [ marker_name: 'DNA_1', channel_role: 'dna' ], + [ marker_name: 'ELANE', channel_role: 'marker', uniprot_id: 'P08246' ], + [ marker_name: 'CD11B', channel_role: 'marker', uniprot_id: 'P11215' ], + [ marker_name: 'FOXP3', channel_role: 'marker' ], + ] + """ + } + } + then { + assert function.success + assert function.result == [['ELANE', 'P08246'], ['CD11B', 'P11215']] + } + } +} + +nextflow_function { + + name "virtuesUnembedded" + script "../modules/local/utils.nf" + function "virtuesUnembedded" + tag "unit" + tag "validation" + + test("rows without a uniprot_id are the unembedded names") { + when { + function { + """ + input[0] = [ + [ marker_name: 'DNA_1', channel_role: 'dna' ], + [ marker_name: 'ELANE', channel_role: 'marker', uniprot_id: 'P08246' ], + [ marker_name: 'CD11B', channel_role: 'marker', uniprot_id: 'P11215' ], + [ marker_name: 'FOXP3', channel_role: 'marker' ], + ] + """ + } + } + then { + assert function.success + assert function.result == ['DNA_1', 'FOXP3'] + } + } +} diff --git a/tests/gpu.nf.test b/tests/gpu.nf.test index 9b20952..2c5f5b0 100644 --- a/tests/gpu.nf.test +++ b/tests/gpu.nf.test @@ -41,7 +41,7 @@ nextflow_pipeline { outdir = "$outputDir" use_gpu = true use_instanseg = true - instanseg_pixel_size = 0.65 + pixel_size = 0.65 instanseg_channels = "DAPI" } } diff --git a/tests/instanseg.nf.test b/tests/instanseg.nf.test index 1237deb..10efacd 100644 --- a/tests/instanseg.nf.test +++ b/tests/instanseg.nf.test @@ -18,7 +18,7 @@ nextflow_pipeline { outdir = "$outputDir" use_cellpose = false use_instanseg = true - instanseg_pixel_size = 0.65 + pixel_size = 0.65 instanseg_channels = "DAPI" } } @@ -60,7 +60,7 @@ nextflow_pipeline { use_cellpose = false use_instanseg = true // Small, so the memory request stays under the tests' 6 GB cap (tests/nextflow.config). - instanseg_pixel_size = 0.1 + pixel_size = 0.1 } } @@ -92,7 +92,7 @@ nextflow_pipeline { use_cellpose = false use_instanseg = true // 5000 px at 1 µm/px is 10000 px at the model's 0.5: 132 GB for one channel. - instanseg_pixel_size = 1.0 + pixel_size = 1.0 instanseg_channels = "DAPI" } } @@ -122,7 +122,7 @@ nextflow_pipeline { then { assertAll( { assert workflow.failed }, - { assert (workflow.stdout + workflow.stderr).join("\n").contains("instanseg_pixel_size") } + { assert (workflow.stdout + workflow.stderr).join("\n").contains("pixel_size") } ) } } @@ -134,7 +134,7 @@ nextflow_pipeline { outdir = "$outputDir" use_cellpose = false use_instanseg = true - instanseg_pixel_size = 0.65 + pixel_size = 0.65 } } diff --git a/tests/instanseg_memory.nf.test b/tests/instanseg_memory.nf.test index 9d8a7e3..9cf4970 100644 --- a/tests/instanseg_memory.nf.test +++ b/tests/instanseg_memory.nf.test @@ -111,7 +111,7 @@ nextflow_function { then { assert function.failed def out = function.stdout.toString() + function.stderr.toString() - assert out.contains("instanseg_pixel_size must be a number, got 'abc'") + assert out.contains("pixel_size must be a number, got 'abc'") } } } diff --git a/tests/nimbus.nf.test b/tests/nimbus.nf.test new file mode 100644 index 0000000..e2afcd1 --- /dev/null +++ b/tests/nimbus.nf.test @@ -0,0 +1,168 @@ +// Nimbus under -stub: one NIMBUS per store and method, one write, QC after it. +// -profile test supplies Cellpose; laptop puts tests/stub_bin on PATH for ashlar. + +nextflow_pipeline { + + name "Nimbus" + script "../main.nf" + profile "test,laptop" + options "-stub" + tag "stub" + tag "pipeline" + + // The trace has no timestamps; a task's .command.begin and .exitcode files mark its start and end. + def taskTimes = { metaDir, workDir, proc -> + def rows = new File("$metaDir/trace.csv").readLines()*.split('\t') + def col = { name -> rows[0].findIndexOf { it == name } } + rows.tail().findAll { it[col('name')].contains(proc) }.collect { r -> + def dir = new File("$workDir/${r[col('hash')].split('/')[0]}").listFiles().find { it.name.startsWith(r[col('hash')].split('/')[1]) } + [start: new File(dir, '.command.begin').lastModified(), end: new File(dir, '.exitcode').lastModified()] + } + } + + test("one method: one NIMBUS, one WRITE_FEATURES, QC after it") { + + when { + params { + outdir = "$outputDir" + use_nimbus = true + nimbus_channels = "DAPI" + pixel_size = 0.65 + use_qc = true + } + } + + then { + def ran = workflow.trace.succeeded().collect { it.name } + def names = { proc -> ran.findAll { it.contains(proc) } } + def write_done = taskTimes(metaDir, workDir, 'WRITE_FEATURES')*.end.max() + def qc_start = taskTimes(metaDir, workDir, 'QC_METRICS')*.start.min() + + assertAll( + { assert workflow.success }, + { assert names("NIMBUS").size() == 1 }, + { assert names("WRITE_FEATURES").size() == 1 }, + { assert names("WRITE_SEGMENTATIONS").size() == 1 }, + // The writes share the store's metadata, so QC must start after the last one. + { assert qc_start >= write_done }, + { assert new File("$outputDir/learned_features/sample_name_cellpose_nimbus.json").exists() }, + { assert path("$outputDir/pipeline_info/histo_software_versions.yml").text.contains('NIMBUS') } + ) + } + } + + test("two methods: a NIMBUS per method, one write") { + + when { + params { + outdir = "$outputDir" + use_nimbus = true + nimbus_channels = "DAPI" + pixel_size = 0.65 + use_instanseg = true + instanseg_channels = "DAPI" + } + } + + then { + def ran = workflow.trace.succeeded().collect { it.name } + def names = { proc -> ran.findAll { it.contains(proc) } } + + assertAll( + { assert workflow.success }, + { assert names("NIMBUS").size() == 2 }, + { assert names("WRITE_FEATURES").size() == 1 }, + { assert new File("$outputDir/learned_features/sample_name_cellpose_nimbus.json").exists() }, + { assert new File("$outputDir/learned_features/sample_name_instanseg_nimbus.json").exists() } + ) + } + } + + test("TMA: one NIMBUS per core") { + + when { + def data = "$baseDir/tests/stub_data" + def sheet = new File("$outputDir", "samplesheet.csv") + sheet.parentFile.mkdirs() + sheet.text = "sample,cycle_number,image_tiles,marker_sheet\n" + + "testslide,1,${data}/cycle01.ome.tiff,${data}/markers.csv\n" + + "testslide,2,${data}/cycle02.ome.tiff,${data}/markers.csv\n" + + params { + outdir = "$outputDir" + input = sheet.path + use_preprocessing = true + use_tma_dearray = true + tma_expected_cores = 4 + tma_core_diameter_mm = 1.5 + cellpose_channels = "DNA_6" + use_nimbus = true + pixel_size = 0.65 + } + } + + then { + def ran = workflow.trace.succeeded().collect { it.name } + def names = { proc -> ran.findAll { it.contains(proc) } } + + assertAll( + { assert workflow.success }, + // The Coreograph stub emits two cores; channels come from the marker sheet. + { assert names("NIMBUS").size() == 2 }, + { assert names("WRITE_FEATURES").size() == 2 }, + { assert names("MERGE_SPATIALDATA").size() == 1 }, + // One provenance file per core, not one overwritten by the other. + { assert new File("$outputDir/learned_features/testslide_core001_cellpose_nimbus.json").exists() }, + { assert new File("$outputDir/learned_features/testslide_core002_cellpose_nimbus.json").exists() } + ) + } + } + + test("use_nimbus off runs neither process") { + + when { + params { + outdir = "$outputDir" + } + } + + then { + def ran = workflow.trace.succeeded().collect { it.name } + + assertAll( + { assert workflow.success }, + { assert !ran.any { it.contains("NIMBUS") } }, + { assert !ran.any { it.contains("WRITE_FEATURES") } } + ) + } + } + + test("nimbus_channels naming a missing channel stops the run") { + + when { + def data = "$baseDir/tests/stub_data" + def sheet = new File("$outputDir", "samplesheet.csv") + sheet.parentFile.mkdirs() + sheet.text = "sample,cycle_number,image_tiles,marker_sheet\n" + + "testslide,1,${data}/cycle01.ome.tiff,${data}/markers.csv\n" + + "testslide,2,${data}/cycle02.ome.tiff,${data}/markers.csv\n" + + params { + outdir = "$outputDir" + input = sheet.path + use_preprocessing = true + cellpose_channels = "DNA_6" + use_nimbus = true + nimbus_channels = "ELANE,NOT_A_CHANNEL" + pixel_size = 0.65 + } + } + + then { + assertAll( + { assert workflow.failed }, + { assert workflow.stdout.any { it.contains("not in the marker sheet: NOT_A_CHANNEL") } || workflow.stderr.any { it.contains("not in the marker sheet: NOT_A_CHANNEL") } } + ) + } + } +} diff --git a/tests/nuclei_and_cells.nf.test b/tests/nuclei_and_cells.nf.test index f38f5f0..3e0e448 100644 --- a/tests/nuclei_and_cells.nf.test +++ b/tests/nuclei_and_cells.nf.test @@ -25,7 +25,7 @@ nextflow_pipeline { outdir = "$outputDir" use_cellpose = false use_instanseg = true - instanseg_pixel_size = 0.65 + pixel_size = 0.65 instanseg_channels = "DAPI" segment_nuclei = true } @@ -60,7 +60,7 @@ nextflow_pipeline { params { outdir = "$outputDir" use_instanseg = true - instanseg_pixel_size = 0.65 + pixel_size = 0.65 instanseg_channels = "DAPI" segment_nuclei = true } @@ -135,7 +135,7 @@ nextflow_pipeline { tma_core_diameter_mm = 1.5 use_cellpose = false use_instanseg = true - instanseg_pixel_size = 0.1 + pixel_size = 0.1 instanseg_channels = "DNA_6" segment_nuclei = true use_qc = true diff --git a/tests/pixel_size.nf.test b/tests/pixel_size.nf.test new file mode 100644 index 0000000..7d567de --- /dev/null +++ b/tests/pixel_size.nf.test @@ -0,0 +1,67 @@ +// pixel_size, with instanseg_pixel_size as its deprecated alias. + +nextflow_function { + + name "pixelSize" + script "../modules/local/utils.nf" + function "pixelSize" + tag "unit" + tag "validation" + + test("pixel_size is returned") { + when { + function { + """ + input[0] = [ pixel_size: 0.65 ] + """ + } + } + then { + assert function.success + assert function.result == 0.65 + } + } + + test("the deprecated alias is parsed to a number") { + when { + function { + """ + input[0] = [ instanseg_pixel_size: '0.65' ] + """ + } + } + then { + assert function.success + assert function.result instanceof Number + assert function.result == 0.65 + } + } + + test("both set and different fails") { + when { + function { + """ + input[0] = [ pixel_size: 0.5, instanseg_pixel_size: 0.65 ] + """ + } + } + then { + assert function.failed + assert function.stdout.any { it.contains("differ; set only pixel_size") } + } + } + + test("neither set gives null") { + when { + function { + """ + input[0] = [:] + """ + } + } + then { + assert function.success + assert function.result == null + } + } +} diff --git a/tests/segmentation_specs.nf.test b/tests/segmentation_specs.nf.test index 25022a6..92ee0f6 100644 --- a/tests/segmentation_specs.nf.test +++ b/tests/segmentation_specs.nf.test @@ -160,7 +160,7 @@ nextflow_function { """ input[0] = [ use_cellpose: true, cellpose_channels: 'DAPI', flow_threshold: '0.4', cellprob_threshold: '-6', min_area_pixels2: '20', clip_limit: '0.2', clahe_kernel_size: '8', gaussian_sigma: '1', - use_instanseg: true, instanseg_channels: 'DAPI', instanseg_pixel_size: '0.65' ] + use_instanseg: true, instanseg_channels: 'DAPI', pixel_size: '0.65' ] """ } } diff --git a/tests/stub_data/markers_virtues.csv b/tests/stub_data/markers_virtues.csv new file mode 100644 index 0000000..ae2e7c7 --- /dev/null +++ b/tests/stub_data/markers_virtues.csv @@ -0,0 +1,5 @@ +channel_number,cycle_number,marker_name,channel_role,channel_compartment,uniprot_id +1,1,DNA_6,dna,nuclear, +2,1,ELANE,marker,cytoplasm,P08246 +3,2,DNA_7,dna,nuclear, +4,2,CD11B,marker,membrane,P11215 diff --git a/tests/tma.nf.test b/tests/tma.nf.test index cc4a963..cd79ae6 100644 --- a/tests/tma.nf.test +++ b/tests/tma.nf.test @@ -75,7 +75,7 @@ nextflow_pipeline { tma_core_diameter_mm = 1.5 cellpose_channels = "DNA_6" use_instanseg = true - instanseg_pixel_size = 0.1 + pixel_size = 0.1 instanseg_channels = "DNA_6" use_qc = true } diff --git a/tests/two_methods.nf.test b/tests/two_methods.nf.test index c6624e4..cf578d8 100644 --- a/tests/two_methods.nf.test +++ b/tests/two_methods.nf.test @@ -16,7 +16,7 @@ nextflow_pipeline { params { outdir = "$outputDir" use_instanseg = true - instanseg_pixel_size = 0.65 + pixel_size = 0.65 instanseg_channels = "DAPI" } } @@ -63,7 +63,7 @@ nextflow_pipeline { params { outdir = "$outputDir" use_instanseg = true - instanseg_pixel_size = 0.65 + pixel_size = 0.65 instanseg_channels = "DAPI" cellpose_kwargs = "{'niter': 10}" instanseg_kwargs = "{'batch_size': 2}" @@ -87,7 +87,7 @@ nextflow_pipeline { params { outdir = "$outputDir" use_instanseg = true - instanseg_pixel_size = 0.65 + pixel_size = 0.65 instanseg_channels = "DAPI" use_qc = false } diff --git a/tests/unit/qc/test_qc_metrics.py b/tests/unit/qc/test_qc_metrics.py index 262c6bc..ede5230 100644 --- a/tests/unit/qc/test_qc_metrics.py +++ b/tests/unit/qc/test_qc_metrics.py @@ -5,6 +5,8 @@ with something that actually happened rather than with a number someone invented. """ +import json + import numpy as np import pytest from qc_metrics import ( @@ -17,6 +19,9 @@ cycle_ratio_metrics, effective_bit_depth, linking_metrics, + nimbus_metrics, + read_uns, + virtues_metrics, nuclear_cycle_pair, patch_metrics, percentiles_from_histogram, @@ -634,3 +639,55 @@ def test_json_serialisable(self): import json json.dumps(linking_metrics(np.array([1]), np.array([1.0]), np.int64(0))) + + +class TestNimbusMetrics: + def test_fraction_and_median(self): + out = nimbus_metrics(np.array([[0.1], [0.6], [0.9]], dtype=np.float32), ["CD3"]) + assert out["CD3"]["fraction_positive"] == pytest.approx(2 / 3) + assert out["CD3"]["median"] == pytest.approx(0.6) + + def test_nan_cells_are_ignored(self): + out = nimbus_metrics(np.array([[0.9], [np.nan], [0.1]], dtype=np.float32), ["CD3"]) + assert out["CD3"]["fraction_positive"] == 0.5 + + def test_all_nan_marker_is_none(self): + X = np.array([[np.nan, 0.7], [np.nan, 0.2]], dtype=np.float32) + out = nimbus_metrics(X, ["A", "B"]) + assert out["A"] == {"fraction_positive": None, "median": None} + assert out["B"]["fraction_positive"] == 0.5 + + +VIRTUES_UNS = { + "channels": {"CD3": "P1", "PanCK": "P2"}, + "unembedded": ["DAPI"], + "stats": {"CD3": {"uniprot_id": "P1", "cap": 1.5, "mean": 0.1, "sd": 0.2, "tissue_pixels": 9}}, + "n_cells": {"cellpose": 5}, + "n_cells_without_pixel": {"cellpose": 1}, + "n_niches_kept": 3, + "n_niches_dropped": 2, +} + + +class TestVirtuesMetrics: + def test_picks_the_method(self): + out = virtues_metrics(VIRTUES_UNS, "cellpose") + assert out["channels"] == ["CD3", "PanCK"] + assert out["unembedded"] == ["DAPI"] + assert out["stats"]["CD3"]["cap"] == 1.5 + assert (out["n_cells"], out["n_cells_without_pixel"]) == (5, 1) + assert (out["n_niches_kept"], out["n_niches_dropped"]) == (3, 2) + + def test_json_serialisable(self): + json.dumps(virtues_metrics(VIRTUES_UNS, "cellpose")) + + def test_read_uns_round_trips_an_anndata_zarr(self, tmp_path): + import anndata as ad + import zarr + + a = ad.AnnData(np.zeros((2, 2), dtype=np.float16)) + a.uns["virtues"] = {**VIRTUES_UNS, "n_cells": {"cellpose": np.int64(5)}, "unembedded": ["DAPI", "X"]} + a.write_zarr(tmp_path / "t.zarr") + got = read_uns(zarr.open_group(str(tmp_path / "t.zarr"), mode="r")["uns"]["virtues"]) + assert got["unembedded"] == ["DAPI", "X"] + assert virtues_metrics(got, "cellpose")["n_cells"] == 5 diff --git a/tests/unit/qc/test_qc_report.py b/tests/unit/qc/test_qc_report.py index f746b92..50cb1e0 100644 --- a/tests/unit/qc/test_qc_report.py +++ b/tests/unit/qc/test_qc_report.py @@ -334,6 +334,38 @@ def test_linking_is_shown_with_nuclei(self): def test_no_linking_section_without_nuclei(self): assert "Nuclei per cell" not in build(minimal_metrics()) + def test_nimbus_section_lists_markers(self): + m = minimal_metrics() + m["nimbus"] = { + "CD3": {"fraction_positive": 0.25, "median": 0.3}, + "PanCK": {"fraction_positive": None, "median": None}, + } + page = build(m) + assert "Nimbus" in page + assert "CD325.0%0.30" in page + assert "PanCKn/an/a" in page + + def test_no_nimbus_section_without_the_key(self): + page = build(minimal_metrics()) + assert "Nimbus" not in page + + def test_virtues_section_present_only_with_the_key(self): + m = minimal_metrics() + assert "VirTues" not in build(m) + m["virtues"] = { + "channels": ["CD3"], + "unembedded": ["DAPI"], + "stats": {"CD3": {"uniprot_id": "P1", "cap": 1.5, "mean": 0.1, "sd": 0.2, "tissue_pixels": 9000}}, + "n_cells": 5, + "n_cells_without_pixel": 1, + "n_niches_kept": 3, + "n_niches_dropped": 2, + } + page = build(m) + assert "VirTues" in page + assert "CD3P1" in page + assert "Channels not embedded: DAPI" in page + def test_hero_number_is_present_unabbreviated(self): """The one number the page leads with is exact, not compacted.""" m = minimal_metrics() diff --git a/tests/unit/test_build_sif.py b/tests/unit/test_build_sif.py new file mode 100644 index 0000000..c75f394 --- /dev/null +++ b/tests/unit/test_build_sif.py @@ -0,0 +1,305 @@ +"""Tests for tools/build_sif.sbatch, run with a fake `apptainer` on PATH that records its calls.""" + +import io +import json +import os +import re +import shutil +import subprocess +import sys +import tarfile +from pathlib import Path + +import pytest +from container_manifest import cache_filename + +SCRIPT = Path(__file__).resolve().parents[2] / "tools" / "build_sif.sbatch" +JOB = "4242" + +FAKE = f"""#!{sys.executable} +import json, os, sys +from pathlib import Path +args = sys.argv[1:] +with open(os.environ["FAKE_LOG"], "a") as fh: + fh.write(json.dumps({{"argv": args, "tmpdir": os.environ.get("APPTAINER_TMPDIR"), + "cachedir": os.environ.get("APPTAINER_CACHEDIR"), + "s_tmpdir": os.environ.get("SINGULARITY_TMPDIR"), + "s_cachedir": os.environ.get("SINGULARITY_CACHEDIR")}}) + "\\n") +if args == ["--version"]: + print("apptainer version 1.4.0-fake"); sys.exit(0) +if args[:2] == ["build", "--help"]: + print("--mksquashfs-args string extra arguments to pass to mksquashfs"); sys.exit(0) +if args[0] == "build": + pos = [a for i, a in enumerate(args[1:], 1) if not a.startswith("-") and args[i - 1] != "--mksquashfs-args"] + out = Path(pos[0]) + counter = Path(os.environ["FAKE_LOG"] + ".builds") + n = int(counter.read_text()) + 1 if counter.exists() else 1 + counter.write_text(str(n)) + if os.environ.get("FAKE_FAIL_ALWAYS") or n <= int(os.environ.get("FAKE_FAIL_FIRST", "0")): + out.write_text("half-written") + print("FATAL: fake network error", file=sys.stderr); sys.exit(255) + out.write_text("SIF_MAGIC fake image " + os.environ.get("FAKE_CONTENT", "")) + if os.environ.get("FAKE_RACE"): # a parallel job finishes first + Path(os.environ["FAKE_RACE"]).write_text("theirs") +sys.exit(0) +""" + + +@pytest.fixture +def env(tmp_path): + fakebin = tmp_path / "bin" + fakebin.mkdir() + fake = fakebin / "apptainer" + fake.write_text(FAKE) + fake.chmod(0o755) + keep = {k: v for k, v in os.environ.items() if k in ("PATH", "LANG", "LC_ALL")} + return { + **keep, + "PATH": f"{fakebin}:{keep['PATH']}", + "USER": "tester", + "HOME": str(tmp_path / "home"), + "TMPDIR": str(tmp_path / "tmpbase"), + "APPTAINER_CACHEDIR": str(tmp_path / "cache"), + "SLURM_JOB_ID": JOB, + "SLURM_CPUS_PER_TASK": "16", + "SLURM_MEM_PER_NODE": "32768", + "BUILD_SIF_RETRY_SLEEP": "0", + "FAKE_LOG": str(tmp_path / "calls.jsonl"), + } + + +BASH = shutil.which("bash") + + +def run(env, *args, cwd, **overrides): + cmd = [BASH, str(SCRIPT), "--need-gb", "0", *args] + return subprocess.run(cmd, env={**env, **overrides}, cwd=cwd, capture_output=True, text=True) # noqa: S603 our script, test args + + +def calls(env): + log = Path(env["FAKE_LOG"]) + return [json.loads(line) for line in log.read_text().splitlines()] if log.exists() else [] + + +def builds(env): + return [c for c in calls(env) if c["argv"][0] == "build" and c["argv"][1:] != ["--help"]] + + +def make_tar(path, members): + with tarfile.open(path, "w") as tar: + for name, data in members.items(): + info = tarfile.TarInfo(name) + info.size = len(data) + tar.addfile(info, io.BytesIO(data)) + return path + + +def test_registry_builds_docker_ref_with_nextflow_name(env, tmp_path): + out = tmp_path / "out" + r = run(env, "docker.io/josenimo/nimbus:0.0.5", str(out), cwd=tmp_path) + assert r.returncode == 0, r.stderr + sif = out / "docker.io-josenimo-nimbus-0.0.5.img" + assert sif.read_text().startswith("SIF_MAGIC") + (b,) = builds(env) + assert b["argv"][-1] == "docker://docker.io/josenimo/nimbus:0.0.5" + assert b["argv"][1:3] == ["--mksquashfs-args", "-processors 16 -mem 16384M"] + assert b["tmpdir"] == str(tmp_path / "tmpbase" / f"build_sif.{JOB}") + assert not Path(b["tmpdir"]).exists(), "job temp dir is cleaned up" + assert [p.name for p in out.iterdir()] == [sif.name], "no partial file left behind" + assert f'rsync -av --ignore-existing {sif} "$NXF_SINGULARITY_CACHEDIR/"' in r.stdout + assert "sha256:" in r.stdout + + +@pytest.mark.parametrize( + "ref", + [ + "docker.io/josenimo/nimbus:0.0.5", + "docker://ghcr.io/schapirolabor/background_subtraction:v0.5.1", + "quay.io/biocontainers/ashlar:1.19.0--pyhdfd78af_0", + ], +) +def test_name_matches_container_manifest(env, tmp_path, ref): + """Same rule as tools/container_manifest.py, which mirrors Nextflow's SingularityCache.""" + out = tmp_path / "out" + assert run(env, ref, str(out), cwd=tmp_path).returncode == 0 + assert (out / cache_filename(ref.removeprefix("docker://"))).exists() + + +def test_untagged_ref_refused(env, tmp_path): + r = run(env, "docker.io/josenimo/nimbus", str(tmp_path / "out"), cwd=tmp_path) + assert r.returncode != 0 and "no tag" in r.stderr + assert builds(env) == [] + + +def test_docker_save_tar_uses_docker_archive(env, tmp_path): + # Docker 25+ writes index.json and oci-layout too; manifest.json must still win. + tar = make_tar( + tmp_path / "nimbus.tar", + {"manifest.json": b"[]", "index.json": b"{}", "oci-layout": b"{}", "repositories": b"{}"}, + ) + out = tmp_path / "out" + r = run(env, "--name", "docker.io-josenimo-nimbus-0.0.5.img", str(tar), str(out), cwd=tmp_path) + assert r.returncode == 0, r.stderr + (b,) = builds(env) + assert b["argv"][-1] == f"docker-archive://{tar.resolve()}" + assert (out / "docker.io-josenimo-nimbus-0.0.5.img").exists() + + +def test_oci_archive_tar_uses_oci_archive(env, tmp_path): + # Misleading extension on purpose: the contents decide. + tar = make_tar(tmp_path / "image.docker.tar", {"./oci-layout": b"{}", "./index.json": b"{}"}) + r = run(env, "--name", "x.img", str(tar), str(tmp_path / "out"), cwd=tmp_path) + assert r.returncode == 0, r.stderr + assert builds(env)[0]["argv"][-1] == f"oci-archive://{tar.resolve()}" + + +def test_oci_layout_dir_uses_oci(env, tmp_path): + layout = tmp_path / "layout" + (layout / "blobs" / "sha256").mkdir(parents=True) + (layout / "oci-layout").write_text("{}") + (layout / "index.json").write_text("{}") + r = run(env, "--name", "x.img", str(layout), str(tmp_path / "out"), cwd=tmp_path) + assert r.returncode == 0, r.stderr + assert builds(env)[0]["argv"][-1] == f"oci://{layout.resolve()}" + + +def test_local_source_needs_name(env, tmp_path): + tar = make_tar(tmp_path / "nimbus.tar", {"manifest.json": b"[]"}) + r = run(env, str(tar), str(tmp_path / "out"), cwd=tmp_path) + assert r.returncode != 0 and "--name is required" in r.stderr + assert builds(env) == [] + + +def test_unknown_tar_refused(env, tmp_path): + tar = make_tar(tmp_path / "random.tar", {"hello.txt": b"hi"}) + r = run(env, "--name", "x.img", str(tar), str(tmp_path / "out"), cwd=tmp_path) + assert r.returncode != 0 and "neither manifest.json" in r.stderr + assert builds(env) == [] + + +def test_existing_sif_is_a_noop(env, tmp_path): + sif = tmp_path / "already.sif" + sif.write_bytes(b"#!/usr/bin/env run-singularity\n\x00SIF_MAGIC\x00rest") + r = run(env, str(sif), str(tmp_path / "out"), cwd=tmp_path) + assert r.returncode == 0 and "nothing to build" in r.stdout + assert builds(env) == [] + + +def test_refuses_overwrite_without_force(env, tmp_path): + out = tmp_path / "out" + out.mkdir() + existing = out / "docker.io-josenimo-nimbus-0.0.5.img" + existing.write_text("old") + r = run(env, "docker.io/josenimo/nimbus:0.0.5", str(out), cwd=tmp_path) + assert r.returncode != 0 and "already exists" in r.stderr and "--force" in r.stderr + assert existing.read_text() == "old" + assert builds(env) == [] + + env["FAKE_CONTENT"] = "new" + r = run(env, "--force", "docker.io/josenimo/nimbus:0.0.5", str(out), cwd=tmp_path) + assert r.returncode == 0, r.stderr + assert existing.read_text().endswith("new") + + +def test_failed_build_leaves_no_file(env, tmp_path): + env["FAKE_FAIL_ALWAYS"] = "1" + env["BUILD_SIF_ATTEMPTS"] = "2" + out = tmp_path / "out" + r = run(env, "docker.io/josenimo/nimbus:0.0.5", str(out), cwd=tmp_path) + assert r.returncode != 0 + assert "failed 2 times for docker://docker.io/josenimo/nimbus:0.0.5" in r.stderr + assert len(builds(env)) == 2 + assert list(out.iterdir()) == [], "neither the final name nor a partial file" + assert not (tmp_path / "tmpbase" / f"build_sif.{JOB}").exists() + + +def test_failed_local_build_leaves_no_file(env, tmp_path): + env["FAKE_FAIL_ALWAYS"] = "1" + tar = make_tar(tmp_path / "nimbus.tar", {"manifest.json": b"[]"}) + out = tmp_path / "out" + r = run(env, "--name", "x.img", str(tar), str(out), cwd=tmp_path) + assert r.returncode != 0 and "apptainer build failed" in r.stderr + assert len(builds(env)) == 1, "no retries for a local source" + assert list(out.iterdir()) == [] + + +def test_registry_retries_transient_failure(env, tmp_path): + env["FAKE_FAIL_FIRST"] = "2" + out = tmp_path / "out" + r = run(env, "docker.io/josenimo/nimbus:0.0.5", str(out), cwd=tmp_path) + assert r.returncode == 0, r.stderr + assert len(builds(env)) == 3 + assert "attempt 2 of 4 failed" in r.stdout + assert (out / "docker.io-josenimo-nimbus-0.0.5.img").read_text().startswith("SIF_MAGIC") + + +def test_default_out_dir_is_nxf_cache(env, tmp_path): + cache = tmp_path / "shared_cache" + env["NXF_SINGULARITY_CACHEDIR"] = str(cache) + r = run(env, "docker.io/josenimo/nimbus:0.0.5", cwd=tmp_path) + assert r.returncode == 0, r.stderr + assert [p.name for p in cache.iterdir()] == ["docker.io-josenimo-nimbus-0.0.5.img"] + assert "(shared cache)" in r.stdout and "rsync" not in r.stdout + + +def test_cache_image_never_replaced(env, tmp_path): + cache = tmp_path / "shared_cache" + cache.mkdir() + existing = cache / "docker.io-josenimo-nimbus-0.0.5.img" + existing.write_text("old") + env["NXF_SINGULARITY_CACHEDIR"] = str(cache) + r = run(env, "--force", "docker.io/josenimo/nimbus:0.0.5", cwd=tmp_path) + assert r.returncode != 0 and "already in the cache" in r.stderr + assert existing.read_text() == "old" + assert builds(env) == [] + + +def test_cache_image_appearing_mid_build_is_kept(env, tmp_path): + cache = tmp_path / "shared_cache" + theirs = cache / "docker.io-josenimo-nimbus-0.0.5.img" + env["NXF_SINGULARITY_CACHEDIR"] = str(cache) + r = run(env, "--force", "docker.io/josenimo/nimbus:0.0.5", cwd=tmp_path, FAKE_RACE=str(theirs)) + assert r.returncode != 0 and "appeared during the build" in r.stderr + assert [p.name for p in cache.iterdir()] == [theirs.name], "no partial file left behind" + assert theirs.read_text() == "theirs" + + +def test_temp_dirs_kept_out_of_cache(env, tmp_path): + cache = tmp_path / "shared_cache" + cache.mkdir() + env["NXF_SINGULARITY_CACHEDIR"] = str(cache) + r = run(env, "docker.io/josenimo/nimbus:0.0.5", str(cache / "sub"), cwd=tmp_path) + assert r.returncode != 0 and "below the cache" in r.stderr + for var, value in (("TMPDIR", cache), ("APPTAINER_CACHEDIR", cache / "sub")): + r = run( + env, "docker.io/josenimo/nimbus:0.0.5", str(tmp_path / "out"), cwd=tmp_path, **{var: str(value)} + ) + assert r.returncode != 0 and "is inside the cache" in r.stderr, var + assert list(cache.iterdir()) == [] + assert builds(env) == [] + + +def test_apptainer_tmpdir_wins_and_singularity_vars_match(env, tmp_path): + env["APPTAINER_TMPDIR"] = str(tmp_path / "apptmp") + env["SINGULARITY_TMPDIR"] = str(tmp_path / "other") # stale value from the user's shell + assert run(env, "docker.io/josenimo/nimbus:0.0.5", str(tmp_path / "out"), cwd=tmp_path).returncode == 0 + (b,) = builds(env) + assert b["tmpdir"] == b["s_tmpdir"] == str(tmp_path / "apptmp" / f"build_sif.{JOB}") + assert b["cachedir"] == b["s_cachedir"] == str(tmp_path / "cache") + + +def test_slurm_log_goes_to_default_cache_logs(): + """#SBATCH lines cannot read variables, so the log path is spelled out twice.""" + text = SCRIPT.read_text() + (cache,) = re.findall(r"^default_cache=(\S+)$", text, re.MULTILINE) + for stream in ("output", "error"): + assert f"#SBATCH --{stream}={cache}/logs/%x.%j.log" in text.splitlines() + + +def test_credentials_never_printed(env, tmp_path): + env["APPTAINER_DOCKER_USERNAME"] = "someuser" + env["APPTAINER_DOCKER_PASSWORD"] = "s3cr3t-token" # noqa: S105 fake value + r = run(env, "docker.io/josenimo/nimbus:0.0.5", str(tmp_path / "out"), cwd=tmp_path) + assert r.returncode == 0, r.stderr + assert "s3cr3t-token" not in r.stdout + r.stderr + assert "someuser" not in r.stdout + r.stderr diff --git a/tests/unit/test_marker_schema.py b/tests/unit/test_marker_schema.py new file mode 100644 index 0000000..c4f73ab --- /dev/null +++ b/tests/unit/test_marker_schema.py @@ -0,0 +1,20 @@ +"""The marker sheet's uniprot_id pattern accepts accessions and rejects gene names.""" + +import json +import re +from pathlib import Path + +import pytest + +SCHEMA = Path(__file__).resolve().parents[2] / "assets/schema_marker.json" +PATTERN = json.loads(SCHEMA.read_text())["items"]["properties"]["uniprot_id"]["pattern"] + + +@pytest.mark.parametrize("value", ["P08575", "P08575-8", "A0A024R161", "Q9Y6K9"]) +def test_accepts_accession(value): + assert re.fullmatch(PATTERN, value) + + +@pytest.mark.parametrize("value", ["CD3", "ELANE", "p08575", "P08575-", "P0857"]) +def test_rejects_non_accession(value): + assert not re.fullmatch(PATTERN, value) diff --git a/tests/unit/test_merge_spatialdata.py b/tests/unit/test_merge_spatialdata.py index 5ad43b0..0e20444 100644 --- a/tests/unit/test_merge_spatialdata.py +++ b/tests/unit/test_merge_spatialdata.py @@ -56,11 +56,16 @@ def test_unknown_region_refused(self): with pytest.raises(ValueError, match="not found"): retarget_table(FakeTable("some_other_element"), {"b": "c1__b"}, "c1") - def test_missing_attrs_refused(self): + def test_unannotated_table_copied_unchanged(self): t = FakeTable("b") t.uns = {} - with pytest.raises(ValueError, match="spatialdata_attrs"): - retarget_table(t, {"b": "c1__b"}, "c1") + assert retarget_table(t, {"b": "c1__b"}, "c1") is t + assert t.uns == {} + + def test_table_with_no_region_unchanged(self): + t = FakeTable("b") + t.uns = {"spatialdata_attrs": {"region": None}} + assert retarget_table(t, {}, "c1").uns == {"spatialdata_attrs": {"region": None}} class TestMergeTwoTablesInOneCore: @@ -106,6 +111,52 @@ def test_both_tables_survive_retargeted(self, tmp_path): assert set(t.obs["region"]) == {want} +class TestMergeLearnedFeaturesTable: + def test_nimbus_table_keeps_uns_and_is_retargeted(self, tmp_path): + sd = pytest.importorskip("spatialdata", reason="merge() needs spatialdata") + import anndata as ad + import geopandas as gpd + import numpy as np + from merge_spatialdata import merge + from shapely.geometry import Point + from spatialdata.models import Image2DModel, ShapesModel, TableModel + + core, n = "slide_c1", 3 + prov = { + "channels": ["CD45", "FOXP3"], + "factors": {"CD45": 1.5, "FOXP3": 2.5}, + "halo": 96, + "test_time_aug": True, + } + sdata = sd.SpatialData() + sdata[core] = Image2DModel.parse(np.zeros((1, 8, 8), dtype="uint16"), dims=("c", "y", "x")) + gdf = gpd.GeoDataFrame(geometry=[Point(i, i) for i in range(n)]) + gdf["radius"] = 1.0 + sdata["m_cells"] = ShapesModel.parse(gdf) + for name in ("m_table", "m_nimbus"): + adata = ad.AnnData(np.ones((n, 2), dtype="float32")) + adata.obs["region"] = "m_cells" + adata.obs["cell_id"] = np.arange(n) + if name == "m_nimbus": + adata.uns["nimbus"] = prov + sdata[name] = TableModel.parse( + adata, region="m_cells", region_key="region", instance_key="cell_id" + ) + core_dir = tmp_path / f"{core}.zarr" + sdata.write(core_dir) + + out = tmp_path / "merged.zarr" + merge(out, [core_dir]) + t = sd.read_zarr(out).tables[f"{core}{SEP}m_nimbus"] + + want = f"{core}{SEP}m_cells" + assert t.uns["spatialdata_attrs"]["region"] == want + assert set(t.obs["region"]) == {want} + assert list(t.uns["nimbus"]["channels"]) == prov["channels"] + assert dict(t.uns["nimbus"]["factors"]) == prov["factors"] + assert t.uns["nimbus"]["halo"] == 96 + + class TestElementNaming: """The rule that keeps core identity visible without doubling it.""" @@ -126,3 +177,25 @@ def test_names_stay_unique_across_cores(self): out = [self.new_name(c, n) for c in cores for n in names] out += [self.new_name(c, c) for c in cores] assert len(set(out)) == len(out) + + +def test_tissue_table_renamed_per_core(tmp_path): + sd = pytest.importorskip("spatialdata", reason="merge() needs spatialdata") + import anndata as ad + import numpy as np + from merge_spatialdata import merge + from spatialdata.models import Image2DModel, TableModel + + cores = [] + for core in ("slide_c1", "slide_c2"): + sdata = sd.SpatialData() + sdata[core] = Image2DModel.parse(np.zeros((1, 8, 8), dtype="uint16"), dims=("c", "y", "x")) + adata = ad.AnnData(np.ones((1, 2), dtype="float32"), obs=pd.DataFrame(index=["tissue_0"])) + sdata["virtues_tissue"] = TableModel.parse(adata) + cores.append(tmp_path / f"{core}.zarr") + sdata.write(cores[-1]) + + out = tmp_path / "merged.zarr" + merge(out, cores) + merged = sd.read_zarr(out) + assert sorted(merged.tables) == [f"slide_c1{SEP}virtues_tissue", f"slide_c2{SEP}virtues_tissue"] diff --git a/tests/unit/test_nimbus_cells.py b/tests/unit/test_nimbus_cells.py new file mode 100644 index 0000000..299c7ac --- /dev/null +++ b/tests/unit/test_nimbus_cells.py @@ -0,0 +1,291 @@ +"""Tiled Nimbus runner core, tested with a fake model.""" + +import math + +import numpy as np +import pytest +from shapely.geometry import Polygon, box + +import nimbus_cells as nc + +MARGIN = 8 + + +def identity(_ch, x, _lab): + return x + + +def grid_cells(n=6, step=20, size=10, x_off=0, y_off=0): + geoms = [ + box(x_off + i * step, y_off + j * step, x_off + i * step + size, y_off + j * step + size) + for j in range(n) + for i in range(n) + ] + return geoms, np.arange(1, len(geoms) + 1) + + +def run(image, geoms, labels, factors, predict=identity, tile=64, min_window=0, names=None): + names = names or [f"c{i}" for i in range(image.shape[0])] + return nc.score_cells(image, geoms, labels, names, factors, predict, tile, MARGIN, min_window) + + +def test_every_cell_scored_once_for_any_tile_size(): + rng = np.random.default_rng(0) + image = rng.integers(1, 100, size=(2, 200, 200)).astype(np.float32) + geoms, labels = grid_cells() + factors = {"c0": 50.0, "c1": 80.0} + results = [run(image, geoms, labels, factors, tile=t) for t in (64, 100, 4096)] + for r in results: + assert r.shape == (36, 2) and r.dtype == np.float32 + assert not np.isnan(r).any() + np.testing.assert_allclose(results[0], results[2], atol=1e-6) + np.testing.assert_allclose(results[1], results[2], atol=1e-6) + + +def test_border_window_shifted_inward_to_min_window(): + bounds = np.array([[950.0, 950.0, 990.0, 990.0], [10.0, 10.0, 40.0, 40.0]]) + centroids = np.array([[970.0, 970.0], [25.0, 25.0]]) + tiles = nc.assign_tiles(centroids, 300) + wins = nc.tile_windows(bounds, tiles, 300, 8, 600, (1000, 1000)) + assert len(wins) == 2 + for y0, y1, x0, x1 in wins.values(): + assert y1 - y0 >= 600 and x1 - x0 >= 600 + assert y0 >= 0 and y1 <= 1000 and x0 >= 0 and x1 <= 1000 + + +def test_window_smaller_than_min_when_image_is(): + bounds = np.array([[10.0, 10.0, 40.0, 40.0]]) + tiles = nc.assign_tiles(np.array([[25.0, 25.0]]), 300) + wins = nc.tile_windows(bounds, tiles, 300, 8, 600, (400, 400)) + assert list(wins.values()) == [(0, 400, 0, 400)] + + +def test_cell_on_image_border_is_whole(): + image = np.zeros((1, 40, 40), dtype=np.float32) + image[0, 5:15, 0:10] = 0.5 + geoms = [box(0, 5, 10, 15)] + out = run(image, geoms, np.array([1]), {"c0": 1.0}, tile=16) + # polygon() includes boundary pixels: the box covers 11x11 px, 100 of them 0.5 (50/121) + assert out[0, 0] == pytest.approx(50 / 121) + + +def test_window_contains_neighbours(): + geoms = [box(10, 10, 20, 20), box(70, 10, 80, 20)] # second owned by next tile + labels = np.array([1, 2]) + tiles = nc.assign_tiles(np.array([[15.0, 15.0], [75.0, 15.0]]), 64) + assert tiles.tolist() == [[0, 0], [1, 0]] + bounds = np.array([g.bounds for g in geoms]) + wins = nc.tile_windows(bounds, tiles, 64, 16, 0, (200, 200)) + lab = nc.label_window(geoms, labels, wins[(0, 0)]) + assert lab.dtype == np.int32 + assert set(np.unique(lab)) == {0, 1, 2} + + +def test_every_window_gets_the_store_factor(): + rng = np.random.default_rng(1) + image = rng.integers(0, 200, size=(1, 200, 200)).astype(np.float32) + geoms, labels = grid_cells() + seen = [] + + def record(_ch, x, _lab): + seen.append(x.copy()) + return x + + run(image, geoms, labels, {"c0": 100.0}, predict=record, tile=64) + assert len(seen) > 1 + for x in seen: + assert x.max() <= 1.0 and x.min() >= 0.0 + # recover the raw window by locating it: values are raw/100 clipped, so all lie on that grid + raw = x * 100.0 + assert np.allclose(raw[x < 1.0], np.round(raw[x < 1.0]), atol=1e-3) + full = np.clip(image[0] / 100.0, 0, 1) + assert max(x.max() for x in seen) == pytest.approx(full.max()) + + +def test_missing_factor_raises(): + image = np.ones((2, 100, 100), dtype=np.float32) + geoms, labels = grid_cells(2) + with pytest.raises(KeyError): + run(image, geoms, labels, {"c0": 1.0}) + + +def test_normalisation_deterministic_and_nonzero_only(): + rng = np.random.default_rng(2) + img = rng.integers(0, 50, size=(1, 300, 300)).astype(np.float32) + img[0, :150] = 0 + a = nc.normalisation_factors(img, ["c0"]) + b = nc.normalisation_factors(img, ["c0"]) + assert a == b + nz = img[0][img[0] > 0] + assert a["c0"] == pytest.approx(float(np.quantile(nz, nc.QUANTILE))) + + +def test_empty_channel_is_nan_column(): + rng = np.random.default_rng(3) + image = np.stack([rng.integers(1, 9, size=(100, 100)), np.zeros((100, 100))]).astype(np.float32) + factors = nc.normalisation_factors(image, ["c0", "c1"]) + assert factors["c1"] is None + calls = [] + + def predict(ch, x, _lab): + calls.append(ch) + return x + + geoms, labels = grid_cells(3) + out = run(image, geoms, labels, factors, predict=predict) + assert set(calls) == {"c0"} + assert np.isnan(out[:, 1]).all() and np.isfinite(out[:, 0]).all() + + +def test_cell_without_pixel_centre_is_nan(): + image = np.ones((1, 50, 50), dtype=np.float32) + geoms = [box(10, 10, 20, 20), box(30.1, 30.1, 30.3, 30.3)] + out = run(image, geoms, np.array([1, 2]), {"c0": 1.0}) + assert out[0, 0] == pytest.approx(1.0) and np.isnan(out[1, 0]) + + +def test_image_px_ceils(): + assert nc.image_px(2048, 0.65) == 3151 + + +def test_model_um_per_px_drives_scale_image_px_and_magnification(monkeypatch): + ps = 0.65 + before = (nc.resize_scale(ps), nc.image_px(2048, ps), nc.magnification(ps)) + assert before == pytest.approx((0.65, math.ceil(2048 / 0.65), 10 / 0.65)) + monkeypatch.setattr(nc, "MODEL_UM_PER_PX", 0.5) + scale, px, mag = nc.resize_scale(ps), nc.image_px(2048, ps), nc.magnification(ps) + assert scale == pytest.approx(1.3) + assert px == math.ceil(2048 * 0.5 / 0.65) + # magnification and resize scale stay inverse: model magnification = mag * scale + assert mag == pytest.approx(10 * 0.5 / ps) + assert mag * scale == pytest.approx(nc.MODEL_MAGNIFICATION) + + +def box_blur(x, r): + from scipy.ndimage import uniform_filter + + return uniform_filter(x, size=2 * r + 1, mode="nearest") + + +def test_margin_gives_whole_image_result_and_zero_margin_does_not(): + rng = np.random.default_rng(4) + image = rng.integers(1, 100, size=(1, 200, 200)).astype(np.float32) + # cells straddle tile edges at 64 and 100 + geoms, labels = grid_cells(8, step=24, size=12, x_off=3, y_off=3) + factors = {"c0": 60.0} + r = 6 + + def blur(_ch, x, _lab): + return box_blur(x, r) + + names = ["c0"] + # a single window that holds everything is the whole-image reference + ref = nc.score_cells(image, geoms, labels, names, factors, blur, 4096, 0, 0) + for tile in (64, 100): + tiled = nc.score_cells(image, geoms, labels, names, factors, blur, tile, r + 1, 0) + np.testing.assert_allclose(tiled, ref, atol=1e-6) + short = nc.score_cells(image, geoms, labels, names, factors, blur, tile, 0, 0) + assert np.abs(short - ref).max() > 1e-4 + + +def test_empty_and_none_geoms_are_skipped(): + image = np.ones((1, 60, 60), dtype=np.float32) + geoms = [box(10, 10, 20, 20), None, Polygon(), box(30, 30, 40, 40)] + out = run(image, geoms, np.array([1, 2, 3, 4]), {"c0": 1.0}) + assert out.shape == (4, 1) + assert np.isnan(out[[1, 2], 0]).all() + assert out[[0, 3], 0] == pytest.approx([1.0, 1.0]) + + +def make_store(tmp_path, region="m_cells"): + import anndata as ad + import geopandas as gpd + import pandas as pd + import spatialdata as sd + from spatialdata.models import Image2DModel, ShapesModel, TableModel + + data = np.full((2, 80, 80), 1, dtype=np.uint16) + for (lo, hi), v in zip(((5, 15), (30, 40), (55, 65)), (100, 200, 300), strict=False): # c1, c2, c3 + data[0, lo:hi, lo:hi] = v + data[1, lo:hi, lo:hi] = v // 10 + image = Image2DModel.parse( + data, + dims=("c", "y", "x"), + c_coords=["CD45", "FOXP3"], + scale_factors=[2], # multiscale, as sopa stores it + ) + ids = ["c3", "c1", "c2"] + geoms = {"c1": box(5, 5, 15, 15), "c2": box(30, 30, 40, 40), "c3": box(55, 55, 65, 65)} + # shapes in a different order from the table, as after a merge + shapes = ShapesModel.parse( + gpd.GeoDataFrame(geometry=[geoms[i] for i in ("c2", "c3", "c1")], index=pd.Index(["c2", "c3", "c1"])) + ) + obs = pd.DataFrame( + { + "region": pd.Categorical([region] * 3), + "slide": pd.Categorical(["S"] * 3), + "core_id": pd.Categorical(["A1"] * 3), + "cell_id": ids, + }, + index=ids, + ) + table = TableModel.parse( + ad.AnnData(np.zeros((3, 1), dtype=np.float32), obs=obs, var=pd.DataFrame(index=["x"])), + region=region, + region_key="region", + instance_key="cell_id", + ) + sdata = sd.SpatialData(images={"img": image}, shapes={region: shapes}, tables={"m_table": table}) + sdata.attrs["cell_segmentation_image"] = "img" + path = tmp_path / "s.zarr" + sdata.write(path) + return path + + +def cli_args(path, tmp_path, channels="FOXP3,CD45"): + return [ + "--sdata", str(path), "--method", "m", "--channels", channels, "--pixel-size", "1.0", + "--device", "cpu", "--output", str(tmp_path / "m_nimbus.h5ad"), + "--provenance", str(tmp_path / "m_nimbus.json"), + ] # fmt: skip + + +def test_cli_table_layout(tmp_path): + pytest.importorskip("spatialdata") + import anndata as ad + + path = make_store(tmp_path) + rc = nc.main(cli_args(path, tmp_path), predict=identity, halo=96) + assert rc == 0 + out = ad.read_h5ad(tmp_path / "m_nimbus.h5ad") + assert list(out.obs_names) == ["c3", "c1", "c2"] + assert list(out.var_names) == ["FOXP3", "CD45"] + assert out.X.dtype == np.float32 + assert not np.isnan(out.X).any() + # cell c1 < c2 < c3 in both channels; a misaligned shape/table join would break this + by_cell = dict(zip(out.obs_names, out.X[:, list(out.var_names).index("CD45")], strict=False)) + assert by_cell["c1"] < by_cell["c2"] < by_cell["c3"] + assert by_cell["c2"] / by_cell["c1"] == pytest.approx(2, rel=0.1) + assert by_cell["c3"] / by_cell["c1"] == pytest.approx(3, rel=0.1) + assert {"region", "slide", "core_id", "cell_id"} <= set(out.obs.columns) + assert set(out.obs["region"]) == {"m_cells"} + keys = { + "nimbus_version", "weights", "weights_sha256", "channels", "factors", "unscored", + "pixel_size", "model_um_per_px", "magnification", "tile_size", "margin", "halo", "min_window", + "test_time_aug", "device", + } # fmt: skip + assert keys <= set(out.uns["nimbus"]) + assert out.uns["nimbus"]["margin"] == nc.image_px(96 + nc.MARGIN_EXTRA_MODEL_PX, 1.0) + import json + + assert set(json.loads((tmp_path / "m_nimbus.json").read_text())) == set(out.uns["nimbus"]) + + +def test_unknown_channel_exits_naming_channels(tmp_path, capsys): + pytest.importorskip("spatialdata") + path = make_store(tmp_path) + with pytest.raises(SystemExit) as e: + nc.main(cli_args(path, tmp_path, channels="CD45,NOPE"), predict=identity, halo=96) + assert e.value.code == 1 + err = capsys.readouterr().err + assert "NOPE" in err and "CD45" in err and "FOXP3" in err diff --git a/tests/unit/test_nimbus_model.py b/tests/unit/test_nimbus_model.py new file mode 100644 index 0000000..8499d26 --- /dev/null +++ b/tests/unit/test_nimbus_model.py @@ -0,0 +1,171 @@ +"""Real-model tests for nimbus_cells; run in the nimbus image, skipped where it or the fixture is absent.""" + +import json +from pathlib import Path + +import numpy as np +import pytest + +pytest.importorskip("nimbus_inference", reason="needs the nimbus image") +pytest.importorskip("shapely") +FIXTURE = Path(__file__).parent / "fixtures" / "nimbus_crop" +pytestmark = pytest.mark.skipif( + not (FIXTURE / "reference_scores.csv").exists(), reason="no nimbus_crop fixture" +) + +import nimbus_cells as nc # noqa: E402 + +FIXTURE_065 = Path(__file__).parent / "fixtures" / "nimbus_crop_065" +needs_065 = pytest.mark.skipif( + not (FIXTURE_065 / "reference_scores.csv").exists(), reason="no nimbus_crop_065 fixture" +) + +CHANNELS = ["CD45", "FOXP3"] # image.npy channel order + + +def load_crop(fixture): + import pandas as pd + import shapely + from skimage.measure import regionprops + + image = np.load(fixture / "image.npy") + labels = np.load(fixture / "labels.npy") + factors = json.loads((fixture / "factors.json").read_text()) + ref = pd.read_csv(fixture / "reference_scores.csv").sort_values("label") + geoms = [] + for p in regionprops(labels): + # pixel squares centred on integer coordinates, so rasterize() recovers exactly these pixels + geoms.append( + shapely.union_all([shapely.box(x - 0.5, y - 0.5, x + 0.5, y + 0.5) for y, x in p.coords]) + ) + ids = np.array([p.label for p in regionprops(labels)]) + order = np.argsort(ids) + assert (ids[order] == ref["label"].to_numpy()).all() + geoms = [geoms[i] for i in order] + compact = np.arange(1, len(geoms) + 1) + window = (0, labels.shape[0], 0, labels.shape[1]) + assert (nc.label_window(geoms, compact, window) > 0).sum() == (labels > 0).sum() + return image, geoms, compact, factors, ref[CHANNELS].to_numpy() + + +@pytest.fixture(scope="module") +def crop(): + return load_crop(FIXTURE) + + +@pytest.fixture(scope="module") +def crop_065(): + return load_crop(FIXTURE_065) + + +@pytest.fixture(scope="module") +def nimbus(): + return nc.load_nimbus("cpu") + + +def test_halo_is_96(nimbus): + assert nc.model_halo(nimbus) == 96 + + +def test_parity_with_upstream(crop, nimbus): + image, geoms, labels, factors, reference = crop + predict = nc.nimbus_predictor(nimbus, 1.0) + margin = nc.image_px(nc.model_halo(nimbus) + nc.MARGIN_EXTRA_MODEL_PX, 1.0) + ours = nc.score_cells( + image, geoms, labels, CHANNELS, factors, predict, 4096, margin, nc.MIN_WINDOW_MODEL_PX + ) + diff = np.abs(ours - reference).max() + print(f"parity max abs diff {diff:.3g}") + np.testing.assert_allclose(ours, reference, atol=1e-4) + + +def test_tile_invariance_real_model(crop, nimbus): + image, geoms, labels, factors, _ = crop + predict = nc.nimbus_predictor(nimbus, 1.0) + margin = nc.image_px(nc.model_halo(nimbus) + nc.MARGIN_EXTRA_MODEL_PX, 1.0) + args = (image, geoms, labels, CHANNELS, factors, predict) + # 640 px tiles give 2x2 windows (>= min_window, shifted inward) at different origins + tiled = nc.score_cells(*args, 640, margin, nc.MIN_WINDOW_MODEL_PX) + whole = nc.score_cells(*args, 4096, margin, nc.MIN_WINDOW_MODEL_PX) + d = np.abs(tiled - whole) + print(f"tile invariance max {d.max():.3g} mean {d.mean():.3g}") + assert d.max() <= 0.01 + + +PS = 0.65 # a real exemplar pixel size + + +@pytest.fixture(scope="module") +def whole_065(crop_065, nimbus): + """One tile holding every cell: the window is the whole image.""" + image, geoms, labels, factors, _ = crop_065 + margin = nc.image_px(nc.model_halo(nimbus) + nc.MARGIN_EXTRA_MODEL_PX, PS) + predict = nc.nimbus_predictor(nimbus, PS) + args = (image, geoms, labels, CHANNELS, factors, predict) + return nc.score_cells(*args, 10_000, margin, nc.image_px(nc.MIN_WINDOW_MODEL_PX, PS)), margin + + +@needs_065 +def test_parity_with_upstream_at_065(crop_065, whole_065): + reference = crop_065[4] + ours, _ = whole_065 + d = np.abs(ours - reference) + print(f"parity at {PS}: max {d.max():.3g} mean {d.mean():.3g}") + np.testing.assert_allclose(ours, reference, atol=1e-4) + + +@pytest.fixture(scope="module") +def shifted_065(crop_065, nimbus, whole_065): + """The whole image again, one column cropped off the left: upstream's own shift noise.""" + import shapely.affinity + + image, geoms, labels, factors, _ = crop_065 + _, margin = whole_065 + keep = np.array([g.bounds[0] >= 1 for g in geoms]) # cells the crop leaves whole + moved = [shapely.affinity.translate(g, xoff=-1) for g, k in zip(geoms, keep, strict=True) if k] + predict = nc.nimbus_predictor(nimbus, PS) + args = (image[:, :, 1:], moved, labels[keep], CHANNELS, factors, predict) + return keep, nc.score_cells(*args, 10_000, margin, nc.image_px(nc.MIN_WINDOW_MODEL_PX, PS)) + + +@needs_065 +def test_tiling_within_shift_noise_at_065(crop_065, nimbus, whole_065, shifted_065): + # Nimbus is not shift-invariant: a 1 px crop moves scores too. Tiling must add no more than that. + image, geoms, labels, factors, _ = crop_065 + whole, margin = whole_065 + min_window = nc.image_px(nc.MIN_WINDOW_MODEL_PX, PS) + tile = 1050 # 2x2 tiles on the 2100 px image + centroids = np.array([(g.centroid.x, g.centroid.y) for g in geoms]) + windows = nc.tile_windows( + np.array([g.bounds for g in geoms]), nc.assign_tiles(centroids, tile), tile, margin, min_window, + image.shape[1:], + ) # fmt: skip + assert len(windows) == 4 + origins_model_px = [o * PS for y0, _, x0, _ in windows.values() for o in (y0, x0)] + # an origin that is a multiple of the 16 px pooling period would hide phase errors + assert any(abs(o / 16 - round(o / 16)) > 1e-6 for o in origins_model_px), origins_model_px + predict = nc.nimbus_predictor(nimbus, PS) + tiled = nc.score_cells(image, geoms, labels, CHANNELS, factors, predict, tile, margin, min_window) + keep, shifted = shifted_065 + d_tiled = np.abs(tiled - whole)[keep] + d_shift = np.abs(shifted - whole[keep]) + for name, d in (("tiled", d_tiled), ("1 px shift", d_shift)): + print(f"{name} at {PS}: max {d.max():.3g} p99 {np.quantile(d, 0.99):.3g} mean {d.mean():.3g}") + assert d_tiled.mean() <= 1.5 * d_shift.mean() + assert np.quantile(d_tiled, 0.99) <= 1.5 * np.quantile(d_shift, 0.99) + + +def test_main_real_model_path(tmp_path): + from test_nimbus_cells import cli_args, make_store + + pytest.importorskip("spatialdata") + import anndata as ad + + path = make_store(tmp_path) + assert nc.main(cli_args(path, tmp_path)) == 0 + out = ad.read_h5ad(tmp_path / "m_nimbus.h5ad") + prov = json.loads((tmp_path / "m_nimbus.json").read_text()) + assert len(prov["weights_sha256"]) == 64 and int(prov["weights_sha256"], 16) >= 0 + assert prov["nimbus_version"] != "unknown" + assert prov["halo"] == 96 + assert out.shape == (3, 2) and np.isfinite(out.X).all() diff --git a/tests/unit/test_schema_rules.py b/tests/unit/test_schema_rules.py index fdb8342..bbe7421 100644 --- a/tests/unit/test_schema_rules.py +++ b/tests/unit/test_schema_rules.py @@ -14,6 +14,7 @@ # Read by a check but needing no rule line. Keep minimal; each entry needs a reason. WARN_ONLY = { # name: reason + "use_tissue_segmentation": "only read as a requirement of use_virtues, whose help_text lists it", } diff --git a/tests/unit/test_segment_patch.py b/tests/unit/test_segment_patch.py index 247e02e..fc16bfc 100644 --- a/tests/unit/test_segment_patch.py +++ b/tests/unit/test_segment_patch.py @@ -1,7 +1,13 @@ """Tests for bin/segment_patch.py: the image element a spec names and sopa's CLI defaults.""" import pytest -from segment_patch import image_key_for, method_arguments, require_image, segmentation_arguments +from segment_patch import ( + check_weights, + image_key_for, + method_arguments, + require_image, + segmentation_arguments, +) def test_image_key_full_and_projected(): @@ -31,13 +37,13 @@ def test_missing_full_image_lists_the_images(): require_image("img", {"other": None}, "full") -def test_cellpose_defaults_are_sopa_cli_defaults(): +def test_cellpose_defaults_follow_sopa_cli_except_model_and_benchmarked(): spec = {"method": "cellpose", "channels": ["a"], "method_kwargs": {"diameter": 30}} kw = method_arguments(spec) - assert kw["flow_threshold"] == 2 - assert kw["cellprob_threshold"] == -6 + assert kw["flow_threshold"] == 0.6 + assert kw["cellprob_threshold"] == -1 assert kw["model_type"] == "cyto3" - assert kw["pretrained_model"] is None + assert kw["pretrained_model"] == "cpsam_v2" # ours; sopa's is None assert kw["gpu"] is False assert kw["diameter"] == 30 assert kw["channels"] == ["a"] @@ -103,7 +109,7 @@ def test_extra_kwargs_must_be_a_dict_literal(text): def test_segmentation_defaults_per_method(): cp = segmentation_arguments({"method": "cellpose"}) - assert cp == {"min_area": 0, "clip_limit": 0.2, "clahe_kernel_size": None, "gaussian_sigma": 1} + assert cp == {"min_area": 0, "clip_limit": 0, "clahe_kernel_size": None, "gaussian_sigma": 0} ins = segmentation_arguments({"method": "instanseg", "segmentation_kwargs": {}}) assert ins == {"min_area": 0, "clip_limit": 0, "clahe_kernel_size": None, "gaussian_sigma": 0} @@ -114,3 +120,25 @@ def test_segmentation_override(): assert kw["gaussian_sigma"] == 2 assert kw["min_area"] == 15 assert kw["clip_limit"] == 0 + + +def test_cellpose_defaults_to_cpsam_v2(): + assert method_arguments({"method": "cellpose"})["pretrained_model"] == "cpsam_v2" + + +def test_missing_weights_name_the_model(tmp_path): + with pytest.raises( + ValueError, match=r"pretrained_model 'cpsam_v2' has no weights in .*CELLPOSE_LOCAL_MODELS_PATH" + ): + check_weights("cpsam_v2", str(tmp_path)) + + +def test_weights_present_or_path_pass(tmp_path): + (tmp_path / "cpsam_v2").write_bytes(b"x") + check_weights("cpsam_v2", str(tmp_path)) + check_weights(str(tmp_path / "cpsam_v2"), None) # an existing path needs no models dir + + +def test_unset_models_dir_fails_for_a_name(): + with pytest.raises(ValueError, match="CELLPOSE_LOCAL_MODELS_PATH is not set"): + check_weights("cpsam_v2", None) diff --git a/tests/unit/test_segmentation_benchmark.py b/tests/unit/test_segmentation_benchmark.py new file mode 100644 index 0000000..e7a2412 --- /dev/null +++ b/tests/unit/test_segmentation_benchmark.py @@ -0,0 +1,637 @@ +"""Unit tests for the segmentation benchmark tools.""" + +from __future__ import annotations + +from pathlib import Path + +import numpy as np +import pandas as pd +import pytest +from segmentation_benchmark import settings +from segmentation_benchmark.scoring import score +from segmentation_benchmark.settings import TODAY, build_settings, today_index + + +def square(labels, value, y, x, size=10): + labels[y : y + size, x : x + size] = value + + +def test_identical_masks_score_one(): + t = np.zeros((50, 50), int) + square(t, 1, 0, 0) + square(t, 2, 20, 20) + s = score(t, t.copy()) + assert (s["tp"], s["fp"], s["fn"], s["f1"], s["mean_ap"]) == (2, 0, 0, 1.0, 1.0) + + +def test_shifted_object_counts_by_iou(): + t = np.zeros((50, 50), int) + square(t, 1, 0, 0) + p = np.zeros_like(t) + square(p, 7, 0, 2) # IoU 80/120 = 0.667, labels need not match + s = score(t, p) + assert s["tp"] == 1 and s["ap_60"] == 1.0 and s["ap_70"] == 0.0 + + +def test_one_side_empty_is_zero_both_empty_is_nan(): + t = np.zeros((50, 50), int) + square(t, 1, 0, 0) + assert score(t, np.zeros_like(t))["f1"] == 0.0 + assert np.isnan(score(np.zeros_like(t), np.zeros_like(t))["f1"]) + + +def test_split_cell_is_one_fn_three_fp(): + t = np.zeros((50, 50), int) + square(t, 1, 0, 0, 20) # 400 px + p = np.zeros_like(t) + p[0:20, 0:7] = 1 + p[0:20, 7:14] = 2 + p[0:20, 14:20] = 3 # IoU 0.35, 0.35, 0.30 + s = score(t, p) + assert (s["tp"], s["fp"], s["fn"]) == (0, 3, 1) + + +def test_exact_half_iou_matches_once(): + t = np.zeros((50, 50), int) + square(t, 1, 0, 0, 20) # 400 px + p = np.zeros_like(t) + p[0:20, 0:10] = 1 + p[0:20, 10:20] = 2 # each IoU exactly 0.5 + s = score(t, p) + assert (s["tp"], s["fp"], s["fn"]) == (1, 1, 0) + + +def test_layout(): + s = build_settings() + assert len(s) == 168 and list(s["index"]) == list(range(168)) + assert (s[:144]["scope"] == "raw").all() and (s[144:156]["scope"] == "tissuenet").all() + assert (s[156:]["target"] == "nuclei").all() and (s[156:]["scope"] == "all").all() + + +def test_today_is_in_every_block(): + s = build_settings() + for target, scope in [("cells", "raw"), ("cells", "tissuenet"), ("nuclei", "all")]: + row = s.loc[today_index(s, target, scope)] + assert (row["gaussian_sigma"], row["clip_limit"], row["flow_threshold"]) == (1, 0.2, 2) + + +def test_today_index_raises_when_absent(): + s = build_settings() + s = s[s["clip_limit"] != TODAY["clip_limit"]] + with pytest.raises(ValueError, match="cells.*raw"): + today_index(s, "cells", "raw") + + +def test_committed_csv_matches(): + committed = pd.read_csv(Path(settings.__file__).with_name("settings.csv")) + pd.testing.assert_frame_equal(committed, build_settings(), check_dtype=False) + + +# Preprocessing ---------------------------------------------------------------------------- + +NAMES = ["DNA_1", "CD45", "ECAD", "FLAT"] + + +def raw_image(): + rng = np.random.default_rng(0) + data = rng.integers(0, 1000, size=(4, 64, 64), dtype=np.uint16) + data[3] = 5 # constant channel + return data + + +@pytest.mark.parametrize("method", ["max", "mean"]) +@pytest.mark.parametrize("sigma", [0, 1]) +def test_project_matches_pipeline(tmp_path, monkeypatch, method, sigma): + import project_channels + import spatialdata as sd + from segmentation_benchmark.preprocess import project + from spatialdata.models import Image2DModel + + data = raw_image() + # One level, one chunk, no tissue shapes: the pipeline's percentiles come from the full image. + image = Image2DModel.parse(data, dims=("c", "y", "x"), c_coords=NAMES, chunks=(1, 64, 64)) + path = tmp_path / "sample.zarr" + sd.SpatialData(images={"sample": image}).write(path) + rows = ["channel_number,cycle_number,marker_name,channel_role,segmentation", "1,1,DNA_1,dna,nuclear"] + rows += [f"{i},1,{n},marker,cell" for i, n in enumerate(NAMES[1:], start=2)] + sheet = tmp_path / "markers.csv" + sheet.write_text("\n".join(rows) + "\n") + + monkeypatch.chdir(tmp_path) + project_channels.project(path, sheet, method=method, low=1, high=99.9, sigma=sigma, prefix="s") + out = sd.read_zarr(path)["sample_projected"] + level = next(iter(out.values())) if hasattr(out, "children") else out + expected = np.asarray(level.sel(c=["cell", "nuclear"]).data) + + np.testing.assert_array_equal(project(data, 0, method, 1, sigma), expected) + + +def test_flat_marker_left_out_all_flat_gives_zeros(): + from segmentation_benchmark.preprocess import project + + data = raw_image() + with_flat = project(data, 0, "max", 1, 1) + without = project(data[:3], 0, "max", 1, 1) + np.testing.assert_array_equal(with_flat, without) + + all_flat = np.stack([data[0], data[3], data[3]]) + out = project(all_flat, 0, "max", 1, 1) + assert out.shape == (2, 64, 64) and out.dtype == np.uint16 + assert not out[0].any() and out[1].any() + + +def test_pad_round_trip(): + from segmentation_benchmark.preprocess import pad_to, unpad + + image = np.random.default_rng(0).random((2, 100, 100)).astype(np.float32) + padded, shape = pad_to(image) + assert padded.shape == (2, 256, 256) and shape == (100, 100) + np.testing.assert_array_equal(padded[:, :100, :100], image) + + big = np.zeros((2, 300, 40), np.float32) + assert pad_to(big)[0].shape == (2, 300, 256) + + labels = np.zeros((256, 256), int) + labels[10:20, 10:20] = 7 + labels[50:60, 50:60] = 9 + labels[200:210, 200:210] = 11 # in the padding, cropped away + out = unpad(labels, shape) + assert out.shape == (100, 100) + assert sorted(np.unique(out)) == [0, 1, 2] + + +def _square_roi(y, x, size=10): + import roifile + + pts = np.array([[x, y], [x + size, y], [x + size, y + size], [x, y + size]]) + return roifile.ImagejRoi.frompoints(pts) + + +def test_polygon_rois_rasterise(): + from segmentation_benchmark.prepare import rois_to_labels + + labels, overlap = rois_to_labels([_square_roi(0, 0), _square_roi(30, 30)], (50, 50)) + assert sorted(np.unique(labels)) == [0, 1, 2] + assert (labels == 1).sum() == (labels == 2).sum() > 50 + assert overlap == 0 + + +def test_overlap_goes_to_later_roi_and_is_reported(): + from segmentation_benchmark.prepare import rois_to_labels + + labels, overlap = rois_to_labels([_square_roi(0, 0), _square_roi(5, 5)], (50, 50)) + assert overlap > 0 + assert labels[7, 7] == 2 + + +def test_unsupported_roi_names_type(): + import roifile + from segmentation_benchmark.prepare import rois_to_labels + + roi = _square_roi(0, 0) + roi.roitype = roifile.ROI_TYPE.OVAL + with pytest.raises(ValueError, match="OVAL"): + rois_to_labels([roi], (50, 50)) + + +def test_tonsil_dna_is_brightest_in_nuclei(): + from segmentation_benchmark.prepare import tonsil_nuclear_channel + + rng = np.random.default_rng(0) + image = rng.random((3, 40, 40)) + 5 # channel 0 is brighter overall, but flat + image[0] += 10 + nuclei = np.zeros((40, 40), int) + nuclei[10:20, 10:20] = 1 + image[2][nuclei > 0] += 20 + assert tonsil_nuclear_channel(image, nuclei) == 2 + + +def test_dapi_from_composite_ignores_cyan(): + from segmentation_benchmark.prepare import dapi_from_composite + + rng = np.random.default_rng(0) + image = rng.random((3, 40, 40)).astype(np.float32) + rgb = np.zeros((40, 40, 3)) + rgb[..., 2] = image[1] + image[2] # channel 1 is blue, channel 2 is cyan (G and B) + rgb[..., 1] = image[2] + assert dapi_from_composite(image, rgb) == (1, "") + + +def test_tissuenet_meta_maps_one_to_one_after_headers(tmp_path): + from segmentation_benchmark.prepare import read_tissuenet + + header = ["filename", "experiment", "pixel_size", "screening_passed", "time_step", "specimen"] + meta = np.array( + [header] * 4 + [["f", "../x/20200101_CyCIF_Tonsil", 0.5, "Not screened", None, "Tonsil"]] * 2, + dtype=object, + ) + x = np.zeros((2, 8, 8, 2)) + x[1, ..., 1] = 3.0 + y = np.zeros((2, 8, 8, 2), np.int32) + y[0, :4, :4, 0] = 1 + y[0, :2, :2, 1] = 1 + path = tmp_path / "t.npz" + np.savez(path, X=x, y=y, meta=meta) + (row0, img0, cells0, nuclei0), (row1, img1, _, _) = list(read_tissuenet(path)) + assert (row0["crop"], row0["platform"], row0["tissue"], row0["nuclear"]) == ( + "0000", + "20200101_CyCIF_Tonsil", + "Tonsil", + 0, + ) + assert img0.shape == (2, 8, 8) and img1[1].max() == 3.0 and img1[0].max() == 0 + assert (cells0 > 0).sum() == 16 and (nuclei0 > 0).sum() == 4 + + np.savez(path, X=x, y=y, meta=meta[:-1]) + with pytest.raises(ValueError, match="tiles"): + list(read_tissuenet(path)) + + +# --- run.py --------------------------------------------------------------------------------- + + +@pytest.fixture +def bench(tmp_path, monkeypatch): + """Tiny data dir (one crop per dataset, cells+nuclei masks) and run.segment returning truth.""" + import tifffile + from segmentation_benchmark import run + + data = tmp_path / "data" + rows = [] + for dataset, nch in [("crossplatform", 3), ("tonsil", 3), ("tissuenet", 2)]: + d = data / "crops" / dataset / "c1" + d.mkdir(parents=True) + rng = np.random.default_rng(0) + tifffile.imwrite(d / "image.tif", rng.integers(0, 1000, (nch, 40, 40)).astype(np.uint16)) + lab = np.zeros((40, 40), np.uint32) + square(lab, 1, 2, 2) + square(lab, 2, 20, 20) + tifffile.imwrite(d / "cells.tif", lab) + tifffile.imwrite(d / "nuclei.tif", lab) + rows.append((dataset, "c1", "p", "t", 0.5, "a|b|c", 0, 40, 40, True, 2, 2)) + cols = "dataset crop platform tissue pixel_size_um channels nuclear height width montage n_cells n_nuclei" + pd.DataFrame(rows, columns=cols.split()).to_csv(data / "crops.csv", index=False) + + calls = [] + + def fake(image, channels, _setting, _gpu): + calls.append(channels) + return tifffile.imread(data / "crops" / "tonsil" / "c1" / "cells.tif")[ + : image.shape[1], : image.shape[2] + ] + + monkeypatch.setattr(run, "segment", fake) + return run, data, tmp_path / "out", calls + + +def test_skips_existing_result(bench): + run, data, out, calls = bench + (out / "results").mkdir(parents=True) + (out / "results" / "3.csv").write_text("x\n") + run.run(data, 3, out) + assert calls == [] + + +def test_overwrites_stale_tmp_and_writes_atomically(bench): + run, data, out, _ = bench + (out / "results").mkdir(parents=True) + (out / "results" / "3.csv.tmp").write_text("stale") + run.run(data, 3, out) # cells, raw: crossplatform + tonsil + df = pd.read_csv(out / "results" / "3.csv") + assert len(df) == 2 and (df["f1"] == 1.0).all() + assert not (out / "results" / "3.csv.tmp").exists() + assert (out / "labels" / "3" / "tonsil__c1.tif").exists() + + +def test_scope_selects_crops(bench): + run, data, out, _ = bench + run.run(data, 150, out) # cells, tissuenet + assert set(pd.read_csv(out / "results" / "150.csv")["dataset"]) == {"tissuenet"} + run.run(data, 160, out) # nuclei, all + assert set(pd.read_csv(out / "results" / "160.csv")["dataset"]) == { + "crossplatform", + "tonsil", + "tissuenet", + } + run.run(data, 3, out) + assert "tissuenet" not in set(pd.read_csv(out / "results" / "3.csv")["dataset"]) + + +def test_partial_run_is_kept_out_of_results(bench): + run, data, out, _ = bench + run.run(data, 3, out, limit_crops=1) + assert not (out / "results" / "3.csv").exists() + assert len(pd.read_csv(out / "results" / "3.partial.csv")) == 1 + run.run(data, 3, out) # the full run still happens + assert len(pd.read_csv(out / "results" / "3.csv")) == 2 + + +def test_no_crops_is_an_error(bench): + run, data, out, _ = bench + with pytest.raises(SystemExit, match="setting 3"): + run.run(data, 3, out, dataset="tissuenet") + assert not (out / "results" / "3.csv").exists() + + +def fake_results(tmp_path, f1_by_setting): + """results/.csv from {index: {dataset: [f1, ...]}}; returns (results, data, out) dirs.""" + results = tmp_path / "out" / "results" + results.mkdir(parents=True) + for index, by_dataset in f1_by_setting.items(): + rows = [ + { + "index": index, + "target": "cells", + "dataset": dataset, + "crop": f"c{i}", + "platform": "Vectra", + "n_true": 5, + "n_pred": 5, + "f1": f1, + "mean_ap": f1 / 2, + "seconds": 1.0, + } + for dataset, values in by_dataset.items() + for i, f1 in enumerate(values) + ] + pd.DataFrame(rows).to_csv(results / f"{index}.csv", index=False) + data = tmp_path / "data" + data.mkdir() + (data / "crops.csv").write_text("dataset,crop,platform,nuclear,montage\n") + return results, data, tmp_path / "report" + + +def test_summary_ranks_by_crossplatform_f1(tmp_path): + import json + + from segmentation_benchmark import report + + results, data, out = fake_results( + tmp_path, + { + 0: {"crossplatform": [0.5, 0.5], "tissuenet": [0.9]}, + 1: {"crossplatform": [0.6, 0.6], "tissuenet": [0.8]}, + 2: {"crossplatform": [0.9, 0.9], "tissuenet": [0.1]}, + }, + ) + report.build_report(results, data, out) + headline = json.loads((out / "headline.json").read_text()) + assert headline["cells_raw"]["best"]["index"] == 2 + assert headline["cells_raw"]["best"]["f1_by_dataset"]["tissuenet"] == pytest.approx(0.1) + + +def test_nan_crops_are_counted_and_excluded(tmp_path): + from segmentation_benchmark import report + + results, data, out = fake_results(tmp_path, {0: {"crossplatform": [0.8, float("nan"), 0.6]}}) + report.build_report(results, data, out) + row = pd.read_csv(out / "summary.csv").query("`index` == 0 and dataset == 'crossplatform'").iloc[0] + assert (row["n_crops"], row["n_nan"]) == (3, 1) + assert row["mean_f1"] == pytest.approx(0.7) + + +def test_partial_results_are_ignored(tmp_path): + from segmentation_benchmark import report + + results, data, out = fake_results(tmp_path, {0: {"crossplatform": [0.8]}}) + (results / "1.partial.csv").write_text("garbage") + report.build_report(results, data, out) + assert set(pd.read_csv(out / "summary.csv")["index"]) == {0} + + +def test_missing_setting_is_listed_and_flagged(tmp_path): + import json + + from segmentation_benchmark import report + + results, data, out = fake_results( + tmp_path, {i: {"crossplatform": [0.5 + i / 100]} for i in (0, 2, 18)} + ) # setting 1 is absent; 18 is today + report.build_report(results, data, out) + head = json.loads((out / "headline.json").read_text()) + assert 1 in head["missing_settings"] and 0 not in head["missing_settings"] + assert 1 in head["cells_raw"]["missing_settings"] and head["cells_raw"]["today_missing"] is False + assert (out / "effects_clip_limit.png").exists() + + +def test_missing_today_is_flagged(tmp_path): + import json + + from segmentation_benchmark import report + + results, data, out = fake_results(tmp_path, {0: {"crossplatform": [0.5]}, 1: {"crossplatform": [0.6]}}) + report.build_report(results, data, out) + head = json.loads((out / "headline.json").read_text()) + assert head["cells_raw"]["today_missing"] is True and head["cells_raw"]["today"] is None + + +def test_vectra_dapi_methods_disagree_skips_crop(tmp_path): + from PIL import Image + from segmentation_benchmark.prepare import _vectra_nuclear + + rng = np.random.default_rng(0) + img = rng.random((3, 40, 40)).astype(np.float32) + rgb = np.zeros((40, 40, 3), np.uint8) + rgb[..., 2] = (img[1] * 255).astype(np.uint8) # composite says channel 1 + Image.fromarray(rgb).save(tmp_path / "x-Crop_Cell_Png.png") + dapi = (img[2] * 255).astype(np.uint8) # DAPI render says channel 2 + Image.fromarray(dapi).save(tmp_path / "x-Crop_Dapi_Png.png") + skipped = [] + assert _vectra_nuclear(img, tmp_path, skipped) == (None, "disagree") + assert "ch1" in skipped[0][1] and "ch2" in skipped[0][1] + + Image.fromarray((img[1] * 255).astype(np.uint8)).save(tmp_path / "x-Crop_Dapi_Png.png") + assert _vectra_nuclear(img, tmp_path, []) == (1, "agree") + + +def _imagej_tif(path, info): + import tifffile + + tifffile.imwrite( + path, np.zeros((3, 8, 8), np.float32), imagej=True, metadata={"axes": "CYX", "Info": info} + ) + + +def test_vectra_channel_names_from_imagej_info(tmp_path): + from segmentation_benchmark.prepare import vectra_channel_names + + _imagej_tif( + tmp_path / "a.tif", + "Foo = 1\nName #1 = CD8 (Opal 650)\nName #2 = Hoechst (DAPI)\nName #3 = Autofluorescence\n", + ) + assert vectra_channel_names(tmp_path / "a.tif") == [ + "CD8 (Opal 650)", + "Hoechst (DAPI)", + "Autofluorescence", + ] + _imagej_tif(tmp_path / "b.tif", "Name #1 = CD8\nName #3 = DAPI\n") # gap: not trusted + assert vectra_channel_names(tmp_path / "b.tif") is None + _imagej_tif(tmp_path / "c.tif", "no names here") + assert vectra_channel_names(tmp_path / "c.tif") is None + + +def test_is_dna_name(): + from segmentation_benchmark.prepare import is_dna_name + + assert is_dna_name("DAPI") and is_dna_name("Hoechst (DAPI)") and is_dna_name("DAPI1") + assert not is_dna_name("CD8 (Opal 650)") and not is_dna_name("Autofluorescence") + + +P01 = "GITR (Opal 520)|IDO (Opal 570)|Ki67 (Opal 540)|Foxp3 (Opal 620)|CD8 (Opal 650)|DAPI|panCK (Opal 690)|Autofluorescence" + + +@pytest.mark.parametrize( + ("selection", "expected"), + [("all", [0, 1, 2, 3, 4, 6, 7]), ("markers", [0, 1, 2, 3, 4, 6]), ("membrane", [0, 1, 4, 6])], +) +def test_cell_channel_selection(selection, expected): + from segmentation_benchmark.preprocess import cell_channels + + assert cell_channels(P01.split("|"), 5, selection) == expected + + +def test_cell_channel_selection_rejects_unknown_and_empty(): + from segmentation_benchmark.preprocess import cell_channels + + with pytest.raises(ValueError, match="selection"): + cell_channels(["CD8", "DAPI"], 1, "nope") + with pytest.raises(ValueError, match="no cell channels"): + cell_channels(["Ki67", "DAPI", "Autofluorescence"], 1, "membrane") + + +def test_project_uses_only_selected_channels(): + from segmentation_benchmark.preprocess import project + + rng = np.random.default_rng(0) + image = rng.random((3, 32, 32)).astype(np.float32) # [marker, DAPI, autofluorescence] + image[2, 5, 5] = 100.0 # bright only in the autofluorescence channel + every = project(image, 1, "max", 1, 0) + marker_only = project(image, 1, "max", 1, 0, cell_idx=[0]) + assert every[0, 5, 5] == 65535 + assert marker_only[0, 5, 5] < 65535 + np.testing.assert_array_equal(every[1], marker_only[1]) + + +# --- round 2 -------------------------------------------------------------------------------- + + +def test_round2_layout(): + from segmentation_benchmark.settings import build_round2 + + s = build_round2() + assert len(s) == 307 and list(s["index"]) == list(range(307)) + blocks = s.groupby(["target", "scope", "cell_channels", "clip_limit"], sort=False).size() + assert blocks.to_dict() == { + ("cells", "raw", "markers", 0.0): 56, + ("cells", "raw", "all", 0.0): 56, + ("cells", "raw", "membrane", 0.0): 56, + ("cells", "tissuenet", "markers", 0.0): 56, + ("nuclei", "all", "markers", 0.0): 56, + ("cells", "raw", "markers", 0.01): 9, + ("cells", "tissuenet", "markers", 0.01): 9, + ("nuclei", "all", "markers", 0.01): 9, + } + fixed = s[["projection_method", "low_percentile", "projection_sigma", "gaussian_sigma"]] + assert (fixed.drop_duplicates().values.tolist()) == [["max", 1, 0, 0]] + assert not s.drop(columns="index").duplicated().any() + + +def test_round2_keeps_round1_pairs_in_every_block(): + from segmentation_benchmark.settings import build_round2 + + s = build_round2() + for _, block in s[s["clip_limit"] == 0].groupby(["target", "scope", "cell_channels"]): + pairs = set(zip(block["flow_threshold"], block["cellprob_threshold"], strict=True)) + assert {(2, -6), (0.4, 0)} <= pairs + + +def test_committed_round2_csv_matches(): + from segmentation_benchmark.settings import build_round2 + + committed = pd.read_csv(Path(settings.__file__).with_name("settings_round2.csv")) + pd.testing.assert_frame_equal(committed, build_round2(), check_dtype=False) + + +def test_round1_rows_combine_all_channels(): + assert (build_settings()["cell_channels"] == "all").all() + + +def test_run_uses_round2_grid_and_channel_selection(bench, monkeypatch): + run, data, out, _ = bench + seen = [] + real = run.project + + def spy(image, nuclear, *args, cell_idx=None, **kwargs): + seen.append(cell_idx) + return real(image, nuclear, *args, cell_idx=cell_idx, **kwargs) + + monkeypatch.setattr(run, "project", spy) + crops = pd.read_csv(data / "crops.csv") + crops["channels"] = "DAPI|CD8|Autofluorescence" + crops.to_csv(data / "crops.csv", index=False) + run.run(data, 0, out, grid="round2") # cells, raw, markers + assert seen == [[1], [1]] + assert (out / "results" / "0.csv").exists() + + +def _threshold_table(f1): + """{key: {(flow, prob): f1}} -> long table as report_round2.pick expects.""" + return pd.DataFrame( + [ + {"key": key, "flow_threshold": flow, "cellprob_threshold": prob, "mean_f1": v} + for key, by_pair in f1.items() + for (flow, prob), v in by_pair.items() + ] + ) + + +def test_pick_minimises_worst_shortfall(): + from segmentation_benchmark.report_round2 import pick + + table = _threshold_table( + { + "a": {(2, -6): 0.90, (0.4, 0): 0.50, (1, -2): 0.85}, + "b": {(2, -6): 0.40, (0.4, 0): 0.80, (1, -2): 0.75}, + } + ) + p = pick(table) + assert p["pair"] == [1, -2] # worst shortfall 0.05, against 0.40 for either corner + assert p["worst_shortfall"] == pytest.approx(0.05) + assert p["best"]["a"] == {"pair": [2, -6], "f1": 0.90} + assert p["missing_pairs"] == [] + + +def test_pick_ignores_pairs_missing_a_key(): + from segmentation_benchmark.report_round2 import pick + + table = _threshold_table({"a": {(1, 0): 0.9, (2, 0): 0.5}, "b": {(2, 0): 0.5}}) + p = pick(table) + assert p["pair"] == [2, 0] and p["missing_pairs"] == [[1, 0]] + + +def test_round2_report_writes_outputs(tmp_path): + from segmentation_benchmark.report_round2 import build_report + from segmentation_benchmark.settings import build_round2 + + s = build_round2() + rng = np.random.default_rng(0) + rows = [] + for _, r in s.iterrows(): + datasets = {"raw": ["crossplatform", "tonsil"], "tissuenet": ["tissuenet"]}.get( + r["scope"], ["crossplatform", "tonsil", "tissuenet"] + ) + for d in datasets: + for c in range(2): + platform = "Vectra" if d == "crossplatform" else "unknown" + f1 = rng.random() + rows.append({"index": r["index"], "target": r["target"], "dataset": d, "crop": f"c{c}", + "platform": platform, "f1": f1, "mean_ap": f1 / 2}) # fmt: skip + results = tmp_path / "results" + results.mkdir() + for index, g in pd.DataFrame(rows).groupby("index"): + g.to_csv(results / f"{index}.csv", index=False) + out = tmp_path / "report" + build_report(results, out) + for name in ["summary_round2.csv", "pick.json", "channels.csv", "clahe.csv", "heatmaps.png", + "channels.png", "clahe.png"]: # fmt: skip + assert (out / name).exists(), name diff --git a/tests/unit/test_site_reference.py b/tests/unit/test_site_reference.py index 00059e7..a128120 100644 --- a/tests/unit/test_site_reference.py +++ b/tests/unit/test_site_reference.py @@ -210,6 +210,11 @@ def test_instanseg_page_names_instanseg_without_sopa_version(): assert cells[2] == "" # instanseg is not pinned; the image tag is sopa's version +def test_nimbus_page_names_nimbus_and_image_tag(): + cells = _facts_row("nimbus") + assert "Nimbus" in cells[1] and "josenimo/nimbus:0.0.5" in cells[3] + + def test_qc_report_page_names_pipeline_scripts_and_keeps_container(): md = render_module_facts( [REPO / d for d in PAGES["qc-report"]], REPO / "containers.tsv", TOOL_OVERRIDES["qc-report"] diff --git a/tests/unit/test_virtues_cells.py b/tests/unit/test_virtues_cells.py new file mode 100644 index 0000000..f864f06 --- /dev/null +++ b/tests/unit/test_virtues_cells.py @@ -0,0 +1,514 @@ +"""Tiled VirTues runner core, with a fake encoder: crops, windows, cells, niches.""" + +import json + +import numpy as np +import pytest +from shapely.geometry import box + +import virtues_cells as vc +import virtues_stats as vs + +C = 3 + + +# Copied from bunnelab/virtues d2c25e1, virtues/utils/cell_tokens.py (MIT), as the test reference. +def _get_uniform_crops(img, stride, tile_size=128): + crops = [] + + h, w = img.shape[-2:] + indices_set = set() + for i in range(0, h - tile_size + 1, stride): + for j in range(0, w - tile_size + 1, stride): + indices_set.add((i, j)) + + last_i = h - tile_size + for j in range(0, w - tile_size + 1, stride): + indices_set.add((last_i, j)) + last_j = w - tile_size + for i in range(0, h - tile_size + 1, stride): + indices_set.add((i, last_j)) + indices_set.add((last_i, last_j)) + indices = sorted(list(indices_set)) + for i, j in indices: + crop = img[:, i : i + tile_size, j : j + tile_size] + crops.append(crop) + for i in range(len(indices)): + indices[i] = (indices[i][0], indices[i][1]) + return crops, indices + + +def fake_encode(crops): + """Each patch's mean per channel, (n, 16, 16, c).""" + n, c = crops.shape[:2] + return crops.reshape(n, c, 16, 8, 16, 8).mean(axis=(3, 5)).transpose(0, 2, 3, 1).astype(np.float32) + + +def stats(mean=0.0, sd=1.0): + return {"cap": np.full(C, 1e9), "mean": np.full(C, mean), "sd": np.full(C, sd)} + + +def make_image(h, w, seed=0): + return np.random.default_rng(seed).integers(0, 2000, (C, h, w)).astype(np.uint16) + + +def reader(img, st, pixel_size=1.0): + """read_input bound to an image, statistics and the padded shape.""" + h, w = vs.model_shape(img.shape[1:], pixel_size) + padded = (h + 2 * vc.PAD, w + 2 * vc.PAD) + + def read_raw(c, y0, y1, x0, x1): + return vs.resample_window(img, c, y0, y1, x0, x1, pixel_size) + + def read_input(y0, y1, x0, x1): + return vc.model_input(read_raw, st, y0, y1, x0, x1, padded) + + return read_input, padded + + +def source(geoms, pixel_size=1.0): + """CellSource in padded coordinates, from image-coordinate geoms.""" + centroids = np.array([(g.centroid.y, g.centroid.x) for g in geoms]) * pixel_size + vc.PAD + b = np.array([g.bounds for g in geoms]) # minx, miny, maxx, maxy + bboxes = b[:, [1, 3, 0, 2]] * pixel_size + vc.PAD + return vc.CellSource(vc.label_reader(geoms, pixel_size), centroids, bboxes) + + +def edge_cells(h, w, n=40, seed=3): + """Boxes straddling the tile-64 and tile-200 lines (in padded coordinates) and the image edge.""" + rng = np.random.default_rng(seed) + lines = [t - vc.PAD for t in (128, 192, 200, 256, 320, 400) if t - vc.PAD > 0] + geoms = [] + for k in range(n): + size = rng.uniform(3, 25, 2) + if k % 4 == 0: # on the image edge + y, x = rng.choice([0, h - size[0]]), rng.uniform(0, w - size[1]) + else: + y = rng.choice(lines) - size[0] / 2 + rng.uniform(-2, 2) + x = rng.choice(lines) - size[1] / 2 + rng.uniform(-2, 2) + y, x = np.clip(y, 0, h - size[0]), np.clip(x, 0, w - size[1]) + geoms.append(box(x, y, x + size[1], y + size[0])) + return geoms + + +def test_crop_grid_equals_upstream(): + for h, w in [(128, 128), (300, 517), (1000, 1000)]: + _, expected = _get_uniform_crops(np.zeros((1, h, w)), vc.STEP, vc.CROP) + assert vc.uniform_crops(h, w) == expected + + +def test_tiled_equals_whole_image_exactly(): + img = make_image(300, 260) + read_input, padded = reader(img, stats(0.5, 2.0)) + sources = {"cells": source(edge_cells(300, 260))} + runs = [vc.cell_embeddings(read_input, sources, padded, fake_encode, tile=t) for t in (64, 200, 4096)] + emb, weight = runs[-1]["cells"] + assert emb.dtype == np.float32 and weight.dtype == np.float64 and (weight > 0).sum() >= 35 + for run in runs[:-1]: + assert np.array_equal(run["cells"][0], emb, equal_nan=True) and np.array_equal( + run["cells"][1], weight + ) + + +def test_cell_matches_upstream_averaging(): + img = make_image(200, 180, seed=1) + st = stats(0.5, 2.0) + read_input, padded = reader(img, st) + geoms = edge_cells(200, 180, n=25, seed=4) + src = source(geoms) + emb, weight = vc.cell_embeddings(read_input, {"cells": src}, padded, fake_encode, tile=128)["cells"] + + # port of upstream compute_cell_tokens on the whole padded image + x = read_input(0, padded[0], 0, padded[1]) + mask = src.read_labels(0, padded[0], 0, padded[1]) + crops, indices = _get_uniform_crops(x, vc.STEP, vc.CROP) + tokens = fake_encode(np.stack(crops)) + cell_tokens, weights = {}, {} + for crop_token, (row, col) in zip(tokens, indices, strict=False): + crop_mask = mask[row : row + vc.CROP, col : col + vc.CROP] + for i in range(16): + for j in range(16): + patch = crop_mask[i * 8 : (i + 1) * 8, j * 8 : (j + 1) * 8] + for cell_id, count in zip(*np.unique(patch, return_counts=True), strict=False): + if cell_id == 0: + continue + cell_tokens.setdefault(cell_id, []).append(crop_token[i, j]) + weights.setdefault(cell_id, []).append(count) + # cells hidden under earlier ones have no pixel, so upstream has no row for them + assert sorted(cell_tokens) == list(np.flatnonzero(weight > 0) + 1) and len(cell_tokens) >= 20 + for cell_id, toks in cell_tokens.items(): + w = np.array(weights[cell_id], dtype=np.float32) + expected = (np.stack(toks) * (w / w.sum())[:, None]).sum(axis=0) + np.testing.assert_allclose(emb[cell_id - 1], expected, rtol=1e-6, atol=1e-6) + + +def test_two_methods_equal_one_at_a_time(): + img = make_image(260, 240, seed=2) + read_input, padded = reader(img, stats()) + cells = edge_cells(260, 240, seed=5) + nuclei = [g.buffer(-1.0) if g.area > 30 else g for g in cells[:30]] + both = vc.cell_embeddings( + read_input, {"cells": source(cells), "nuclei": source(nuclei)}, padded, fake_encode, tile=100 + ) + for name, geoms in [("cells", cells), ("nuclei", nuclei)]: + alone = vc.cell_embeddings(read_input, {name: source(geoms)}, padded, fake_encode, tile=100) + assert np.array_equal(both[name][0], alone[name][0], equal_nan=True) + assert np.array_equal(both[name][1], alone[name][1]) + + +def test_cell_without_pixel_is_nan(): + img = make_image(100, 100) + read_input, padded = reader(img, stats()) + geoms = [box(20, 20, 30, 30), box(10.6, 40, 10.9, 60)] # sliver between pixel centres 10.5 and 11.5 + emb, weight = vc.cell_embeddings(read_input, {"cells": source(geoms)}, padded, fake_encode)["cells"] + assert weight[0] > 0 and weight[1] == 0 + assert np.isfinite(emb[0]).all() and np.isnan(emb[1]).all() + + +def test_overlap_earlier_cell_wins(): + geoms = [box(10, 10, 20, 20), box(15, 15, 25, 25)] + read_labels = vc.label_reader(geoms, 1.0) + p = vc.PAD + whole = read_labels(p, p + 40, p, p + 40) + assert whole.dtype == np.int32 + assert (whole[10:20, 10:20] == 1).all() and (whole == 2).sum() == 100 - 25 + # a window over the overlap alone gives the same labels + assert np.array_equal(read_labels(p + 16, p + 22, p + 16, p + 22), whole[16:22, 16:22]) + img = make_image(60, 60) + read_input, padded = reader(img, stats()) + _, weight = vc.cell_embeddings(read_input, {"cells": source(geoms)}, padded, fake_encode)["cells"] + # a pixel in a crop overlap counts once per crop, so compare with an upstream-style count + counts = np.zeros(3) + labels = read_labels(0, padded[0], 0, padded[1]) + for i, j in vc.uniform_crops(*padded): + counts += np.bincount(labels[i : i + 128, j : j + 128].ravel(), minlength=3) + assert np.array_equal(weight, counts[1:]) + + +def test_model_input_window_independent(): + img = make_image(150, 170, seed=6) + st = stats(0.7, 1.5) + read_input, (hp, wp) = reader(img, st, pixel_size=0.8) + whole = read_input(0, hp, 0, wp) + assert whole.dtype == np.float32 and whole.shape == (C, hp, wp) + for y0, y1, x0, x1 in [ + (0, 40, 0, 50), + (hp - 30, hp, wp - 60, wp), + (vc.PAD - 2, vc.PAD + 3, vc.PAD - 1, vc.PAD + 9), + (hp - vc.PAD - 3, hp - vc.PAD + 2, 50, 90), + (130, 190, 140, 141), + ]: + assert np.array_equal(read_input(y0, y1, x0, x1), whole[:, y0:y1, x0:x1]) + # the pad is standardised zeros, blurred, as upstream pads before standardising + assert np.allclose(whole[:, : vc.PAD - 1], -0.7 / 1.5) + # the blur is torchvision's: 3 x 3 Gaussian, sigma 1, reflect border, on the padded image + raw = np.zeros((C, hp, wp)) + h, w = hp - 2 * vc.PAD, wp - 2 * vc.PAD + for c in range(C): + raw[c, vc.PAD : vc.PAD + h, vc.PAD : vc.PAD + w] = vs.resample_window(img, c, 0, h, 0, w, 0.8) + z = (np.log1p(raw) - 0.7) / 1.5 + k = np.exp(-0.5 * np.array([1.0, 0.0, 1.0])) + k2 = np.outer(k, k) / k.sum() ** 2 + zp = np.pad(z, ((0, 0), (1, 1), (1, 1)), mode="reflect") + blurred = sum(k2[a, b] * zp[:, a : a + hp, b : b + wp] for a in range(3) for b in range(3)) + np.testing.assert_allclose(whole, blurred, rtol=1e-5, atol=1e-5) + + +def niches(img, polygons, pixel_size=1.0): + st = stats() + read_input, _ = reader(img, st, pixel_size) + shape = vs.model_shape(img.shape[1:], pixel_size) + + def read_tissue(y0, y1, x0, x1): + return vs.tissue_mask(polygons, y0, y1, x0, x1, pixel_size) + + return read_input, vc.niche_embeddings(read_input, read_tissue, shape, fake_encode) + + +def test_niche_grid_and_threshold(): + img = make_image(300, 300) + _, (origins, frac, emb) = niches(img, [box(0, 0, 300, 300)]) + assert origins == [(0, 0), (0, 128), (128, 0), (128, 128)] + assert np.array_equal(frac, np.ones(4)) and emb.shape == (4, C) and emb.dtype == np.float32 + # 37 of 128 columns is 28.9% (dropped); 40 is 31.25% (kept) + _, (origins, frac, _) = niches(img, [box(0, 0, 37, 128)]) + assert origins == [] + _, (origins, frac, _) = niches(img, [box(0, 0, 40, 128)]) + assert origins == [(0, 0)] and frac[0] == pytest.approx(40 / 128) + + +def test_niche_is_patch_mean(): + img = make_image(300, 300, seed=7) + read_input, (origins, _, emb) = niches(img, [box(0, 0, 300, 300)]) + for (y, x), row in zip(origins, emb, strict=False): + crop = read_input(y + vc.PAD, y + vc.PAD + 128, x + vc.PAD, x + vc.PAD + 128) + np.testing.assert_allclose(row, fake_encode(crop[None]).reshape(256, C).mean(axis=0), rtol=1e-6) + np.testing.assert_allclose(row, crop.mean(axis=(1, 2)), rtol=1e-5, atol=1e-6) + + +def test_tissue_is_mean_of_kept_niches(): + img = make_image(400, 300, seed=8) + _, (origins, _, emb) = niches(img, [box(0, 0, 300, 150)]) + assert len(origins) == 2 + np.testing.assert_allclose(vc.tissue_embedding(emb), emb.mean(axis=0), rtol=1e-6) + + +def test_no_niche_gives_nan_tissue(): + img = make_image(300, 300) + _, (origins, frac, emb) = niches(img, []) + assert origins == [] and frac.shape == (0,) and emb.shape == (0, C) + tissue = vc.tissue_embedding(emb) + assert tissue.shape == (C,) and np.isnan(tissue).all() + + +# --- CLI, with a fake encoder --- + +PANEL = [("CD45", "P08575"), ("CD3", "P07766"), ("PanCK", "P05787")] +FASTA = ( + ">sp|P08575|PTPRC_HUMAN Receptor-type tyrosine-protein phosphatase C\nMYLWLKLLAF\nGFAFLDTEVF\n" + ">sp|P08575-8|PTPRC_HUMAN Isoform 8\nMYLWLK\n" + ">sp|P07766|CD3E_HUMAN T-cell surface glycoprotein CD3 epsilon chain\nMQSGTHWRVL\n" + ">sp|P05787|K2C8_HUMAN Keratin, type II cytoskeletal 8\nMSIRVTQKSY\nKVSTSGPRAF\n" +) + + +def fake_encode_512(crops): + """fake_encode padded to the model's 512 columns.""" + tokens = fake_encode(crops) + return np.pad(tokens, ((0, 0), (0, 0), (0, 0), (0, 512 - tokens.shape[-1]))) + + +def write_stats(path, panel=PANEL): + markers = { + n: {"uniprot_id": u, "cap": 5000.0, "mean": 5.0, "sd": 1.5, "tissue_pixels": 100} for n, u in panel + } + path.write_text(json.dumps({"format": 1, "slide": "S", "markers": markers})) + return path + + +def scaled(geoms, factor): + """geoms kept 1/factor in size, with Scale(factor) to global, as sopa stores a coarser level.""" + import geopandas as gpd + from shapely.affinity import scale + from spatialdata.models import ShapesModel + from spatialdata.transformations import Scale + + gdf = gpd.GeoDataFrame(geometry=[scale(g, 1 / factor, 1 / factor, origin=(0, 0)) for g in geoms.geometry]) + gdf.index = geoms.index + return ShapesModel.parse(gdf, transformations={"global": Scale([factor, factor], axes=("x", "y"))}) + + +def make_virtues_store(tmp_path, roi, roi_scale=1, cell_scale=1): + """300 x 520 image px at 0.5 um/px (model 150 x 260): two methods, CD45 bright in cp_1 only.""" + import anndata as ad + import geopandas as gpd + import pandas as pd + import spatialdata as sd + from spatialdata.models import Image2DModel, TableModel + + rng = np.random.default_rng(0) + data = rng.integers(0, 200, (4, 300, 520)).astype(np.uint16) + data[1, 100:150, 200:260] = 4000 # CD45 inside cp_1 + image = Image2DModel.parse( + data, dims=("c", "y", "x"), c_coords=["DNA", "CD45", "CD3", "PanCK"], scale_factors=[2] + ) + cells = { + "cellpose": { + "cp_0": box(10, 10, 40, 40), + "cp_1": box(200, 100, 260, 150), + "cp_2": box(400, 200, 460, 260), + "cp_3": box(100.2, 100, 100.4, 140), # between pixel centres at 0.5 um/px: no pixel + }, + "stardist": {"sd_0": box(15, 15, 35, 35), "sd_1": box(210, 110, 250, 140)}, + } + shapes, tables = {}, {} + for m, geoms in cells.items(): + ids = list(geoms)[::-1] # table order differs from the shapes' + shapes[f"{m}_cells"] = scaled( + gpd.GeoDataFrame(geometry=list(geoms.values()), index=pd.Index(list(geoms))), cell_scale + ) + obs = pd.DataFrame( + { + "region": pd.Categorical([f"{m}_cells"] * len(ids)), + "slide": pd.Categorical(["S"] * len(ids)), + "core_id": pd.Categorical(["A1"] * len(ids)), + "cell_id": ids, + }, + index=ids, + ) + tables[f"{m}_table"] = TableModel.parse( + ad.AnnData(np.zeros((len(ids), 1), dtype=np.float32), obs=obs, var=pd.DataFrame(index=["x"])), + region=f"{m}_cells", + region_key="region", + instance_key="cell_id", + ) + if roi is not None: + shapes["region_of_interest"] = scaled(gpd.GeoDataFrame(geometry=[roi]), roi_scale) + sdata = sd.SpatialData(images={"img": image}, shapes=shapes, tables=tables) + sdata.attrs["cell_segmentation_image"] = "img" + path = tmp_path / "s.zarr" + sdata.write(path) + return path + + +def run_cli(tmp_path, monkeypatch, roi, panel=PANEL, stats_panel=PANEL, device="cuda", **scales): + pytest.importorskip("spatialdata") + tmp_path.mkdir(exist_ok=True) + fasta = tmp_path / "uniprot.fasta" + fasta.write_text(FASTA) + monkeypatch.setenv("VIRTUES_UNIPROT", str(fasta)) + path = make_virtues_store(tmp_path, roi, **scales) + out = tmp_path / "out" + argv = [ + "--sdata", str(path), "--methods", "cellpose,stardist", + "--channels", ",".join(f"{n}:{u}" for n, u in panel), "--unembedded", "DNA", + "--stats", str(write_stats(tmp_path / "S_virtues_stats.json", stats_panel)), + "--pixel-size", "0.5", "--device", device, "--outdir", str(out), + ] # fmt: skip + return vc.main(argv, encode=fake_encode_512), out + + +UNS_KEYS = { + "virtues_commit", "weights", "weights_sha256", "esm_model", "uniprot_release", "channels", + "unembedded", "stats", "pixel_size", "model_um_per_px", "crop_size", "crop_step", "patch_size", + "padding", "tile_size", "batch_size", "device", "n_cells", "n_cells_without_pixel", + "n_niches_kept", "n_niches_dropped", +} # fmt: skip + + +def test_cli_outputs_layout(tmp_path, monkeypatch): + rc, out = run_cli(tmp_path, monkeypatch, roi=box(0, 0, 260, 300)) # left half: square 0 only + assert rc == 0 + import anndata as ad + import geopandas as gpd + + names = [f"virtues_{i}" for i in range(512)] + cp = ad.read_h5ad(out / "cellpose_virtues.h5ad") + assert list(cp.obs_names) == ["cp_3", "cp_2", "cp_1", "cp_0"] + assert cp.X.dtype == np.float16 and list(cp.var_names) == names + assert {"region", "slide", "core_id", "cell_id"} <= set(cp.obs.columns) + assert set(cp.obs["region"]) == {"cellpose_cells"} + assert cp.uns["spatialdata_attrs"]["instance_key"] == "cell_id" + x = np.asarray(cp.X, dtype=np.float32) + assert np.isnan(x[0]).all() and np.isfinite(x[1:]).all() + # CD45 (column 0) is bright only in cp_1: a misaligned shape/table join breaks this + assert x[2, 0] > x[1, 0] + 1 and x[2, 0] > x[3, 0] + 1 + sdist = ad.read_h5ad(out / "stardist_virtues.h5ad") + assert list(sdist.obs_names) == ["sd_1", "sd_0"] and np.isfinite(np.asarray(sdist.X, np.float32)).all() + + uns = cp.uns["virtues"] + assert set(uns) == UNS_KEYS + assert dict(uns["channels"]) == dict(PANEL) and list(uns["unembedded"]) == ["DNA"] + assert dict(uns["n_cells"]) == {"cellpose": 4, "stardist": 2} + assert dict(uns["n_cells_without_pixel"]) == {"cellpose": 1, "stardist": 0} + assert uns["n_niches_kept"] == 1 and uns["n_niches_dropped"] == 1 + assert uns["pixel_size"] == 0.5 and uns["batch_size"] == vc.BATCH and uns["device"] == "cuda" + assert set(json.loads((out / "virtues.json").read_text())) == UNS_KEYS + + niches = gpd.read_parquet(out / "virtues_niches.parquet") + assert list(niches.index) == ["niche_0"] + assert niches.geometry.iloc[0].equals(box(0, 0, 256, 256)) # model 128 px at 0.5 um/px + nt = ad.read_h5ad(out / "virtues_niches_table.h5ad") + assert list(nt.obs_names) == ["niche_0"] and list(nt.obs["niche_id"]) == ["niche_0"] + assert nt.obs["tissue_fraction"].iloc[0] == 1.0 + assert nt.obs["slide"].iloc[0] == "S" and nt.obs["core_id"].iloc[0] == "A1" + assert nt.X.dtype == np.float16 and nt.X.shape == (1, 512) + assert nt.uns["spatialdata_attrs"]["region"] == "virtues_niches" + assert nt.uns["spatialdata_attrs"]["instance_key"] == "niche_id" + assert set(nt.uns["virtues"]) == UNS_KEYS + + tissue = ad.read_h5ad(out / "virtues_tissue.h5ad") + assert tissue.n_obs == 1 and tissue.X.dtype == np.float16 + assert tissue.obs["slide"].iloc[0] == "S" and tissue.obs["core_id"].iloc[0] == "A1" + assert tissue.obs["n_niches"].iloc[0] == 1 + assert np.array_equal(tissue.X, nt.X) + assert set(tissue.uns["virtues"]) == UNS_KEYS + + +def test_cli_coarse_roi_and_cells_match_scale0(tmp_path, monkeypatch): + # sopa's tissue() keeps the ROI in its coarsest level's pixels; cells may sit on a level too + import anndata as ad + + _, ref = run_cli(tmp_path / "ref", monkeypatch, roi=box(0, 0, 260, 300)) + _, out = run_cli(tmp_path / "coarse", monkeypatch, roi=box(0, 0, 260, 300), roi_scale=16, cell_scale=2) + for f in ("cellpose_virtues", "stardist_virtues", "virtues_niches_table", "virtues_tissue"): + a, b = ad.read_h5ad(ref / f"{f}.h5ad"), ad.read_h5ad(out / f"{f}.h5ad") + assert np.array_equal(np.asarray(a.X), np.asarray(b.X), equal_nan=True), f + nt = ad.read_h5ad(out / "virtues_niches_table.h5ad") + assert list(nt.obs["tissue_fraction"]) == [1.0] + + +def test_cli_no_niche_writes_no_niche_files(tmp_path, monkeypatch): + rc, out = run_cli(tmp_path, monkeypatch, roi=box(0, 0, 20, 20)) + assert rc == 0 + import anndata as ad + + assert not (out / "virtues_niches.parquet").exists() + assert not (out / "virtues_niches_table.h5ad").exists() + tissue = ad.read_h5ad(out / "virtues_tissue.h5ad") + assert tissue.X.shape == (1, 512) and np.isnan(np.asarray(tissue.X, np.float32)).all() + assert tissue.obs["n_niches"].iloc[0] == 0 + uns = tissue.uns["virtues"] + assert uns["n_niches_kept"] == 0 and uns["n_niches_dropped"] == 2 + assert (out / "cellpose_virtues.h5ad").exists() + + +def test_cli_missing_roi_embeds_cells_with_nan_tissue(tmp_path, monkeypatch, capsys): + # sopa writes no ROI when it finds no tissue, e.g. a nearly empty TMA core + rc, out = run_cli(tmp_path, monkeypatch, roi=None) + assert rc == 0 + import anndata as ad + + assert "tissue segmentation found no tissue in" in capsys.readouterr().err + assert not (out / "virtues_niches_table.h5ad").exists() + tissue = ad.read_h5ad(out / "virtues_tissue.h5ad") + assert np.isnan(np.asarray(tissue.X, np.float32)).all() and tissue.obs["n_niches"].iloc[0] == 0 + cp = ad.read_h5ad(out / "cellpose_virtues.h5ad") + assert np.isfinite(np.asarray(cp.X, np.float32)[1:]).all() + + +def test_unknown_uniprot_id_exits_naming_it(tmp_path, monkeypatch, capsys): + panel = [*PANEL[:2], ("PanCK", "Q99999")] + with pytest.raises(SystemExit) as e: + run_cli(tmp_path, monkeypatch, roi=box(0, 0, 260, 300), panel=panel, stats_panel=panel) + assert e.value.code == 1 and "Q99999" in capsys.readouterr().err + + +def test_stats_mismatch_exits(tmp_path, monkeypatch, capsys): + stats_panel = [*PANEL[:2], ("PanCK", "P08575-8")] + with pytest.raises(SystemExit) as e: + run_cli(tmp_path, monkeypatch, roi=box(0, 0, 260, 300), stats_panel=stats_panel) + err = capsys.readouterr().err + assert e.value.code == 1 and "PanCK" in err and "P08575-8" in err + + +def test_unknown_channel_exits_naming_it(tmp_path, monkeypatch, capsys): + panel = [*PANEL, ("NOPE", "P08575")] + with pytest.raises(SystemExit) as e: + run_cli(tmp_path, monkeypatch, roi=box(0, 0, 260, 300), panel=panel, stats_panel=panel) + err = capsys.readouterr().err + assert e.value.code == 1 and "NOPE" in err and "DNA" in err + + +def test_non_cuda_device_exits(tmp_path, monkeypatch, capsys): + with pytest.raises(SystemExit) as e: + run_cli(tmp_path, monkeypatch, roi=box(0, 0, 260, 300), device="cpu") + assert e.value.code == 1 and "cpu" in capsys.readouterr().err + + +def test_uniprot_sequences(tmp_path): + fasta = tmp_path / "u.fasta" + fasta.write_text(FASTA) + seqs = vc.uniprot_sequences(fasta, ["P05787", "P08575-8", "P08575"]) + assert seqs == {"P05787": "MSIRVTQKSYKVSTSGPRAF", "P08575-8": "MYLWLK", "P08575": "MYLWLKLLAFGFAFLDTEVF"} + with pytest.raises(KeyError, match="Q99999"): + vc.uniprot_sequences(fasta, ["P05787", "Q99999"]) + + +def test_cell_source_clips_to_model_grid(): + # 1003 image px at 0.65 um/px is 651 model px; model row 651's centre (image y 1002.3) is in the image + h = vs.model_shape((1003, 40), 0.65) + src = vc.cell_source([box(0, 990, 20, 1003), box(0, 1010, 20, 1020)], 0.65, h) + labels = src.read_labels(vc.PAD + 640, vc.PAD + 660, vc.PAD, vc.PAD + 20) + assert (labels[: 651 - 640] == 1).any() and not labels[651 - 640 :].any() + assert src.bboxes[0, 1] == vc.PAD + 651 and (src.bboxes[1] == 0).all() diff --git a/tests/unit/test_virtues_model.py b/tests/unit/test_virtues_model.py new file mode 100644 index 0000000..4bba1e6 --- /dev/null +++ b/tests/unit/test_virtues_model.py @@ -0,0 +1,38 @@ +"""Real-model tests for virtues_cells; run in the virtues image on a GPU, skipped elsewhere.""" + +import os + +import numpy as np +import pytest + +pytest.importorskip("virtues", reason="needs the virtues image") +pytest.importorskip("flash_attn", reason="needs the virtues image") +torch = pytest.importorskip("torch") +pytestmark = pytest.mark.skipif(not torch.cuda.is_available(), reason="needs a CUDA GPU") + +import virtues_cells as vc # noqa: E402 + +IDS = ["P08575", "P07766", "P05787"] # CD45, CD3E, KRT8 + + +@pytest.fixture(scope="module") +def encode(): + seqs = vc.uniprot_sequences(os.environ["VIRTUES_UNIPROT"], IDS) + model = vc.load_virtues(os.environ["VIRTUES_WEIGHTS"], [seqs[i] for i in IDS], "cuda") + return vc.virtues_encoder(model, len(IDS), "cuda") + + +def crops(n, seed=0): + return np.random.default_rng(seed).normal(size=(n, len(IDS), vc.CROP, vc.CROP)).astype(np.float32) + + +def test_encoder_shape(encode): + out = encode(crops(3)) + assert out.shape == (3, vc.GRID, vc.GRID, 512) and out.dtype == np.float32 + assert np.isfinite(out).all() + assert encode(crops(0)).shape == (0, vc.GRID, vc.GRID, 512) + + +def test_determinism(encode): + x = crops(5, seed=1) + assert np.array_equal(encode(x), encode(x)) diff --git a/tests/unit/test_virtues_stats.py b/tests/unit/test_virtues_stats.py new file mode 100644 index 0000000..c1b9620 --- /dev/null +++ b/tests/unit/test_virtues_stats.py @@ -0,0 +1,243 @@ +"""Model scale, window independence and slide statistics for VirTues.""" + +import json + +import numpy as np +import pytest +from shapely.geometry import box + +import virtues_stats as vs + + +def test_resample_identity_at_one_um(): + img = np.random.default_rng(0).integers(0, 1000, (1, 20, 30)).astype(np.uint16) + out = vs.resample_window(img, 0, 0, 20, 0, 30, 1.0) + assert out.dtype == np.float32 and np.array_equal(out, img[0].astype(np.float32)) + + +def test_resample_area_average(): + img = np.arange(16, dtype=np.uint16).reshape(1, 4, 4) + out = vs.resample_window(img, 0, 0, 2, 0, 2, 0.5) + expected = img[0].astype(float).reshape(2, 2, 2, 2).mean(axis=(1, 3)) + assert vs.model_shape((4, 4), 0.5) == (2, 2) + assert np.allclose(out, expected) + + +def test_resample_window_independent_bit_for_bit(): + rng = np.random.default_rng(1) + img = rng.integers(0, 65535, (1, 300, 300)).astype(np.uint16) + h, w = vs.model_shape((300, 300), 0.65) + whole = vs.resample_window(img, 0, 0, h, 0, w, 0.65) + for _ in range(20): + y0, x0 = rng.integers(0, h - 1), rng.integers(0, w - 1) + y1, x1 = rng.integers(y0 + 1, h + 1), rng.integers(x0 + 1, w + 1) + assert np.array_equal(vs.resample_window(img, 0, y0, y1, x0, x1, 0.65), whole[y0:y1, x0:x1]) + + +def test_resample_upsampling(): + img = np.arange(6, dtype=np.uint16).reshape(1, 2, 3) + out = vs.resample_window(img, 0, 0, 4, 0, 6, 2.0) + assert out.shape == (4, 6) + assert np.array_equal(out, np.repeat(np.repeat(img[0], 2, axis=0), 2, axis=1).astype(np.float32)) + + +def test_tissue_mask_pixel_centres(): + mask = vs.tissue_mask([box(0, 0, 10, 10)], 0, 40, 0, 40, 0.5) + assert mask[:5, :5].all() and mask.sum() == 25 + + +def make_hist(rng, scale): + img = rng.integers(0, scale, (1, 64, 64)).astype(np.uint16) + return img, vs.histogram(img, [box(0, 0, 64, 64)], [0], 1.0, rows=16) + + +def test_stats_equal_numpy(): + rng = np.random.default_rng(2) + (a, ha), (b, hb) = make_hist(rng, 500), make_hist(rng, 3000) + pooled = np.concatenate([a.ravel(), b.ravel()]).astype(np.float64) + s = vs.stats_from_histogram(ha[0] + hb[0]) + cap = np.quantile(pooled, 0.99) + x = np.log1p(np.minimum(pooled, cap)) + assert s["cap"] == cap and s["tissue_pixels"] == pooled.size + assert np.isclose(s["mean"], x.mean(), rtol=1e-12) and np.isclose(s["sd"], x.std(), rtol=1e-12) + + +def test_histogram_only_tissue(): + rng = np.random.default_rng(3) + img = rng.integers(0, 100, (1, 64, 64)).astype(np.uint16) + poly = [box(0, 0, 32, 32)] + base = vs.histogram(img, poly, [0], 1.0) + img[:, 40:, 40:] = 9999 + assert np.array_equal(vs.histogram(img, poly, [0], 1.0), base) + assert base.sum() == 32 * 32 + + +def test_float_image_refused(): + with pytest.raises(TypeError, match="float32"): + vs.histogram(np.zeros((1, 8, 8), dtype=np.float32), [box(0, 0, 8, 8)], [0], 1.0) + + +def test_constant_marker_refused(): + counts = np.zeros(vs.N_BINS, dtype=np.int64) + counts[100] = 50 + with pytest.raises(ValueError, match="constant"): + vs.stats_from_histogram(counts) + + +def test_no_tissue_refused(): + with pytest.raises(ValueError, match="no tissue"): + vs.stats_from_histogram(np.zeros(vs.N_BINS, dtype=np.int64)) + + +def write_hist(path, sample, markers, ids, seed=0): + counts = np.zeros((len(markers), vs.N_BINS), dtype=np.int64) + counts[:, :200] = np.random.default_rng(seed).integers(1, 20, (len(markers), 200)) + np.savez(path, counts=counts, markers=np.array(markers), uniprot_ids=np.array(ids), sample=sample) + + +def test_combine_writes_layout(tmp_path): + write_hist(tmp_path / "a.npz", "A", ["CD3", "CD8"], ["P07766", "P01732"], 1) + write_hist(tmp_path / "b.npz", "B", ["CD3", "CD8"], ["P07766", "P01732"], 2) + out = tmp_path / "s.json" + vs.combine([tmp_path / "a.npz", tmp_path / "b.npz"], "SL", 0.65, out) + doc = json.loads(out.read_text()) + assert doc["format"] == 1 and doc["cores"] == ["A", "B"] and doc["pixel_size"] == 0.65 + assert set(doc["markers"]["CD3"]) == {"uniprot_id", "cap", "mean", "sd", "tissue_pixels"} + assert vs.load_stats(out, [("CD3", "P07766")])["CD3"]["uniprot_id"] == "P07766" + + +def test_combine_refuses_mismatched_markers(tmp_path): + write_hist(tmp_path / "a.npz", "A", ["CD3"], ["P07766"]) + write_hist(tmp_path / "b.npz", "B", ["CD3"], ["P99999"]) + with pytest.raises(ValueError, match="P99999"): + vs.combine([tmp_path / "a.npz", tmp_path / "b.npz"], "SL", 1.0, tmp_path / "o.json") + + +def test_load_stats_id_mismatch(tmp_path): + write_hist(tmp_path / "a.npz", "A", ["CD3"], ["P07766"]) + vs.combine([tmp_path / "a.npz"], "SL", 1.0, tmp_path / "s.json") + with pytest.raises(ValueError, match="P11111"): + vs.load_stats(tmp_path / "s.json", [("CD3", "P11111")]) + + +def test_histogram_tiling_independent(): + rng = np.random.default_rng(4) + img = rng.integers(0, 4000, (2, 150, 170)).astype(np.uint16) + poly = [box(10, 5, 120, 140), box(130, 20, 165, 60)] + assert np.array_equal( + vs.histogram(img, poly, [0, 1], 0.65, rows=16), vs.histogram(img, poly, [0, 1], 0.65) + ) + + +WHOLE = box(0, 0, 40, 40) + + +def write_store(tmp_path, data, roi=WHOLE, roi_scale=1): + """A real store; the ROI is kept 1/roi_scale in size with Scale(roi_scale), as sopa's tissue() does.""" + import geopandas as gpd + import spatialdata as sd + from shapely.affinity import scale + from spatialdata.models import Image2DModel, ShapesModel + from spatialdata.transformations import Scale + + shapes = {} + if roi is not None: + shapes[vs.TISSUE_KEY] = ShapesModel.parse( + gpd.GeoDataFrame(geometry=[scale(roi, 1 / roi_scale, 1 / roi_scale, origin=(0, 0))]), + transformations={"global": Scale([roi_scale, roi_scale], axes=("x", "y"))}, + ) + image = Image2DModel.parse(data, dims=("c", "y", "x"), c_coords=["CD3", "CD8"]) + sdata = sd.SpatialData(images={"img": image}, shapes=shapes) + sdata.attrs["cell_segmentation_image"] = "img" + path = tmp_path / "s.zarr" + sdata.write(path) + return path + + +def run_cli(tmp_path, dtype=np.uint16, shape=(2, 40, 40), pixel_size=1.0, **store): + pytest.importorskip("spatialdata") + data = np.random.default_rng(5).integers(0, 500, shape).astype(dtype) + path = write_store(tmp_path, data, **store) + out = tmp_path / "S1_virtues_hist.npz" + argv = ["histogram", "--sdata", str(path), "--channels", "CD3:P07766,CD8:P01732"] + return out, data, lambda: vs.main([*argv, "--pixel-size", str(pixel_size), "--output", str(out)]) + + +def test_cli_histogram_writes_npz(tmp_path): + out, _, run = run_cli(tmp_path) + run() + with np.load(out) as z: + assert z["counts"].shape == (2, vs.N_BINS) and z["counts"].sum() == 2 * 40 * 40 + assert list(z["markers"]) == ["CD3", "CD8"] and list(z["uniprot_ids"]) == ["P07766", "P01732"] + assert str(z["sample"]) == "S1" + + +def test_to_image_pixels_undoes_roi_scale(): + import geopandas as gpd + from spatialdata.models import Image2DModel, ShapesModel + from spatialdata.transformations import Scale + + image = Image2DModel.parse(np.zeros((1, 8, 8), np.uint16), dims=("c", "y", "x")) + roi = ShapesModel.parse( + gpd.GeoDataFrame(geometry=[box(4, 6, 14, 16)]), + transformations={"global": Scale([16, 16], axes=("x", "y"))}, + ) + assert vs.to_image_pixels(roi, image)[0].equals(box(64, 96, 224, 256)) + + +@pytest.mark.parametrize("pixel_size", [1.0, 0.65]) +def test_cli_roi_on_coarse_level_counts_scale0_pixels(tmp_path, pixel_size): + # sopa's tissue() keeps the ROI in its coarsest level's pixels, with a scale to global + truth = box(64, 96, 224, 256) + out, data, run = run_cli(tmp_path, shape=(2, 320, 320), pixel_size=pixel_size, roi=truth, roi_scale=16) + run() + with np.load(out) as z: + counts = z["counts"] + assert np.array_equal(counts, vs.histogram(data, [truth], [0, 1], pixel_size)) + if pixel_size == 1.0: + assert counts.sum(axis=1).tolist() == [160 * 160] * 2 + + +def test_cli_float_image_exits_naming_dtype(tmp_path): + _, _, run = run_cli(tmp_path, dtype=np.float32) + with pytest.raises(SystemExit) as e: + run() + assert "float32" in str(e.value) + + +def test_cli_missing_roi_counts_zero_tissue(tmp_path, capsys): + # sopa writes no ROI when it finds no tissue, e.g. a nearly empty TMA core + out, _, run = run_cli(tmp_path, roi=None) + run() + with np.load(out) as z: + assert z["counts"].shape == (2, vs.N_BINS) and z["counts"].sum() == 0 + assert f"tissue segmentation found no tissue in {tmp_path / 's.zarr'}" in capsys.readouterr().err + + +def test_combine_slide_without_tissue_names_it(tmp_path): + empty = np.zeros((1, vs.N_BINS), dtype=np.int64) + np.savez( + tmp_path / "a.npz", + counts=empty, + markers=np.array(["CD3"]), + uniprot_ids=np.array(["P07766"]), + sample="A", + ) + args = ["combine", "--slide", "SL", "--pixel-size", "1.0", "--output", str(tmp_path / "s.json")] + with pytest.raises(SystemExit) as e: + vs.main([*args, str(tmp_path / "a.npz")]) + assert "tissue segmentation found no tissue on slide SL" in str(e.value) + + +def test_combine_constant_marker_names_remedy(tmp_path): + counts = np.zeros((1, vs.N_BINS), dtype=np.int64) + counts[0, 100] = 50 + np.savez( + tmp_path / "a.npz", + counts=counts, + markers=np.array(["CD3"]), + uniprot_ids=np.array(["P07766"]), + sample="A", + ) + with pytest.raises(ValueError, match="slide SL, marker CD3: .*constant.*uniprot_id.*virtues_stats"): + vs.combine([tmp_path / "a.npz"], "SL", 1.0, tmp_path / "s.json") diff --git a/tests/unit/test_write_features.py b/tests/unit/test_write_features.py new file mode 100644 index 0000000..49ab522 --- /dev/null +++ b/tests/unit/test_write_features.py @@ -0,0 +1,163 @@ +"""Tests for bin/write_features.py on a real SpatialData store built in tmp_path.""" + +import anndata as ad +import geopandas as gpd +import numpy as np +import pandas as pd +import pytest +import spatialdata as sd +from shapely.geometry import box +from spatialdata.models import Image2DModel, ShapesModel, TableModel +from write_features import write_features +from write_segmentations import RESERVED, write_segmentations + +IDS = ["c0", "c1", "c2"] + + +def parsed_table(ids, var, region="cellpose_cells", uns=None): + obs = pd.DataFrame({"region": pd.Categorical([region] * len(ids)), "cell_id": ids}, index=ids) + adata = ad.AnnData(np.ones((len(ids), len(var)), dtype="float32"), obs=obs, var=pd.DataFrame(index=var)) + adata.uns.update(uns or {}) + return TableModel.parse(adata, region=region, region_key="region", instance_key="cell_id") + + +@pytest.fixture +def store(tmp_path): + image = Image2DModel.parse( + np.ones((2, 64, 64), dtype=np.uint16), dims=("c", "y", "x"), c_coords=["A", "B"] + ) + shapes = ShapesModel.parse( + gpd.GeoDataFrame( + geometry=[box(i * 10, 0, i * 10 + 5, 5) for i in range(3)], + index=pd.Index(IDS, name="cell_id"), + ) + ) + path = tmp_path / "sample.zarr" + sdata = sd.SpatialData( + images={"img": image}, + shapes={"cellpose_cells": shapes}, + tables={"cellpose_table": parsed_table(IDS, ["A", "B"])}, + ) + sdata.attrs["cell_segmentation_image"] = "img" + sdata.write(path) + return path + + +def nimbus_h5ad(tmp_path, ids=IDS): + p = tmp_path / "cellpose_nimbus.h5ad" + parsed_table(ids, ["A", "B"], uns={"nimbus": {"version": "0.0.5"}}).write_h5ad(p) + return p + + +def test_writes_table_and_uns(store, tmp_path): + write_features(store, [nimbus_h5ad(tmp_path)]) + out = sd.read_zarr(store) + assert "cellpose_nimbus" in out.tables + assert list(out.tables["cellpose_nimbus"].obs_names) == IDS + assert out.tables["cellpose_nimbus"].uns["nimbus"]["version"] == "0.0.5" + assert "cellpose_table" in out.tables + + +def test_refuses_row_mismatch(store, tmp_path): + for ids in (["c2", "c1", "c0"], ["c0", "c1"]): + with pytest.raises(ValueError, match="cellpose_nimbus.*cellpose_table"): + write_features(store, [nimbus_h5ad(tmp_path, ids)]) + assert "cellpose_nimbus" not in sd.read_zarr(store).tables + + +def test_rerun_is_idempotent(store, tmp_path): + h5ad = nimbus_h5ad(tmp_path) + write_features(store, [h5ad]) + write_features(store, [h5ad]) + out = sd.read_zarr(store) + assert sorted(out.tables) == ["cellpose_nimbus", "cellpose_table"] + args = ([niche_h5ad(tmp_path), tissue_h5ad(tmp_path)], [niche_parquet(tmp_path)]) + write_features(store, *args) + write_features(store, *args) + out = sd.read_zarr(store) + assert sorted(out.shapes) == ["cellpose_cells", "virtues_niches"] + assert sorted(out.tables) == [ + "cellpose_nimbus", + "cellpose_table", + "virtues_niches_table", + "virtues_tissue", + ] + + +def test_write_segmentations_removes_stale_nimbus(store, tmp_path): + write_features(store, [nimbus_h5ad(tmp_path)]) + assert RESERVED.match("cellpose_nimbus") + table = tmp_path / "cellpose_table.h5ad" + parsed_table(IDS, ["A", "B"]).write_h5ad(table) + write_segmentations(store, [], [table]) + assert "cellpose_nimbus" not in sd.read_zarr(store).tables + + +NICHES = ["niche_0", "niche_1"] + + +def niche_parquet(tmp_path, ids=NICHES): + p = tmp_path / "virtues_niches.parquet" + gpd.GeoDataFrame( + geometry=[box(i * 20, 0, i * 20 + 16, 16) for i in range(len(ids))], index=pd.Index(ids) + ).to_parquet(p) + return p + + +def niche_h5ad(tmp_path, ids=NICHES): + p = tmp_path / "virtues_niches_table.h5ad" + obs = pd.DataFrame({"region": pd.Categorical(["virtues_niches"] * len(ids)), "niche_id": ids}, index=ids) + adata = ad.AnnData(np.ones((len(ids), 4), dtype="float32"), obs=obs) + TableModel.parse(adata, region="virtues_niches", region_key="region", instance_key="niche_id").write_h5ad( + p + ) + return p + + +def tissue_h5ad(tmp_path): + p = tmp_path / "virtues_tissue.h5ad" + adata = ad.AnnData( + np.ones((1, 4), dtype="float32"), obs=pd.DataFrame({"slide": ["s"]}, index=["tissue_0"]) + ) + TableModel.parse(adata).write_h5ad(p) + return p + + +def test_writes_niches_shapes_and_table(store, tmp_path): + write_features(store, [niche_h5ad(tmp_path)], [niche_parquet(tmp_path)]) + out = sd.read_zarr(store) + assert list(out.shapes["virtues_niches"].index) == NICHES + assert list(out.tables["virtues_niches_table"].obs_names) == NICHES + assert out.tables["virtues_niches_table"].uns["spatialdata_attrs"]["region"] == "virtues_niches" + + +def test_writes_unannotated_tissue_table(store, tmp_path): + write_features(store, [tissue_h5ad(tmp_path)]) + out = sd.read_zarr(store) + assert list(out.tables["virtues_tissue"].obs_names) == ["tissue_0"] + assert "region" not in out.tables["virtues_tissue"].uns.get("spatialdata_attrs", {}) + + +def test_niche_table_rows_must_match_shapes(store, tmp_path): + with pytest.raises(ValueError, match="virtues_niches_table"): + write_features(store, [niche_h5ad(tmp_path, ["niche_1", "niche_0"])], [niche_parquet(tmp_path)]) + with pytest.raises(ValueError, match="virtues_niches_table"): + write_features(store, [niche_h5ad(tmp_path)], []) + assert "virtues_niches" not in sd.read_zarr(store).shapes + + +def test_nimbus_tables_still_checked_against_method_table(store, tmp_path): + with pytest.raises(ValueError, match="cellpose_nimbus.*cellpose_table"): + write_features(store, [nimbus_h5ad(tmp_path, ["c1", "c0", "c2"])], [niche_parquet(tmp_path)]) + + +def test_write_segmentations_removes_stale_virtues_elements(store, tmp_path): + write_features(store, [niche_h5ad(tmp_path), tissue_h5ad(tmp_path)], [niche_parquet(tmp_path)]) + for name in ("virtues_niches", "virtues_niches_table", "virtues_tissue", "cellpose_virtues"): + assert RESERVED.match(name) + table = tmp_path / "cellpose_table.h5ad" + parsed_table(IDS, ["A", "B"]).write_h5ad(table) + write_segmentations(store, [], [table]) + out = sd.read_zarr(store) + assert "virtues_niches" not in out.shapes + assert not {"virtues_niches_table", "virtues_tissue"} & set(out.tables) diff --git a/tests/validate_markersheet.nf.test b/tests/validate_markersheet.nf.test index 5307126..e894c38 100644 --- a/tests/validate_markersheet.nf.test +++ b/tests/validate_markersheet.nf.test @@ -238,6 +238,27 @@ nextflow_function { } } + test("with backsub, a Nimbus channel that is removed is rejected") { + when { + params { + use_backsub = true + nimbus_channels = 'CD45' + } + function { + """ + input[0] = [ + [ channel_number: 1, cycle_number: 1, marker_name: 'DAPI', channel_role: 'dna', exposure: 100 ], + [ channel_number: 2, cycle_number: 1, marker_name: 'CD45', channel_role: 'marker', exposure: 100, remove: true ] + ] + """ + } + } + then { + assert function.failed + assert function.stdout.any { it.contains("nimbus_channels") && it.contains("[CD45]") } + } + } + test("with use_gpu, InstanSeg's default of 11 channels is rejected before stitching") { when { params { diff --git a/tests/validate_params.nf.test b/tests/validate_params.nf.test index 077acdd..bbf3414 100644 --- a/tests/validate_params.nf.test +++ b/tests/validate_params.nf.test @@ -63,11 +63,81 @@ nextflow_function { } } + test("use_instanseg without pixel_size is rejected") { + when { + function { + """ + input[0] = [ use_instanseg: true, use_preprocessing: true ] + """ + } + } + then { + assert function.failed + assert function.stdout.any { it.contains("use_instanseg requires pixel_size") } + } + } + + test("use_nimbus without pixel_size is rejected") { + when { + function { + """ + input[0] = [ use_cellpose: true, cellpose_channels: 'DAPI', use_nimbus: true, nimbus_channels: 'CD3' ] + """ + } + } + then { + assert function.failed + assert function.stdout.any { it.contains("use_nimbus requires pixel_size") } + } + } + + test("use_nimbus without segment_cells is rejected") { + when { + function { + """ + input[0] = [ use_cellpose: true, cellpose_channels: 'DAPI', pixel_size: 0.65, segment_cells: false, segment_nuclei: true, use_nimbus: true, nimbus_channels: 'CD3' ] + """ + } + } + then { + assert function.failed + assert function.stdout.any { it.contains("use_nimbus requires segment_cells") } + } + } + + test("use_nimbus without preprocessing needs nimbus_channels") { + when { + function { + """ + input[0] = [ use_cellpose: true, cellpose_channels: 'DAPI', use_nimbus: true, pixel_size: 0.65, use_preprocessing: false ] + """ + } + } + then { + assert function.failed + assert function.stdout.any { it.contains("use_nimbus without use_preprocessing needs nimbus_channels") } + } + } + + test("conflicting pixel sizes stop every run") { + when { + function { + """ + input[0] = [ use_cellpose: true, cellpose_channels: 'DAPI', pixel_size: 0.5, instanseg_pixel_size: 0.65 ] + """ + } + } + then { + assert function.failed + assert function.stdout.any { it.contains("differ; set only pixel_size") } + } + } + test("both methods with use_gpu are accepted") { when { function { """ - input[0] = [ use_cellpose: true, cellpose_channels: 'DAPI', use_instanseg: true, instanseg_pixel_size: 0.65, + input[0] = [ use_cellpose: true, cellpose_channels: 'DAPI', use_instanseg: true, pixel_size: 0.65, instanseg_channels: 'DAPI', use_gpu: true ] """ } @@ -81,7 +151,7 @@ nextflow_function { when { function { """ - input[0] = [ use_instanseg: true, instanseg_pixel_size: 0.65, use_gpu: true, + input[0] = [ use_instanseg: true, pixel_size: 0.65, use_gpu: true, instanseg_channels: (1..10).collect { "M\$it" }.join(' ') ] """ } @@ -95,7 +165,7 @@ nextflow_function { when { function { """ - input[0] = [ use_instanseg: true, instanseg_pixel_size: 0.65, use_gpu: true, + input[0] = [ use_instanseg: true, pixel_size: 0.65, use_gpu: true, instanseg_channels: (1..11).collect { "M\$it" }.join(' ') ] """ } @@ -295,4 +365,101 @@ nextflow_function { assert function.stdout.any { it.contains("quantification_statistics lists mean twice") } } } + + test("use_virtues with every requirement is accepted") { + when { + function { + """ + input[0] = [ use_cellpose: true, use_virtues: true, use_gpu: true, use_preprocessing: true, use_tissue_segmentation: true, pixel_size: 0.65 ] + """ + } + } + then { + assert function.success + } + } + + test("use_virtues without use_gpu is rejected") { + when { + function { + """ + input[0] = [ use_cellpose: true, use_virtues: true, use_gpu: false, use_preprocessing: true, use_tissue_segmentation: true, pixel_size: 0.65 ] + """ + } + } + then { + assert function.failed + assert function.stdout.any { it.contains("use_virtues requires use_gpu: VirTues runs on FlashAttention, which has no CPU path.") } + } + } + + test("use_virtues without use_preprocessing is rejected") { + when { + function { + """ + input[0] = [ use_cellpose: true, use_virtues: true, use_gpu: true, use_preprocessing: false, use_tissue_segmentation: true, pixel_size: 0.65 ] + """ + } + } + then { + assert function.failed + assert function.stdout.any { it.contains("use_virtues requires use_preprocessing: UniProt IDs come from the marker sheet, which pre-stitched input does not have.") } + } + } + + test("use_virtues without use_tissue_segmentation is rejected") { + when { + function { + """ + input[0] = [ use_cellpose: true, use_virtues: true, use_gpu: true, use_preprocessing: true, use_tissue_segmentation: false, pixel_size: 0.65 ] + """ + } + } + then { + assert function.failed + assert function.stdout.any { it.contains("use_virtues requires use_tissue_segmentation: intensity statistics are computed over tissue pixels.") } + } + } + + test("use_virtues without segment_cells is rejected") { + when { + function { + """ + input[0] = [ use_cellpose: true, use_virtues: true, use_gpu: true, use_preprocessing: true, use_tissue_segmentation: true, pixel_size: 0.65, segment_cells: false, segment_nuclei: true ] + """ + } + } + then { + assert function.failed + assert function.stdout.any { it.contains("use_virtues requires segment_cells: VirTues embeds cells, so there must be a cell segmentation.") } + } + } + + test("use_virtues without pixel_size is rejected") { + when { + function { + """ + input[0] = [ use_cellpose: true, use_virtues: true, use_gpu: true, use_preprocessing: true, use_tissue_segmentation: true ] + """ + } + } + then { + assert function.failed + assert function.stdout.any { it.contains("use_virtues requires pixel_size (microns per pixel of the image): VirTues runs at 1 µm per pixel.") } + } + } + + test("virtues_stats without use_virtues is rejected") { + when { + function { + """ + input[0] = [ use_cellpose: true, use_gpu: true, use_preprocessing: true, use_tissue_segmentation: true, pixel_size: 0.65, virtues_stats: '/x/s.json' ] + """ + } + } + then { + assert function.failed + assert function.stdout.any { it.contains("virtues_stats is set but use_virtues is not.") } + } + } } diff --git a/tests/validate_virtues_markers.nf.test b/tests/validate_virtues_markers.nf.test new file mode 100644 index 0000000..67652fc --- /dev/null +++ b/tests/validate_virtues_markers.nf.test @@ -0,0 +1,164 @@ +// Marker sheet checks for use_virtues. Each rule is seen to fail with its message. + +nextflow_function { + + name "validateVirtuesMarkers" + script "../subworkflows/local/utils_nfcore_histo_pipeline/main.nf" + function "validateVirtuesMarkers" + tag "unit" + tag "validation" + + test("a sheet with unique IDs on markers is accepted") { + when { + params { use_backsub = false } + function { + """ + input[0] = [ + [ marker_name: 'DNA_1', channel_role: 'dna' ], + [ marker_name: 'ELANE', channel_role: 'marker', uniprot_id: 'P08246' ], + [ marker_name: 'CD11B', channel_role: 'marker', uniprot_id: 'P11215' ], + ] + input[1] = 'sheet' + """ + } + } + then { + assert function.success + } + } + + test("a sheet with no uniprot_id is rejected") { + when { + params { use_backsub = false } + function { + """ + input[0] = [ + [ marker_name: 'DNA_1', channel_role: 'dna' ], + [ marker_name: 'ELANE', channel_role: 'marker' ], + ] + input[1] = 'sheet' + """ + } + } + then { + assert function.failed + assert function.stdout.any { it.contains("sheet: use_virtues needs a uniprot_id on at least one marker row; a channel is embedded only when it has one.") } + } + } + + test("a DNA row with a uniprot_id is rejected") { + when { + params { use_backsub = false } + function { + """ + input[0] = [ + [ marker_name: 'DNA_1', channel_role: 'dna', uniprot_id: 'P08246' ], + [ marker_name: 'ELANE', channel_role: 'marker', uniprot_id: 'P11215' ], + ] + input[1] = 'sheet' + """ + } + } + then { + assert function.failed + assert function.stdout.any { it.contains("sheet: DNA stains are not embedded; remove the uniprot_id from: [DNA_1].") } + } + } + + test("a repeated uniprot_id is rejected") { + when { + params { use_backsub = false } + function { + """ + input[0] = [ + [ marker_name: 'ELANE', channel_role: 'marker', uniprot_id: 'P08246' ], + [ marker_name: 'ELANE2', channel_role: 'marker', uniprot_id: 'P08246' ], + ] + input[1] = 'sheet' + """ + } + } + then { + assert function.failed + assert function.stdout.any { it.contains("sheet: uniprot_id must be unique. Repeated: [P08246].") } + } + } + + test("stats missing a marker are rejected") { + when { + params { use_backsub = false } + function { + """ + input[0] = [ + [ marker_name: 'ELANE', channel_role: 'marker', uniprot_id: 'P08246' ], + [ marker_name: 'CD11B', channel_role: 'marker', uniprot_id: 'P11215' ], + ] + input[1] = 'sheet' + input[2] = [ format: 1, markers: [ ELANE: [ uniprot_id: 'P08246' ] ] ] + """ + } + } + then { + assert function.failed + assert function.stdout.any { it.contains("sheet: virtues_stats has no statistics for: [CD11B].") } + } + } + + test("stats with a different uniprot_id are rejected") { + when { + params { use_backsub = false } + function { + """ + input[0] = [ + [ marker_name: 'ELANE', channel_role: 'marker', uniprot_id: 'P08246' ], + ] + input[1] = 'sheet' + input[2] = [ format: 1, markers: [ ELANE: [ uniprot_id: 'P11215' ] ] ] + """ + } + } + then { + assert function.failed + assert function.stdout.any { it.contains("sheet: virtues_stats records a different uniprot_id for: ELANE (sheet P08246, stats P11215).") } + } + } + + test("matching stats are accepted") { + when { + params { use_backsub = false } + function { + """ + input[0] = [ + [ marker_name: 'ELANE', channel_role: 'marker', uniprot_id: 'P08246' ], + ] + input[1] = 'sheet' + input[2] = [ format: 1, markers: [ ELANE: [ uniprot_id: 'P08246' ] ] ] + """ + } + } + then { + assert function.success + } + } + + test("with use_backsub a removed row is ignored by every rule") { + when { + params { use_backsub = true } + function { + """ + input[0] = [ + [ marker_name: 'DNA_1', channel_role: 'dna', uniprot_id: 'P08246', remove: true ], + [ marker_name: 'GONE', channel_role: 'marker', uniprot_id: 'P11215', remove: true ], + [ marker_name: 'ELANE', channel_role: 'marker', uniprot_id: 'P11215' ], + [ marker_name: 'CD11B', channel_role: 'marker', uniprot_id: 'P08246', remove: true ], + ] + input[1] = 'sheet' + input[2] = [ format: 1, markers: [ ELANE: [ uniprot_id: 'P11215' ] ] ] + """ + } + } + then { + assert function.success + } + } +} diff --git a/tests/virtues.nf.test b/tests/virtues.nf.test new file mode 100644 index 0000000..4e9c827 --- /dev/null +++ b/tests/virtues.nf.test @@ -0,0 +1,241 @@ +// VirTues under -stub: histograms per store, statistics per slide, one VIRTUES per store, one write, QC after it. +// use_virtues needs preprocessing (UniProt IDs come from the marker sheet), tissue segmentation and use_gpu. + +nextflow_pipeline { + + name "VirTues" + script "../main.nf" + profile "test,laptop" + options "-stub" + tag "stub" + tag "pipeline" + + // A two-cycle sample sheet naming the VirTues marker sheet; absolute paths, since nf-test launches elsewhere. + def writeSheet = { outputDir, baseDir -> + def data = "$baseDir/tests/stub_data" + def sheet = new File("$outputDir", "samplesheet.csv") + sheet.parentFile.mkdirs() + sheet.text = "sample,cycle_number,image_tiles,marker_sheet\n" + + "testslide,1,${data}/cycle01.ome.tiff,${data}/markers_virtues.csv\n" + + "testslide,2,${data}/cycle02.ome.tiff,${data}/markers_virtues.csv\n" + sheet.path + } + + // Each task's work directory, from the trace hash (e.g. "ab/12cd34"). + def taskDirs = { metaDir, workDir, proc -> + def rows = new File("$metaDir/trace.csv").readLines()*.split('\t') + def col = { name -> rows[0].findIndexOf { it == name } } + rows.tail().findAll { it[col('name')].contains(proc) }.collect { r -> + def hash = r[col('hash')].split('/') + new File("$workDir/${hash[0]}").listFiles().find { it.name.startsWith(hash[1]) } + } + } + + // The trace has no timestamps; a task's .command.begin and .exitcode files mark its start and end. + def taskTimes = { metaDir, workDir, proc -> + taskDirs(metaDir, workDir, proc).collect { dir -> + [start: new File(dir, '.command.begin').lastModified(), end: new File(dir, '.exitcode').lastModified()] + } + } + + test("one method: histogram, stats, one VIRTUES, one write") { + + when { + params { + outdir = "$outputDir" + input = writeSheet(outputDir, baseDir) + use_preprocessing = true + cellpose_channels = "DNA_6" + use_virtues = true + use_gpu = true + use_tissue_segmentation = true + pixel_size = 0.65 + use_qc = true + } + } + + then { + def ran = workflow.trace.succeeded().collect { it.name } + def names = { proc -> ran.findAll { it.contains(proc) } } + // "VIRTUES (" matches the VIRTUES task only, not VIRTUES_HISTOGRAM or VIRTUES_STATS. + def accelerator = { proc -> taskDirs(metaDir, workDir, proc).collect { new File(it, '.accelerator').text.trim() } } + def write_done = taskTimes(metaDir, workDir, 'WRITE_FEATURES')*.end.max() + def qc_start = taskTimes(metaDir, workDir, 'QC_METRICS')*.start.min() + + assertAll( + { assert workflow.success }, + { assert names("VIRTUES_HISTOGRAM").size() == 1 }, + { assert names("VIRTUES_STATS").size() == 1 }, + { assert names("VIRTUES (").size() == 1 }, + { assert names("WRITE_FEATURES").size() == 1 }, + // The writes share the store's metadata, so QC must start after the last one. + { assert qc_start >= write_done }, + { assert new File("$outputDir/learned_features/testslide_virtues_stats.json").exists() }, + { assert new File("$outputDir/learned_features/testslide_virtues.json").exists() }, + { assert path("$outputDir/pipeline_info/histo_software_versions.yml").text.contains('VIRTUES') }, + { assert accelerator("VIRTUES (") == ['gpu'] }, + { assert accelerator("VIRTUES_HISTOGRAM") == ['none'] }, + { assert accelerator("VIRTUES_STATS") == ['none'] } + ) + } + } + + test("two methods: one VIRTUES for both") { + + when { + params { + outdir = "$outputDir" + input = writeSheet(outputDir, baseDir) + use_preprocessing = true + cellpose_channels = "DNA_6" + use_instanseg = true + instanseg_channels = "DNA_6" + use_virtues = true + use_gpu = true + use_tissue_segmentation = true + pixel_size = 0.65 + } + } + + then { + def ran = workflow.trace.succeeded().collect { it.name } + def names = { proc -> ran.findAll { it.contains(proc) } } + def staged = taskDirs(metaDir, workDir, 'WRITE_FEATURES').collect { new File(it, 'staged_inputs.txt').readLines()*.split(' ')*.getAt(0) } + + assertAll( + { assert workflow.success }, + { assert names("VIRTUES_HISTOGRAM").size() == 1 }, + { assert names("VIRTUES_STATS").size() == 1 }, + { assert names("VIRTUES (").size() == 1 }, + { assert names("WRITE_FEATURES").size() == 1 }, + // One write gets both methods' tables and the store-level elements. + { assert staged[0].containsAll(['cellpose_virtues.h5ad', 'instanseg_virtues.h5ad', 'virtues_niches.parquet']) } + ) + } + } + + test("TMA: one stats task per slide, one VIRTUES per core") { + + when { + params { + outdir = "$outputDir" + input = writeSheet(outputDir, baseDir) + use_preprocessing = true + use_tma_dearray = true + tma_expected_cores = 4 + tma_core_diameter_mm = 1.5 + cellpose_channels = "DNA_6" + use_virtues = true + use_gpu = true + use_tissue_segmentation = true + pixel_size = 0.65 + } + } + + then { + def ran = workflow.trace.succeeded().collect { it.name } + def names = { proc -> ran.findAll { it.contains(proc) } } + + assertAll( + { assert workflow.success }, + // The Coreograph stub emits two cores. + { assert names("VIRTUES_HISTOGRAM").size() == 2 }, + { assert names("VIRTUES_STATS").size() == 1 }, + { assert names("VIRTUES (").size() == 2 }, + { assert names("WRITE_FEATURES").size() == 2 }, + { assert new File("$outputDir/learned_features/testslide_virtues_stats.json").exists() }, + // One provenance file per core, not one overwritten by the other. + { assert new File("$outputDir/learned_features/testslide_core001_virtues.json").exists() }, + { assert new File("$outputDir/learned_features/testslide_core002_virtues.json").exists() } + ) + } + } + + test("virtues_stats given: no statistics tasks") { + + when { + // Covers every marker with a uniprot_id in markers_virtues.csv, as validation requires. + def stats = new File("$outputDir", "given_stats.json") + stats.parentFile.mkdirs() + stats.text = '{"format": 1, "markers": {"ELANE": {"uniprot_id": "P08246"}, "CD11B": {"uniprot_id": "P11215"}}}' + + params { + outdir = "$outputDir" + input = writeSheet(outputDir, baseDir) + use_preprocessing = true + cellpose_channels = "DNA_6" + use_virtues = true + virtues_stats = stats.path + use_gpu = true + use_tissue_segmentation = true + pixel_size = 0.65 + } + } + + then { + def ran = workflow.trace.succeeded().collect { it.name } + def names = { proc -> ran.findAll { it.contains(proc) } } + + assertAll( + { assert workflow.success }, + { assert names("VIRTUES_HISTOGRAM").isEmpty() }, + { assert names("VIRTUES_STATS").isEmpty() }, + { assert names("VIRTUES (").size() == 1 }, + { assert names("WRITE_FEATURES").size() == 1 } + ) + } + } + + test("with Nimbus: both models, one write per store") { + + when { + params { + outdir = "$outputDir" + input = writeSheet(outputDir, baseDir) + use_preprocessing = true + cellpose_channels = "DNA_6" + use_nimbus = true + use_virtues = true + use_gpu = true + use_tissue_segmentation = true + pixel_size = 0.65 + } + } + + then { + def ran = workflow.trace.succeeded().collect { it.name } + def names = { proc -> ran.findAll { it.contains(proc) } } + def staged = taskDirs(metaDir, workDir, 'WRITE_FEATURES').collect { new File(it, 'staged_inputs.txt').readLines()*.split(' ')*.getAt(0) } + + assertAll( + { assert workflow.success }, + { assert names("NIMBUS").size() == 1 }, + { assert names("VIRTUES (").size() == 1 }, + { assert names("WRITE_FEATURES").size() == 1 }, + { assert staged[0].containsAll(['cellpose_nimbus.h5ad', 'cellpose_virtues.h5ad']) } + ) + } + } + + test("use_virtues off runs none of the three") { + + when { + params { + outdir = "$outputDir" + input = writeSheet(outputDir, baseDir) + use_preprocessing = true + cellpose_channels = "DNA_6" + } + } + + then { + def ran = workflow.trace.succeeded().collect { it.name } + + assertAll( + { assert workflow.success }, + { assert !ran.any { it.contains("VIRTUES") } }, + { assert !ran.any { it.contains("WRITE_FEATURES") } } + ) + } + } +} diff --git a/tools/benchmark_projection.py b/tools/benchmark_projection.py index 2e3355c..5ed03e0 100755 --- a/tools/benchmark_projection.py +++ b/tools/benchmark_projection.py @@ -33,6 +33,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "bin")) from project_channels import combine, percentile_bounds, rescale # noqa: E402 +from segmentation_benchmark.preprocess import sopa_preprocess # noqa: E402 PREVIEW_CROP = 400 @@ -75,19 +76,6 @@ def project_crop( return (combine(np.stack(stack), method) * 65535 + 0.5).astype(np.uint16) -def sopa_preprocess(image: Any, gaussian_sigma: float, clip_limit: float) -> Any: - """sopa.segmentation.stainings._run_patch, before the model.""" - import numpy as np - from scipy.ndimage import gaussian_filter - from skimage import exposure - - if gaussian_sigma > 0: - image = np.stack([gaussian_filter(c, sigma=gaussian_sigma) for c in image]) - if clip_limit > 0: - image = np.stack([exposure.equalize_adapthist(c, clip_limit=clip_limit) for c in image]) - return image - - def segment(image: Any, n_channels: int, diameter: float, flow: float, cellprob: float, gpu: bool) -> Any: from sopa.segmentation.methods import cellpose_patch diff --git a/tools/build_sif.sbatch b/tools/build_sif.sbatch new file mode 100755 index 0000000..534df2f --- /dev/null +++ b/tools/build_sif.sbatch @@ -0,0 +1,357 @@ +#!/usr/bin/env bash +# +# Build an Apptainer SIF from a Docker image, straight into Nextflow's singularity cache. +# +# Usage (from the repo root, on the cluster, after sourcing histo's setup.sh): +# sbatch tools/build_sif.sbatch [--name FILE] [--force] [--need-gb N] [out_dir] +# bash tools/build_sif.sbatch --help +# +# a registry ref, e.g. docker.io/josenimo/nimbus:0.0.5 (docker:// optional), +# or a local docker-save tar, OCI archive, or OCI layout directory (no network). +# out_dir default $NXF_SINGULARITY_CACHEDIR, else the histo cache: +# /fast/AG_Coscia/software/pipelines/histo/singularity-images +# --name output file name. Default for a ref: Nextflow's cache name, e.g. +# docker.io-josenimo-nimbus-0.0.5.img. Required for a local source. +# --force replace an existing file in out_dir. Refused in the shared cache: use a new tag. +# --need-gb free space to require (default 60 for a ref, 4x the source size for a file). +# +# The output is a SIF either way; `.img` is only the name Nextflow looks for. It is built as +# .partial. and renamed once verified, so Nextflow never sees half an image. +# Log: /logs/build_sif..log (sbatch -o elsewhere.log to change). +# Temp: $APPTAINER_TMPDIR and $APPTAINER_CACHEDIR (setup.sh sets both), else +# /fast/AG_Coscia/software/nextflow/$USER/apptainer_{tmp,cache}. +# Tests set BUILD_SIF_ATTEMPTS and BUILD_SIF_RETRY_SLEEP (default 4 attempts, 60 s doubling). + +# mksquashfs scales to ~16 threads; past that the /fast write is the limit. +#SBATCH --cpus-per-task=16 +# Twice the mksquashfs cache, plus room for extraction; covers 25% of a 176 GB node on Apptainer < 1.4. +#SBATCH --mem=48G +# A ~14 GB image pulls and squashes in under an hour; the rest is slack for retries. +#SBATCH --time=04:00:00 +# MDC default partition (7 d); no GPU needed. +#SBATCH --partition=normal +# /fast is only mounted on Ceph nodes. +#SBATCH --constraint=ceph +#SBATCH --job-name=build_sif +# SLURM expands no variables here and creates no directories: keep in step with default_cache. +#SBATCH --output=/fast/AG_Coscia/software/pipelines/histo/singularity-images/logs/%x.%j.log +#SBATCH --error=/fast/AG_Coscia/software/pipelines/histo/singularity-images/logs/%x.%j.log + +set -euo pipefail +# Colleagues read the copy in the shared cache; rsync -a keeps these permissions. +umask 022 + +# The header comment, up to the first blank line. +usage() { awk 'NR > 2 && /^#/ { sub(/^# ?/, ""); print; next } NR > 2 { exit }' "${BASH_SOURCE[0]}"; } +stage() { printf '\n==== [%s] %s\n' "$(date '+%F %T')" "$*"; } +info() { printf ' %s\n' "$*"; } +die() { + printf '\nERROR: %s\n' "$1" >&2 + shift + for hint in "$@"; do printf ' -> %s\n' "$hint" >&2; done + exit 1 +} + +# Physical path of $1, even if it does not exist yet. +resolve() { + local p="$1" rest="" + while [[ ! -d "$p" ]]; do + rest="/$(basename "$p")$rest" + p="$(dirname "$p")" + done + p="$(cd "$p" && pwd -P)" + printf '%s%s' "${p%/}" "$rest" +} + +# Nextflow SingularityCache.simpleName: '.img' unless the name carries '.sif'. +nxf_cache_name() { + local n="$1" ext=".img" + if [[ "$n" == *.sif:* ]]; then + ext=".sif" + n="${n//.sif:/-}" + elif [[ "$n" == *.sif ]]; then + ext=".sif" + n="${n%.sif}" + fi + n="${n//:/-}" + n="${n//\//-}" + printf '%s%s' "$n" "$ext" +} + +sha256() { if command -v sha256sum >/dev/null; then sha256sum "$1"; else shasum -a 256 "$1"; fi; } + +# ---------------------------------------------------------------------------- arguments + +name="" force=0 need_gb="" +positional=() +while (($#)); do + case "$1" in + -h | --help) usage; exit 0 ;; + --force) force=1 ;; + --name) + [[ $# -ge 2 ]] || die "--name needs a value" "see --help" + name="$2" + shift + ;; + --need-gb) + [[ $# -ge 2 ]] || die "--need-gb needs a value" "see --help" + need_gb="$2" + shift + ;; + -*) die "unknown option: $1" "see: bash tools/build_sif.sbatch --help" ;; + *) positional+=("$1") ;; + esac + shift +done +((${#positional[@]} >= 1 && ${#positional[@]} <= 2)) || + die "expected [out_dir], got ${#positional[@]} arguments" "see: bash tools/build_sif.sbatch --help" +[[ -z "$need_gb" || "$need_gb" =~ ^[0-9]+$ ]] || die "--need-gb must be a whole number of GB, got '$need_gb'" + +source_arg="${positional[0]}" +default_cache=/fast/AG_Coscia/software/pipelines/histo/singularity-images +# Where generic_setup.sh puts each user's apptainer dirs. +user_base="/fast/AG_Coscia/software/nextflow/${USER:?USER is not set}" +out_dir="${positional[1]:-${NXF_SINGULARITY_CACHEDIR:-${NXF_APPTAINER_CACHEDIR:-$default_cache}}}" +job_id="${SLURM_JOB_ID:-local.$$}" +cpus="${SLURM_CPUS_PER_TASK:-4}" +mem_mb="${SLURM_MEM_PER_NODE:-8192}" +attempts="${BUILD_SIF_ATTEMPTS:-4}" +retry_sleep="${BUILD_SIF_RETRY_SLEEP:-60}" + +# ---------------------------------------------------------------------------- source + +if [[ -e "$source_arg" ]]; then + mode=local + src_abs="$(resolve "$source_arg")" + if [[ -d "$src_abs" ]]; then + if [[ -f "$src_abs/oci-layout" && -f "$src_abs/index.json" ]]; then + bootstrap="oci://$src_abs" + elif [[ -f "$src_abs/manifest.json" ]]; then + die "$src_abs looks like an unpacked docker save" "pass the .tar from docker save instead" + else + die "$src_abs is not an OCI layout directory (needs oci-layout and index.json)" + fi + else + header="$(head -c 64 "$src_abs" | LC_ALL=C tr -d '\0')" + if [[ "$header" == *SIF_MAGIC* || "${header:0:4}" == hsqs || "$src_abs" == *.sif || "$src_abs" == *.img ]]; then + echo "$src_abs is already an Apptainer image; nothing to build." + echo "To stage it, rename it to the Nextflow cache name and copy it without overwriting:" + echo " rsync -av --ignore-existing \"\$NXF_SINGULARITY_CACHEDIR/\"" + exit 0 + fi + # Contents, not the extension, decide the bootstrap. A few dozen members, so a variable is fine. + members="$(tar -tf "$src_abs" 2>/dev/null | sed -e 's|^\./||' -e 's|/$||')" || + die "$src_abs is not a readable tar archive" "expected the output of 'docker save' or an OCI archive" + # docker save from Docker 25+ also writes index.json, so manifest.json decides first. + if grep -qx 'manifest.json' <<<"$members"; then + bootstrap="docker-archive://$src_abs" + elif grep -qx 'oci-layout' <<<"$members" && grep -qx 'index.json' <<<"$members"; then + bootstrap="oci-archive://$src_abs" + else + die "$src_abs has neither manifest.json (docker save) nor oci-layout and index.json (OCI)" \ + "list it with: tar -tf $src_abs | head" + fi + fi + if [[ -z "$need_gb" ]]; then + # Unpacking needs 3-4x the compressed size; 20 GB floor for small images. + src_kb="$(du -sk "$src_abs" | awk '{print $1}')" + need_gb=$(((src_kb * 4 + 1048575) / 1048576)) + ((need_gb >= 20)) || need_gb=20 + fi + [[ -n "$name" ]] || die "--name is required for a local source" \ + "use the name Nextflow looks for: the container string with ':' and '/' as '-', plus .img" \ + "e.g. container docker.io/josenimo/nimbus:0.0.5 -> --name docker.io-josenimo-nimbus-0.0.5.img" +elif [[ "$source_arg" == /* || "$source_arg" == .* || "$source_arg" =~ \.(tar|tar\.gz|tgz|sif|img)$ ]]; then + die "no such file or directory: $source_arg" "check the path; a registry ref looks like docker.io/user/image:tag" +else + mode=registry + ref="${source_arg#docker://}" + [[ "$ref" != *://* ]] || die "unsupported scheme in '$source_arg'" "give a docker:// ref or a local path" + [[ "$ref" =~ ^[A-Za-z0-9][A-Za-z0-9._/:@-]*$ ]] || die "not a valid image reference: '$ref'" + last="${ref##*/}" + [[ "$last" == *:* || "$last" == *@* ]] || + die "'$ref' has no tag" "pin one, e.g. $ref:1.0; :latest changes under you and Nextflow names files by tag" + bootstrap="docker://$ref" + [[ -n "$need_gb" ]] || need_gb=60 + [[ -n "$name" ]] || name="$(nxf_cache_name "$ref")" +fi + +[[ "$name" != */* && "$name" != .* && "$name" =~ \.(img|sif)$ ]] || + die "bad --name '$name'" "a plain file name ending in .img or .sif" + +# ---------------------------------------------------------------------------- paths + +# First candidate that is set and not under /tmp (small, and shared on login and compute nodes). +first_off_tmp() { + local d + for d in "$@"; do + if [[ -n "$d" && "$d" != /tmp && "$d" != /tmp/* ]]; then + printf '%s' "$d" + return + fi + done +} +tmp_base="$(first_off_tmp "${APPTAINER_TMPDIR:-}" "${TMPDIR:-}" "$user_base/apptainer_tmp")" +APPTAINER_CACHEDIR="$(first_off_tmp "${APPTAINER_CACHEDIR:-}" "$user_base/apptainer_cache")" + +out_dir="$(resolve "$out_dir")" +tmp_base="$(resolve "$tmp_base")" +APPTAINER_CACHEDIR="$(resolve "$APPTAINER_CACHEDIR")" +# Same value under both names, or apptainer warns that they differ. +export APPTAINER_CACHEDIR SINGULARITY_CACHEDIR="$APPTAINER_CACHEDIR" + +# Shared caches: Nextflow reads them, and colleagues' running jobs may hold their images. +shared_caches=() +for c in "${NXF_SINGULARITY_CACHEDIR:-}" "${NXF_APPTAINER_CACHEDIR:-}" "$default_cache"; do + if [[ -n "$c" ]]; then shared_caches+=("$(resolve "$c")"); fi +done +in_cache=0 +for c in "${shared_caches[@]}"; do + if [[ "$out_dir" == "$c" ]]; then + in_cache=1 + elif [[ "$out_dir" == "$c"/* ]]; then + die "$out_dir is below the cache $c" "Nextflow only looks in $c itself; pass that, or a directory outside it" + fi + for d in "$tmp_base" "$APPTAINER_CACHEDIR"; do + if [[ "$d" == "$c" || "$d" == "$c"/* ]]; then + die "$d is inside the cache $c" "point APPTAINER_TMPDIR, TMPDIR or APPTAINER_CACHEDIR elsewhere" + fi + done +done + +final="$out_dir/$name" +partial="$out_dir/$name.partial.$job_id" +job_tmp="$tmp_base/build_sif.$job_id" +export APPTAINER_TMPDIR="$job_tmp" SINGULARITY_TMPDIR="$job_tmp" + +if [[ -e "$final" && "$in_cache" -eq 1 ]]; then + # Each Nextflow task opens the image by name, so a replacement would mix images within a run. + die "$final is already in the cache" "nothing to build; to change the image, push a new tag" \ + "or build elsewhere (pass an out_dir) and compare sha256 first" +elif [[ -e "$final" && "$force" -eq 0 ]]; then + die "$final already exists" "pass --force to replace it, or choose another out_dir or --name" +fi + +cleanup() { + if [[ -e "$partial" ]]; then rm -f -- "$partial"; fi + # Literal job-specific suffix, so this can never match anything but our own directory. + if [[ "$job_tmp" == */build_sif."$job_id" && -d "$job_tmp" ]]; then + rm -rf -- "$job_tmp" 2>/dev/null || { chmod -R u+w -- "$job_tmp" && rm -rf -- "$job_tmp"; } || + echo "WARNING: could not remove $job_tmp; delete it by hand" >&2 + fi +} +trap cleanup EXIT +# SLURM sends TERM at timeout or scancel; exiting runs the EXIT trap. +trap 'echo "Interrupted; cleaning up" >&2; exit 143' TERM INT + +# ---------------------------------------------------------------------------- environment + +stage "Environment" +info "host: $(hostname)" +info "slurm job: ${SLURM_JOB_ID:-none (not under sbatch)}" +info "cpus / mem: $cpus / ${mem_mb} MB" +command -v apptainer >/dev/null || + die "apptainer is not on PATH" "load it (e.g. module load apptainer) or check the node; see 'which apptainer'" +info "apptainer: $(apptainer --version)" +info "source: $bootstrap" +info "output: $final$( ((in_cache)) && printf ' (shared cache)')" +if [[ -n "${SLURM_JOB_ID:-}" ]] && command -v scontrol >/dev/null; then + info "log: $(scontrol show job "$SLURM_JOB_ID" 2>/dev/null | sed -n 's/^ *StdOut=//p')" +fi +info "tmp: $APPTAINER_TMPDIR" +info "cache: $APPTAINER_CACHEDIR" +if [[ "$mode" == registry ]]; then + if [[ -n "${APPTAINER_DOCKER_USERNAME:-}" && -n "${APPTAINER_DOCKER_PASSWORD:-}" ]]; then + info "registry: credentials from APPTAINER_DOCKER_USERNAME/PASSWORD" + else + info "registry: anonymous (Docker Hub rate limits apply)" + fi +fi + +for d in "$out_dir" "$job_tmp" "$APPTAINER_CACHEDIR"; do + mkdir -p -- "$d" || die "cannot create $d" "check the path and that you can write there" +done +# A killed job (OOM, node failure) skips the cleanup trap; a parallel job is building the same name. +for stale in "$final".partial.*; do + if [[ -e "$stale" ]]; then info "WARNING: found $stale (a running build, or a killed one's leftover)"; fi +done + +# ---------------------------------------------------------------------------- disk space + +stage "Check free space (need ${need_gb} GB per location)" +for d in "$job_tmp" "$out_dir"; do + avail_kb="$(df -Pk "$d" | awk 'NR == 2 {print $4}')" + avail_gb=$((avail_kb / 1048576)) + info "$d: ${avail_gb} GB free" + ((avail_gb >= need_gb)) || + die "not enough space in $d: ${avail_gb} GB free, ${need_gb} GB needed" \ + "free space there, set TMPDIR or out_dir elsewhere, or lower the check with --need-gb" +done + +# ---------------------------------------------------------------------------- build + +stage "Build $bootstrap" +build_args=(build) +help_text="$(apptainer build --help 2>&1 || true)" +if [[ "$help_text" == *--mksquashfs-args* ]]; then + # mksquashfs sees the whole node, not the job: cap threads and its cache (default 25% of node RAM). + build_args+=(--mksquashfs-args "-processors $cpus -mem $((mem_mb / 2))M") +else + info "WARNING: this apptainer has no --mksquashfs-args (needs >= 1.4); mksquashfs will use every CPU it sees" +fi +build_args+=("$partial" "$bootstrap") +info "command: apptainer $(printf '%q ' "${build_args[@]}")" + +if [[ "$mode" == registry ]]; then + attempt=1 + until apptainer "${build_args[@]}"; do + rm -f -- "$partial" + if ((attempt >= attempts)); then + die "apptainer build failed $attempts times for docker://$ref" \ + "check the ref exists: tag spelling, registry, public or private" \ + "check this node reaches the registry: curl -sI https://registry-1.docker.io/v2/" \ + "rate limited? export APPTAINER_DOCKER_USERNAME and APPTAINER_DOCKER_PASSWORD, then resubmit" \ + "resubmitting reuses layers already in $APPTAINER_CACHEDIR" + fi + wait_s=$((retry_sleep * 2 ** (attempt - 1))) + info "attempt $attempt of $attempts failed; retrying in ${wait_s} s" + sleep "$wait_s" + attempt=$((attempt + 1)) + done +else + apptainer "${build_args[@]}" || + die "apptainer build failed for $bootstrap" "see the apptainer output above" \ + "check the archive is complete: compare its size or sha256 with the machine it came from" +fi + +# ---------------------------------------------------------------------------- verify + +stage "Verify" +apptainer inspect "$partial" || die "apptainer inspect failed on the new image" "see the output above; rebuild" +# Nextflow runs every task with bash inside the image. +apptainer exec "$partial" /bin/bash -c true || + die "the image cannot run /bin/bash" "Nextflow needs bash in the image; check the Dockerfile" + +if [[ -e "$final" ]] && ((in_cache || !force)); then + die "$final appeared during the build" "check for a parallel job; the new image is discarded" +fi +mv -f -- "$partial" "$final" + +stage "Done" +info "file: $final" +info "size: $(du -h -- "$final" | cut -f1) ($(wc -c <"$final" | tr -d ' ') bytes)" +info "sha256: $(sha256 "$final" | cut -d' ' -f1)" +info "format: SIF (the .img suffix is only Nextflow's cache naming)" +if ((in_cache)); then + echo + echo "Nextflow will use it from $out_dir." + exit 0 +fi +for c in "${shared_caches[@]}"; do + if [[ -e "$c/$name" ]]; then + info "NOTE: $name is already in $c; rsync below will skip it. Compare sha256 first." + fi +done +echo +echo "Copy into the shared cache yourself (never overwrites an existing image):" +echo " rsync -av --ignore-existing $final \"\$NXF_SINGULARITY_CACHEDIR/\"" diff --git a/tools/containers/nimbus/Dockerfile b/tools/containers/nimbus/Dockerfile new file mode 100644 index 0000000..e3365f3 --- /dev/null +++ b/tools/containers/nimbus/Dockerfile @@ -0,0 +1,14 @@ +# Nimbus-Inference on the sopa image. --no-deps because Nimbus pins numpy<2 but runs on numpy 2. +FROM docker.io/josenimo/sopa:2.3.0 + +RUN pip install --no-cache-dir --no-deps Nimbus-Inference==0.0.5 \ + && pip install --no-cache-dir --no-deps \ + alpineer==0.2.1 kornia==0.9.0 pyometiff==1.1.4 lmdb==3.0.0 lxml==5.4.0 \ + && pip install --no-cache-dir huggingface_hub==2.4.0 + +# V1.pt is baked in so no run needs the network (MIT licence, ungated). +RUN python -c "import pathlib, nimbus_inference as n; from huggingface_hub import hf_hub_download; \ +d = pathlib.Path(n.__file__).parent / 'assets'; d.mkdir(exist_ok=True); \ +hf_hub_download('JLrumberger/Nimbus-Inference', 'V1.pt', local_dir=d)" + +ENV HF_HUB_OFFLINE=1 diff --git a/tools/containers/nimbus/README.md b/tools/containers/nimbus/README.md new file mode 100644 index 0000000..273f719 --- /dev/null +++ b/tools/containers/nimbus/README.md @@ -0,0 +1,36 @@ +# Nimbus image (docker.io/josenimo/nimbus:0.0.5) + +Nimbus-Inference 0.0.5 on `josenimo/sopa:2.3.0`, `V1.pt` baked in, no network at run time. + +- Build: `docker buildx build --platform linux/amd64 -t docker.io/josenimo/nimbus:0.0.5 tools/containers/nimbus` +- Save: `docker save docker.io/josenimo/nimbus:0.0.5 -o nimbus_0.0.5.tar` +- SIF on the cluster: `sbatch tools/build_sif.sbatch docker.io/josenimo/nimbus:0.0.5`, or from the tar with `--name docker.io-josenimo-nimbus-0.0.5.img nimbus_0.0.5.tar` +- Verify: `docker run --rm --network none --entrypoint python docker.io/josenimo/nimbus:0.0.5 -c "import numpy; from nimbus_inference.nimbus import Nimbus as N; n=N(dataset=None, output_dir='', save_predictions=False, device='cpu', checkpoint='V1.pt'); n.load_checkpoint(padding='valid'); print(numpy.__version__)"` +- Extra deps beyond the brief: `lxml` (pyometiff import), `huggingface_hub` with its own deps (needs `httpx2`). + +## Findings (2026-11-11) + +- **Numpy 2.** `import nimbus_inference.nimbus` works on numpy 2.5.4 (`--no-deps`). +- **CPU load.** `V1.pt` loads on CPU without `map_location`; no `map_location` is needed. +- **Halo.** Valid model, 1024 in, 836 out: raw `(1024-836)//2 = 94`; after upstream's `crop_by` + (`836 % 32 = 4`) the output is 832, so the halo is `(1024-832)//2 = 96`. Use 96. +- **Magnification: not found.** Neither the paper nor the README gives the µm/px of "10x". + The paper (Methods) says images are "resized to 1/4th of their original resolution" and tiled + at 512 px, with no physical units. Issue + [#61](https://github.com/angelolab/Nimbus-Inference/issues/61) (2026-05-22) asks whether MPP 1 + means `magnification=10`; the maintainer reply (2026-06-03) does not answer. "10x = 1 µm/px" + stays an unconfirmed assumption. Ask the authors (jlrumber@stanford.edu) or test sensitivity. +- **Citation.** Rumberger JL, Greenwald NF, Ranek JS, et al. (20 authors, last: Angelo M). + "Automated classification of cellular expression in multiplexed imaging data with Nimbus." + Nature Methods 22(10):2161-2170, 2025. DOI 10.1038/s41592-025-02826-9 + (preprint bioRxiv 10.1101/2024.06.02.597062). + +## Parity fixture (generated, not committed) + +- Make: `uv run --python 3.11 --with tifffile --with numpy --with scikit-image --with scipy python -I tools/make_nimbus_fixture.py local_test_datasets/exemplar001/stitched/Exemplar001.ome.tif tests/unit/fixtures/nimbus_crop` +- Reference: `uv run --python 3.11 --with Nimbus-Inference==0.0.5 python -I tools/nimbus_reference.py tests/unit/fixtures/nimbus_crop` +- Crop: exemplar-001 stitched, rows 1000-2280, cols 600-1880; channels CD45 (dense), FOXP3 (sparse). +- Labels: no exemplar-001 segmentation exists on disk, so a quick scikit-image nuclei watershed + on DNA_6, expanded 3 px (2683 cells). Not Cellpose; parity does not depend on label quality. +- The reference script uses `checkpoint="latest"`, which downloads `V1.pt` (the uv env has no + local weights); same file as in the image. About 2.5 min on the Mac CPU. diff --git a/tools/containers/virtues/Dockerfile b/tools/containers/virtues/Dockerfile new file mode 100644 index 0000000..befaf3e --- /dev/null +++ b/tools/containers/virtues/Dockerfile @@ -0,0 +1,59 @@ +# VirTues (bunnelab/virtues) with FlashAttention 2, sp32 weights, ESM-2 and UniProt baked in; no network at run time. +# Ubuntu 24.04 gives Python 3.12 like the sopa image (zarr 3.4 needs it); torch 2.5.1 from PyPI bundles CUDA 12.4. +FROM ubuntu:24.04 + +ARG VIRTUES_COMMIT=d2c25e1 +ARG SPORA_IO_COMMIT=ef15868 +# Passed by the build command (see README); the UniProt download below must report the same release. +ARG UNIPROT_RELEASE +ARG FLASH_ATTN_WHL=https://github.com/Dao-AILab/flash-attention/releases/download/v2.7.4.post1/flash_attn-2.7.4.post1+cu12torch2.5cxx11abiFALSE-cp312-cp312-linux_x86_64.whl + +RUN apt-get update && apt-get install -y --no-install-recommends python3.12 python3.12-venv git curl ca-certificates \ + && rm -rf /var/lib/apt/lists/* && python3.12 -m venv /opt/venv +ENV PATH=/opt/venv/bin:$PATH + +RUN pip install --no-cache-dir torch==2.5.1 torchvision==0.20.1 + +# Data stack pinned to docker.io/josenimo/sopa:2.3.0 so both images read the same SpatialData store. +RUN pip install --no-cache-dir \ + numpy==2.5.4 pandas==3.1.1 pyarrow==26.0.1 zarr==3.4.2 dask==2026.8.0 xarray==2026.9.0 \ + shapely==2.1.2 geopandas==1.2.0 anndata==0.13.4 spatialdata==0.8.0 + +# Prebuilt wheel for this torch/CUDA/Python/ABI; FlashAttention is never compiled here. +RUN pip install --no-cache-dir --no-deps "${FLASH_ATTN_WHL}" + +# Checkout also supplies assets/example_dataset (parity data) and configs. Editable, because upstream's +# packaging (include = ["virtues"]) omits subpackages from a regular install. +RUN git clone https://github.com/bunnelab/virtues /opt/virtues-src \ + && git -C /opt/virtues-src checkout "${VIRTUES_COMMIT}" && rm -rf /opt/virtues-src/.git + +# --no-deps for the two packages: their pins target other torch builds; runtime imports are listed below. +RUN pip install --no-cache-dir --no-deps -e /opt/virtues-src \ + "git+https://github.com/bunnelab/spora-io@${SPORA_IO_COMMIT}" \ + && pip install --no-cache-dir \ + fair-esm==2.0.0 omegaconf==2.3.0 safetensors==0.7.0 einops==0.8.1 loguru==0.7.3 \ + scipy==1.16.3 tqdm==4.67.1 fastparquet==2026.9.0 huggingface_hub==2.4.0 + +ENV TORCH_HOME=/opt/torch +RUN python -c "import esm; esm.pretrained.esm2_t30_150M_UR50D()" + +RUN python -c "import shutil; from huggingface_hub import hf_hub_download; \ +p = hf_hub_download('bunnelab/virtues', 'virtues-sp32/model.safetensors', local_dir='/opt/virtues/dl'); \ +shutil.move(p, '/opt/virtues/sp32.tmp')" \ + && mkdir -p /opt/virtues/sp32 && mv /opt/virtues/sp32.tmp /opt/virtues/sp32/model.safetensors && rm -rf /opt/virtues/dl + +RUN test -n "${UNIPROT_RELEASE}" && mkdir -p /opt/uniprot && curl -fsSL -D /tmp/h.txt -o /opt/uniprot/human_sprot_isoforms.fasta \ + 'https://rest.uniprot.org/uniprotkb/stream?format=fasta&includeIsoform=true&query=(organism_id:9606)+AND+(reviewed:true)' \ + && grep -i "^x-uniprot-release: ${UNIPROT_RELEASE}[[:space:]]*$" /tmp/h.txt && rm /tmp/h.txt + +# After the UniProt layer so a rebuild reuses it: upstream's ESM module imports Bio; pytest runs the model tests. +RUN pip install --no-cache-dir biopython==1.88 pytest==9.2.0 + +ENV VIRTUES_WEIGHTS=/opt/virtues/sp32/model.safetensors \ + VIRTUES_UNIPROT=/opt/uniprot/human_sprot_isoforms.fasta \ + VIRTUES_UNIPROT_RELEASE=${UNIPROT_RELEASE} \ + VIRTUES_COMMIT=${VIRTUES_COMMIT} \ + VIRTUES_SRC=/opt/virtues-src \ + HF_HUB_OFFLINE=1 + +COPY check_image.py /opt/check_image.py diff --git a/tools/containers/virtues/README.md b/tools/containers/virtues/README.md new file mode 100644 index 0000000..e29f302 --- /dev/null +++ b/tools/containers/virtues/README.md @@ -0,0 +1,47 @@ +# VirTues image (docker.io/josenimo/virtues:d2c25e1-2) + +[bunnelab/virtues](https://github.com/bunnelab/virtues) at `d2c25e1` and spora-io at `ef15868`, with +FlashAttention 2, the `sp32` weights, ESM-2 150M and human UniProt (reviewed, with isoforms) baked in, +so no run needs the network. `check_image.py` is at `/opt/check_image.py`. + +- Build (`UNIPROT_RELEASE` must match what UniProt serves, or the build fails; ~20 min under emulation): + `REL=$(curl -sI 'https://rest.uniprot.org/uniprotkb/stream?format=fasta&includeIsoform=true&query=(organism_id:9606)+AND+(reviewed:true)' | tr -d '\r' | awk -F': ' 'tolower($1)=="x-uniprot-release"{print $2}')` + then `docker buildx build --platform linux/amd64 --build-arg UNIPROT_RELEASE=$REL --load -t docker.io/josenimo/virtues:d2c25e1-2 tools/containers/virtues` +- Mac check (offline, no CUDA): `docker run --rm --platform linux/amd64 --network none docker.io/josenimo/virtues:d2c25e1-2 python /opt/check_image.py --cpu-only` +- Push (public; CI and image staging pull it): `docker push docker.io/josenimo/virtues:d2c25e1-2` +- Save: `docker save docker.io/josenimo/virtues:d2c25e1-2 -o virtues_d2c25e1-2.tar` +- SIF on the cluster: `sbatch tools/build_sif.sbatch docker.io/josenimo/virtues:d2c25e1-2`, or from the tar with `--name docker.io-josenimo-virtues-d2c25e1-2.img virtues_d2c25e1-2.tar` +- Cluster check (GPU node, as an `sbatch` or interactive job; the example core is read from the image): + `apptainer exec --nv --containall "$NXF_SINGULARITY_CACHEDIR/docker.io-josenimo-virtues-d2c25e1-2.img" python /opt/check_image.py` + It imports `flash_attn`, runs `compute_cell_tokens` on the bundled example core as notebook 2 does, + and prints the token shapes. Send the output back. + +Environment (read by the pipeline): `VIRTUES_WEIGHTS`, `VIRTUES_UNIPROT`, `VIRTUES_UNIPROT_RELEASE`, +`VIRTUES_COMMIT`, `VIRTUES_SRC` (checkout with `assets/example_dataset`), `TORCH_HOME=/opt/torch`, `HF_HUB_OFFLINE=1`. + +## Findings (2026-11-24) + +- **Base.** Not `pytorch/pytorch:2.5.1-cuda12.4-cudnn9-runtime`: it is Python 3.11, and the sopa + image's `numpy 2.5` and `zarr 3.4` need 3.12. Now `ubuntu:24.04` (Python 3.12.3, venv) with + `torch 2.5.1` and `torchvision 0.20.1` from PyPI (CUDA 12.4 libraries bundled), and the + `flash_attn-2.7.4.post1+cu12torch2.5cxx11abiFALSE-cp312` wheel. Never compiled. Image is large (12.9 GB on disk). +- **Versions.** torch 2.5.1+cu124, FlashAttention 2.7.4.post1, spatialdata 0.8.0, anndata 0.13.4, + geopandas 1.2.0, numpy 2.5.4, pandas 3.1.1, zarr 3.4.2 (same as `sopa:2.3.0`), fair-esm 2.0.0, + safetensors 0.7.0, omegaconf 2.3.0, einops 0.8.1. + Tag `d2c25e1-2` adds biopython 1.88 (upstream's ESM module imports it) and pytest 9.2.0 (model tests). +- **Editable install.** Upstream's `pyproject.toml` has `include = ["virtues"]`, so a normal install + drops `virtues.modules`. The image installs `/opt/virtues-src` with `-e`. +- **flash_attn imports on CPU.** `virtues.modules.multiplex_virtues` imports and the weights load + with `strict=True` (`All keys matched successfully`) on the Mac under emulation. No stub needed. +- **ESM-2 parity.** Our embedding of the 40 IDs in `assets/example_dataset/marker_embeddings/` against + the bundled `.pt`: max abs difference 9.5e-07 for 39 of them (CPU float32 noise). One outlier, + `P36402` (TCF7), 3.4e-02: UniProt 2026_04 has sequence version 4 (one residue differs from version + 3, release 2025_02). The version 3 sequence gives 1.5e-07. Isoform `P08575-8` matches. +- **Token shape (from the code; the A40 parity run passes with it).** `encoder_output.patch_summary_tokens` + is a list with one `(16, 16, 512)` tensor per 128 px crop (`H W D`; dtype set by autocast). +- **Backsub (0.5.1, `background_sub.py`).** Output dtype equals input dtype: `data_type` read from the + source (L171), integer results clipped then `.astype(ref_dtype)` (L243-246). The `--marker-output` CSV + keeps unknown columns such as `uniprot_id`: it reads the sheet with `pd.read_csv` (L378) and drops only + `keep`, `ind`, `processed`, `factor`, `bg_idx` (L383-385; `remove` earlier, L118), adds `channel_number` + (L386); rows with `remove` true are dropped (L380). +- **Cluster check.** `check_image.py` passed on an A40 (2026-11-25), and parity with upstream (2026-11-26). diff --git a/tools/containers/virtues/check_image.py b/tools/containers/virtues/check_image.py new file mode 100644 index 0000000..a318ce7 --- /dev/null +++ b/tools/containers/virtues/check_image.py @@ -0,0 +1,104 @@ +# ruff: noqa: E402, PTH208, PTH123, PTH118, SIM115 +# Container script: imports are deferred on purpose and plain os/open is fine. +"""Check the VirTues image. --cpu-only skips everything that needs CUDA (flash_attn, the forward pass).""" + +import argparse +import importlib +import os +import sys + +import torch + +ap = argparse.ArgumentParser() +ap.add_argument("--cpu-only", action="store_true") +args = ap.parse_args() + +SRC = os.environ["VIRTUES_SRC"] +EMB_DIR = f"{SRC}/assets/example_dataset/marker_embeddings" + +print("python", sys.version.split()[0], "torch", torch.__version__, "cuda", torch.version.cuda) +for mod in ("spatialdata", "anndata", "geopandas", "esm", "virtues", "spora_io"): + m = importlib.import_module(mod) + print(mod, getattr(m, "__version__", "(no __version__)")) +print("uniprot release", os.environ["VIRTUES_UNIPROT_RELEASE"], "commit", os.environ["VIRTUES_COMMIT"]) + +# Mac emulation has no CUDA driver; upstream imports flash_attn unconditionally, so this may fail there. +model = None +try: + from virtues.modules.multiplex_virtues import MultiplexVirtues + from virtues.utils.utils import load_marker_embedding_dict, load_marker_embeddings + from safetensors.torch import load_file + + emb = load_marker_embeddings(EMB_DIR) + model = MultiplexVirtues(prior_bias_embeddings=emb) + print("load_state_dict:", model.load_state_dict(load_file(os.environ["VIRTUES_WEIGHTS"]), strict=True)) +except ImportError as e: + if not args.cpu_only: + raise + print("SKIPPED model load on CPU, import failed:", e) + +# Our ESM-2 embedding of each bundled ID vs the bundled .pt (upstream: mean of layer-30 residue tokens). +import esm + +ids = sorted(f[:-3] for f in os.listdir(EMB_DIR) if f.endswith(".pt")) +seqs, name = {}, None +for line in open(os.environ["VIRTUES_UNIPROT"]): + if line.startswith(">"): + name = line.split("|")[1] + seqs[name] = [] + else: + seqs[name].append(line.strip()) +esm_model, alphabet = esm.pretrained.load_model_and_alphabet("esm2_t30_150M_UR50D") +esm_model.eval() +conv = alphabet.get_batch_converter() +worst = 0.0 +for i in ids: + seq = "".join(seqs[i]) + _, _, tok = conv([(i, seq)]) + with torch.no_grad(): + rep = esm_model(tok, repr_layers=[30])["representations"][30][0, 1 : len(seq) + 1].mean(0) + d = (rep - torch.load(f"{EMB_DIR}/{i}.pt", weights_only=True)).abs().max().item() + worst = max(worst, d) + print(f"esm {i} len={len(seq)} max_abs_diff={d:.3e}") +print("esm max_abs_diff over", len(ids), "markers:", f"{worst:.3e}") + +if args.cpu_only: + print("OK (cpu-only)") + sys.exit(0) + +# Cluster path: as notebook 2_demo_cell_phenotyping.ipynb. +import flash_attn +from omegaconf import OmegaConf +from spora_io import MultiplexImagingDataset +from virtues.utils.cell_tokens import compute_cell_tokens + +print("flash_attn", flash_attn.__version__, "gpu", torch.cuda.get_device_name(0)) +model = model.cuda().eval() +conf = OmegaConf.load(f"{SRC}/configs/base_config.yaml") +c = OmegaConf.load(f"{SRC}/configs/datasets/example_config.yaml")["datasets"]["example_dataset"] +ds = MultiplexImagingDataset( + name=c.name, + path=os.path.join(SRC, c.path), + modality=c.modality, + standardization=c.standardization, + resolution=c.resolution, + tile_size=conf.data.tile_size, + disable_quantile_mask=True, + filter_list=["gaussian_blur"], + use_mean_std=True, +) +tid = "cords2024cancer_ocmzljpb_0001" +t = ds.get_tissue(tissue_id=tid, kind="uniprot_filtered", preprocess=False) +emb_dict = load_marker_embedding_dict(EMB_DIR) +midxs = torch.tensor([emb_dict[u] for u in t.uniprot_ids], dtype=torch.long) +mask = ds.get_cell_instance_mask(tid).mask +pad = (120, 120, 120, 120) +x = torch.nn.functional.pad(t.image, pad=pad) +mask = torch.nn.functional.pad(mask, pad=pad) +x, refined = ds.standardizer.apply(x, tid, t.measured_mask, t.image_loading_mask) +ds._refine_channel_metadata(t.image_loading_mask, t.channel_names, t.uniprot_ids, refined) +cell_ids, tokens, crop_tokens, idx = compute_cell_tokens(model, x, midxs, mask) +print("image", tuple(x.shape), "crops", len(idx), "channels", len(midxs)) +print("patch_summary_tokens per crop:", tuple(crop_tokens[0].shape), crop_tokens[0].dtype) +print("cell_tokens:", tuple(tokens.shape), tokens.dtype, "cells", len(cell_ids)) +print("OK (cluster)") diff --git a/tools/make_nimbus_fixture.py b/tools/make_nimbus_fixture.py new file mode 100644 index 0000000..4fa60d2 --- /dev/null +++ b/tools/make_nimbus_fixture.py @@ -0,0 +1,52 @@ +"""Cut the Nimbus parity fixture from a stitched OME-TIFF (CYX). + +Usage: python -I tools/make_nimbus_fixture.py [size [y0 x0]] +Needs numpy, tifffile, scikit-image, scipy (e.g. `uv run --with ...`). +Writes image.npy (C,Y,X uint16) and labels.npy (int32). +""" + +import sys +from pathlib import Path + +import numpy as np +import tifffile +from scipy import ndimage as ndi +from skimage.feature import peak_local_max +from skimage.filters import gaussian, threshold_otsu +from skimage.segmentation import expand_labels, watershed + +# 0-based channels of exemplar-001 (markers_exemplar001.csv): DNA_6, CD45 (dense), FOXP3 (sparse). +DNA, CHANNELS = 0, (3, 10) +Y0, X0, SIZE = 1000, 600, 1280 +EXPAND_PX = 3 + + +def whole_cell_labels(dna): + """Quick nuclei watershed expanded to whole cells. Parity does not depend on its quality.""" + smooth = gaussian(dna.astype(np.float32), 2) + fg = smooth > threshold_otsu(smooth) + dist = ndi.distance_transform_edt(fg) + peaks = peak_local_max(gaussian(dist, 1), min_distance=5, labels=fg) + markers = np.zeros(dna.shape, np.int32) + markers[tuple(peaks.T)] = np.arange(1, len(peaks) + 1) + nuclei = watershed(-dist, markers, mask=fg) + return expand_labels(nuclei, EXPAND_PX).astype(np.int32) + + +def main(src, out_dir, size=SIZE, y0=Y0, x0=X0): + out = Path(out_dir) + out.mkdir(parents=True, exist_ok=True) + stack = tifffile.imread(src) + win = (slice(y0, y0 + size), slice(x0, x0 + size)) + image = np.stack([stack[c][win] for c in CHANNELS]).astype(np.uint16) + labels = whole_cell_labels(stack[DNA][win]) + np.save(out / "image.npy", image) + np.save(out / "labels.npy", labels) + print( + f"image {image.shape} {image.dtype}, labels {labels.shape} {labels.dtype}, " + f"{len(np.unique(labels)) - 1} cells" + ) + + +if __name__ == "__main__": + main(*sys.argv[1:3], *map(int, sys.argv[3:6])) diff --git a/tools/nimbus_reference.py b/tools/nimbus_reference.py new file mode 100644 index 0000000..047be16 --- /dev/null +++ b/tools/nimbus_reference.py @@ -0,0 +1,62 @@ +"""Run upstream Nimbus on the fixture crop to produce the parity reference. + +Usage: python -I tools/nimbus_reference.py [pixel_size [checkpoint]] +Needs Nimbus-Inference==0.0.5 in a numpy<2 environment (see tools/containers/nimbus/README.md). +Reads image.npy and labels.npy; writes factors.json and reference_scores.csv. +pixel_size 1 (default): magnification = model_magnification = 10, so upstream does no rescaling. +Otherwise magnification = 10 / pixel_size and upstream resizes (int()) itself. +checkpoint "latest" downloads V1.pt; pass "V1.pt" inside the nimbus image (no network). +""" + +import json +import sys +import tempfile +from pathlib import Path + +import numpy as np +import tifffile +from nimbus_inference.nimbus import Nimbus +from nimbus_inference.utils import MultiplexDataset + +CHANNEL_NAMES = ("CD45", "FOXP3") # image.npy channel order, see make_nimbus_fixture.py + + +def main(fixture, pixel_size=1.0, checkpoint="latest"): + fixture = Path(fixture) + image = np.load(fixture / "image.npy") + labels = np.load(fixture / "labels.npy") + with tempfile.TemporaryDirectory() as tmp: + fov = Path(tmp) / "crop" + fov.mkdir() + for name, plane in zip(CHANNEL_NAMES, image, strict=False): + tifffile.imwrite(fov / f"{name}.tiff", plane) + tifffile.imwrite(Path(tmp) / "labels.tiff", labels) + dataset = MultiplexDataset( + [str(fov)], + lambda _: str(Path(tmp) / "labels.tiff"), + suffix=".tiff", + magnification=10 / pixel_size, + output_dir=tmp, + ) + # One FOV, so the factor is deterministic (upstream's subset shuffle is moot). + dataset.prepare_normalization_dict(n_subset=1, overwrite=True) + nimbus = Nimbus( + dataset=dataset, + output_dir=tmp, + save_predictions=False, + batch_size=4, + test_time_aug=True, + model_magnification=10, + device="cpu", + checkpoint=checkpoint, + ) + table = nimbus.predict_fovs() + factors = {k: float(v) for k, v in dataset.normalization_dict.items()} + (fixture / "factors.json").write_text(json.dumps(factors, indent=2)) + out = table[["label", *CHANNEL_NAMES]].sort_values("label") + out.to_csv(fixture / "reference_scores.csv", index=False) + print(f"{len(out)} cells; factors {factors}") + + +if __name__ == "__main__": + main(sys.argv[1], *([float(sys.argv[2])] if len(sys.argv) > 2 else []), *sys.argv[3:4]) diff --git a/tools/segmentation_benchmark/README.md b/tools/segmentation_benchmark/README.md new file mode 100644 index 0000000..6da421a --- /dev/null +++ b/tools/segmentation_benchmark/README.md @@ -0,0 +1,59 @@ +# Segmentation benchmark + +Scores Cellpose-SAM (`cpsam_v2`, diameter 30) against ground-truth masks on three public +datasets (Cross-platform, Tonsil, TissueNet). One SLURM array task runs one setting of the +preprocessing/threshold grid (`settings.csv`, 168 rows) over its crops and writes +`results/.csv` (F1 and AP at IoU 0.5-0.9 per crop). Montage crops also write their labels. +Data never enters the repo. + +## Steps + +1. Prepare on the Mac (raw downloads to one crop layout): + `python tools/segmentation_benchmark/prepare.py --raw $RAW --out $BENCH/data` +2. Copy data and repo to cluster scratch: + `rsync -a $BENCH/data/ cluster:$SCRATCH/bench/data/` and + `rsync -a --exclude .git ./ cluster:$SCRATCH/bench/repo/` +3. Timing job first (today's cells/raw setting, 20 crops); `--time` on the command line + overrides the 4 h default, extra arguments go to `run.py`. It writes `results/18.partial.csv`, + which the full array ignores: + `sbatch --array=18 --time=01:00:00 tools/segmentation_benchmark/run_array.sbatch --limit-crops 20` + Use its seconds to set `--time` in the sbatch. +4. Full array: + `export SIF=... DATA=$SCRATCH/bench/data OUT=$SCRATCH/bench/out REPO=$SCRATCH/bench/repo` + `sbatch --array=0-167%8 tools/segmentation_benchmark/run_array.sbatch` + Set the partition line in the script first. Finished settings are skipped on resubmit. +5. Copy back and report: `rsync -a cluster:$SCRATCH/bench/out/{results,labels} $BENCH/out/`, then + `python tools/segmentation_benchmark/report.py --results $BENCH/out/results --data $BENCH/data --out $BENCH/out/report` + +## Round 2 + +`settings_round2.csv`, 307 rows, on round 1's best preprocessing (max, percentile 1, no +smoothing, no CLAHE): + +- 0-167: cells on Cross-platform and Tonsil, 7 `flow_threshold` x 8 `cellprob_threshold`, for + each cell channel selection: `markers` (no autofluorescence; the baseline), `all` (round 1), + `membrane` (also no nuclear-localised markers). +- 168-223: cells on TissueNet; 224-279: nuclei on all three (no projection smoothing). +- 280-306: CLAHE 0.01 at 9 threshold pairs, one block per target. + +The pick is one threshold pair for nuclei and cells: the smallest worst shortfall from the best +on cells and nuclei, Cross-platform and TissueNet. Tonsil is reported, not used. + +1. Prepare as above into a new folder (Vectra channel names come from the TIFF metadata): + `--out $BENCH/data_round2`, then rsync it to the cluster. +2. `sbatch --array=0-306%8 --time=00:30:00 tools/segmentation_benchmark/run_array.sbatch --grid round2` + with `DATA` and `OUT` pointing at the round-2 folders. +3. `python tools/segmentation_benchmark/report_round2.py --results $BENCH/out_round2/results --out $BENCH/out_round2/report --round1 $BENCH/out/results` + (`--round1` checks that the six settings both rounds share give the same F1). + +## Data layout + +`data/crops.csv` lists every crop; each has `data/crops///image.tif` (C,Y,X) and +`cells.tif` and/or `nuclei.tif`. A target is scored only where its mask file exists. +Settings 0-143 are cells on Cross-platform and Tonsil, 144-155 cells on TissueNet, 156-167 +nuclei on all three. + +## Licences and tokens + +TissueNet: non-commercial use. Cross-platform: CC BY 4.0 (per its paper). Tonsil: CC BY 4.0. +Download tokens (Synapse) live in `~/.synapseConfig`, never in the repo. diff --git a/tools/segmentation_benchmark/__init__.py b/tools/segmentation_benchmark/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tools/segmentation_benchmark/prepare.py b/tools/segmentation_benchmark/prepare.py new file mode 100644 index 0000000..4da168d --- /dev/null +++ b/tools/segmentation_benchmark/prepare.py @@ -0,0 +1,387 @@ +"""Normalise the benchmark datasets into one crop layout. + +Writes `crops///{image,cells,nuclei}.tif` (image C,Y,X as stored; labels +uint32; a label file is absent when the dataset has no such mask) and `crops.csv`. Every +run rewrites everything it finds, so re-running after a download only adds crops. + +Findings from inspecting the data (Cross-platform = Aleynick et al. 2023, Sci Data): +- Cross-platform ROIs are all FREEHAND polygons; no other type occurs. Neighbouring cells + share boundary pixels, so 5-15% of foreground is covered twice; the later ROI wins and the + share is reported. The dataset's own *_Mask_Png.png draws cells with a 1-px gap, so it + matches our fill in the interior only (see the report for agreement numbers). +- Vectra crop TIFFs are (8, 400, 400) float32 ImageJ hyperstacks; the inForm channel names + (marker, Opal dye, DAPI or Hoechst, Autofluorescence) are in the ImageJ Info field as + `Name #k = ...`. DAPI is found independently: the channel best correlated with the pure-blue + part (B - max(R, G)) of the crop's own *_Cell_Png.png composite; *_Dapi_Png.png is only a + cross-check. A crop whose DAPI channel is not named DAPI/Hoechst is skipped. Without names, + channels are ch. P05's CD40L is poor quality per the xlsx; kept. 0.5 um/px. +- CODEX crop TIFFs are (T, 4, 400, 400) uint16, T cycles x 4 channels; flattening t*4+c gives + the "Channel Name" order of the xlsx Markers sheet. We keep DAPI1 (index 0) and the real + markers and drop Blank/Empty channels and the repeat DAPI cycles, so "every non-DNA channel" + holds (accepted: a user's marker sheet would do the same). Pixel size 0.3774 um. +- Tonsil (Zenodo 22107836): (7, 100, 100) uint16, DAPI is index 6 on all 10 crops (checked by + `tonsil_nuclear_channel`); nuclei ids are a subset of cell ids. Pixel size unknown. +- TissueNet 1.1 test npz (modified Apache, non-commercial): X (N,256,256,2) = [nuclear, whole + cell], y (N,256,256,2) = [whole cell, nuclear]; `meta` has 4 header rows (header text + repeated) before N data rows, checked to be 1:1 with X. platform = experiment folder name, + tissue = specimen, 0.5 um/px. Only the test split is read. +""" + +from __future__ import annotations + +import argparse +import re +import sys +from collections import Counter +from pathlib import Path + +import numpy as np +import pandas as pd +import tifffile +from skimage.draw import polygon + +PIXEL_SIZE_UM = {"Vectra": 0.5, "CODEX": 0.3774} # paper Table 2 +POLYGON_TYPES = ("POLYGON", "FREEHAND", "TRACED") +DAPI_MIN_CORR = 0.9 +TISSUENET_TEST = "tissuenet_v1.1_test.npz" +TISSUENET_MONTAGE_MIN_CELLS = 20 +DAPI_MIN_BLUE_CORR = 0.5 +DAPI_MIN_MARGIN = 0.1 +DNA_NAMES = ("dapi", "hoechst") +COLUMNS = [ + "dataset", "crop", "platform", "tissue", "pixel_size_um", "channels", "nuclear", + "height", "width", "montage", "n_cells", "n_nuclei", +] # fmt: skip + + +def rois_to_labels(rois: list, shape: tuple[int, int]) -> tuple[np.ndarray, float]: + """Instance labels 1..N in ROI order, and the share of foreground covered by 2+ ROIs.""" + labels = np.zeros(shape, np.uint32) + covered = np.zeros(shape, np.uint8) + for i, roi in enumerate(rois, 1): + if roi.roitype.name not in POLYGON_TYPES: + raise ValueError(f"ROI {i} has unsupported type {roi.roitype.name}") + xy = roi.coordinates() + rr, cc = polygon(xy[:, 1], xy[:, 0], shape) + labels[rr, cc] = i # the later ROI wins an overlap + covered[rr, cc] = np.minimum(covered[rr, cc] + 1, 2) + foreground = (covered > 0).sum() + return labels, float((covered > 1).sum() / foreground) if foreground else 0.0 + + +def tonsil_nuclear_channel(image: np.ndarray, nuclei: np.ndarray) -> int: + """The channel most enriched inside nuclei (mean inside / mean outside).""" + inside = nuclei > 0 + ratio = [ch[inside].mean() / max(ch[~inside].mean(), 1e-9) for ch in image] + return int(np.argmax(ratio)) + + +def _key(name: str) -> str: + """File and xlsx crop names differ in brackets and dots; compare alphanumerics only.""" + return re.sub(r"[^A-Za-z0-9]", "", name).lower() + + +def _crop_name(folder: str) -> str: + return re.sub(r"[^A-Za-z0-9.-]+", "_", folder.strip()).strip("_") + + +def _one(folder: Path, pattern: str, skipped: list) -> Path | None: + found = sorted(folder.glob(pattern)) + if len(found) > 1: + skipped.append((folder.name, f"{len(found)} files match {pattern}")) + return None + return found[0] if found else None + + +def _read_rois(zip_path: Path | None, shape: tuple[int, int]) -> tuple[np.ndarray | None, float]: + import roifile + + if zip_path is None: + return None, 0.0 + return rois_to_labels(roifile.roiread(zip_path), shape) + + +def _panel_tables(xlsx: Path) -> tuple[dict, dict]: + """(crop key -> tissue, CODEX sample prefix -> channel names in file order).""" + import openpyxl + + wb = openpyxl.load_workbook(xlsx, read_only=True, data_only=True) + tissue, codex = {}, {} + for sheet in ("Vectra", "Codex"): + for row in wb[sheet].iter_rows(min_row=2, values_only=True): + if row[0] and row[1] and "Markers" not in str(row[0]): + tissue[_key(str(row[0]))] = str(row[1]).strip() + prefix = None + for row in wb["Codex"].iter_rows(min_row=2, values_only=True): + if row[0] and str(row[0]).endswith(" Markers"): + prefix = str(row[0]).removesuffix(" Markers") + codex[prefix] = [] + if prefix and isinstance(row[1], int) and row[2]: + codex[prefix].append(str(row[2]).strip()) + return tissue, codex + + +def _codex_channels(img: np.ndarray, folder: str, panels: dict, skipped: list): + """Flatten (T, 4, Y, X); keep DAPI1 and the real markers. None when names do not fit.""" + img = img.reshape(-1, *img.shape[-2:]) + names = next((v for k, v in panels.items() if folder.lower().startswith(k.lower())), None) + if names is None or len(names) != len(img): + skipped.append( + (folder, f"panel names {None if names is None else len(names)} != {len(img)} channels") + ) + return None + keep = [i for i, n in enumerate(names) if n == "DAPI1" or not re.fullmatch(r"Blank|Empty|DAPI\d", n)] + return img[keep], [names[i] for i in keep], 0 + + +def _load_png(path: Path | None) -> np.ndarray | None: + from PIL import Image + + if path is None: + return None + try: # PIL sniffs content: some *_Png.png files are really TIFFs + return np.asarray(Image.open(path)) + except OSError: # a file still downloading + return None + + +def _correlations(image: np.ndarray, ref: np.ndarray) -> np.ndarray: + """Pearson r of each channel with `ref`, at ref's resolution.""" + from PIL import Image + + out = [] + for ch in image: + if ch.shape != ref.shape: + ch = np.asarray(Image.fromarray(ch.astype(np.float32)).resize(ref.shape[::-1])) + out.append(np.corrcoef(ch.ravel(), ref.ravel())[0, 1]) + return np.nan_to_num(np.array(out), nan=-1.0) + + +def dapi_from_composite(image: np.ndarray, rgb: np.ndarray) -> tuple[int | None, str]: + """DAPI is blue in every Vectra panel: pick the channel best matching the pure-blue part.""" + rgb = rgb[..., :3].astype(float) + blue = np.clip(rgb[..., 2] - np.maximum(rgb[..., 0], rgb[..., 1]), 0, None) # cyan/white are not DAPI + corr = _correlations(image, blue) + order = np.argsort(-corr) + if corr[order[0]] < DAPI_MIN_BLUE_CORR: + return None, f"best blue correlation {corr[order[0]]:.2f} < {DAPI_MIN_BLUE_CORR}" + if corr[order[0]] - corr[order[1]] < DAPI_MIN_MARGIN: + return ( + None, + f"top two blue correlations within {DAPI_MIN_MARGIN} ({corr[order[0]]:.2f}, {corr[order[1]]:.2f})", + ) + return int(order[0]), "" + + +def _vectra_nuclear(img: np.ndarray, folder: Path, skipped: list) -> tuple[int | None, str]: + """(DAPI index, check). The composite decides; the DAPI render, when present, only checks.""" + dapi = _load_png(_one(folder, "*Dapi_Png.png", skipped)) + by_dapi, corr = None, None + if dapi is not None: + dapi = dapi if dapi.ndim == 2 else dapi[..., :3].mean(-1) + corr = _correlations(img, dapi.astype(float)) + by_dapi = int(np.argmax(corr)) if corr.max() >= DAPI_MIN_CORR else None + composite = _load_png(_one(folder, "*-Crop_Cell_Png.png", skipped)) + if composite is None or composite.ndim != 3: + if by_dapi is None: + skipped.append((folder.name, "DAPI not identified: no usable composite or DAPI PNG")) + return None, "none" + return by_dapi, "dapi-png only" + index, why = dapi_from_composite(img, composite) + if index is None: + skipped.append((folder.name, f"DAPI not identified from composite: {why}")) + return None, "none" + if by_dapi is None: + return index, "composite only" + if by_dapi != index: # trust neither + skipped.append( + ( + folder.name, + f"DAPI methods disagree: composite ch{index} (DAPI-PNG r={corr[index]:.2f}), " + f"DAPI PNG ch{by_dapi} (r={corr[by_dapi]:.2f})", + ) + ) + return None, "disagree" + return index, "agree" + + +def vectra_channel_names(tif: Path) -> list[str] | None: + """inForm channel names from the ImageJ Info field, or None when absent or not 1..N.""" + with tifffile.TiffFile(tif) as t: + info = (t.imagej_metadata or {}).get("Info", "") + found = {int(k): v.strip() for k, v in re.findall(r"^Name #(\d+) = (.*)$", info, flags=re.M)} + if not found or sorted(found) != list(range(1, len(found) + 1)): + return None + return [found[k] for k in sorted(found)] + + +def is_dna_name(name: str) -> bool: + return name.strip().lower().startswith(DNA_NAMES) + + +def read_crossplatform(root: Path, skipped: list | None = None): + """Yield (row, image, cells, nuclei) per Vectra/CODEX crop; skips are appended to `skipped`.""" + root = Path(root) + skipped = skipped if skipped is not None else [] + xlsx = root / "Annotation Panel Table.xlsx" + tissues, panels = _panel_tables(xlsx) + folders = sorted((p for p in (root / "Vectra").glob("*/*") if p.is_dir()), key=lambda p: p.name) + sorted( + (p for p in (root / "CODEX").glob("*") if p.is_dir()), key=lambda p: p.name + ) + for folder in folders: + platform = "Vectra" if folder.parent.parent.name == "Vectra" else "CODEX" + tif = _one(folder, "*-Crop_Tif*.tif", skipped) # also matches -Crop_Tiff.tif + if tif is None: + skipped.append((folder.name, "no crop TIFF")) + continue + cell_zip = _one(folder, "*Cell_Mask_Roi_Zip*.zip", skipped) + dapi_zip = _one(folder, "*Dapi_Mask_Roi_Zip*.zip", skipped) # also Roi_Zip-1.zip + if cell_zip is None and dapi_zip is None: + skipped.append((folder.name, "no cell or nuclei ROIs")) + continue + img = tifffile.imread(tif) + if platform == "CODEX": + out = _codex_channels(img, folder.name, panels, skipped) + if out is None: + continue + img, names, nuclear = out + else: + nuclear, check = _vectra_nuclear(img, folder, skipped) + if nuclear is None: + continue + names = vectra_channel_names(tif) + if names is None or len(names) != len(img): + names = [f"ch{i}" for i in range(len(img))] + names[nuclear] = "DAPI" + elif not is_dna_name(names[nuclear]): + skipped.append((folder.name, f"DAPI found at ch{nuclear}, which is named {names[nuclear]!r}")) + continue + shape = img.shape[-2:] + cells, overlap_c = _read_rois(cell_zip, shape) + nuclei, overlap_n = _read_rois(dapi_zip, shape) + row = { + "dataset": "crossplatform", "crop": _crop_name(folder.name), "platform": platform, + "tissue": tissues.get(_key(folder.name), "unknown"), + "pixel_size_um": PIXEL_SIZE_UM[platform], "channels": "|".join(names), + "nuclear": nuclear, "height": shape[0], "width": shape[1], + "n_cells": 0 if cells is None else int(cells.max()), + "n_nuclei": 0 if nuclei is None else int(nuclei.max()), + "overlap_cells": overlap_c, "overlap_nuclei": overlap_n, + "dapi_check": check if platform == "Vectra" else "n/a", + } # fmt: skip + if row["tissue"] == "unknown": + skipped.append((folder.name, "tissue not found in xlsx (kept as unknown)")) + yield row, img, cells, nuclei + + +def read_tonsil(root: Path): + """Yield (row, image, cells, nuclei) per Zenodo tonsil crop.""" + names = ["CD21", "CD23", "CD20", "CD4", "CK", "CD8", "DAPI"] + for tif in sorted(Path(root).glob("*.tif")): + if "_GT_" in tif.name: + continue + img = tifffile.imread(tif) + cells = tifffile.imread(tif.with_name(tif.stem + "_GT_cells.tif")).astype(np.uint32) + nuclei = tifffile.imread(tif.with_name(tif.stem + "_GT_nuclei.tif")).astype(np.uint32) + nuclear = tonsil_nuclear_channel(img, nuclei) + assert nuclear == 6, f"{tif.name}: DAPI expected at 6, found {nuclear}" + row = { + "dataset": "tonsil", "crop": tif.stem, "platform": "unknown", "tissue": "tonsil", + "pixel_size_um": np.nan, "channels": "|".join(names), "nuclear": nuclear, + "height": img.shape[1], "width": img.shape[2], + "n_cells": len(np.unique(cells)) - 1, "n_nuclei": len(np.unique(nuclei)) - 1, + "overlap_cells": 0.0, "overlap_nuclei": 0.0, "dapi_check": "n/a", + } # fmt: skip + yield row, img, cells, nuclei + + +def read_tissuenet(npz: Path): + """Yield (row, image, cells, nuclei) per tile of a TissueNet test npz.""" + data = np.load(npz, allow_pickle=True) # meta is an object array + x, y, meta = data["X"], data["y"], data["meta"] + is_header = meta[:, 0] == "filename" + meta = meta[~is_header] + if len(meta) != len(x) or len(y) != len(x) or x.shape[-1] != 2 or y.shape[-1] != 2: + raise ValueError( + f"TissueNet meta rows {len(meta)} (after {is_header.sum()} headers) != {len(x)} tiles" + ) + for i, (m, tile, lab) in enumerate(zip(meta, x, y, strict=True)): + image = np.moveaxis(tile, -1, 0).astype(np.float32) # [nuclear, whole cell] + cells, nuclei = lab[..., 0].astype(np.uint32), lab[..., 1].astype(np.uint32) + row = { + "dataset": "tissuenet", "crop": f"{i:04d}", "platform": Path(str(m[1])).name, + "tissue": str(m[5]), "pixel_size_um": float(m[2]), "channels": "nuclear|membrane", + "nuclear": 0, "height": image.shape[1], "width": image.shape[2], + "n_cells": len(np.unique(cells)) - 1, "n_nuclei": len(np.unique(nuclei)) - 1, + "overlap_cells": 0.0, "overlap_nuclei": 0.0, "dapi_check": "n/a", + } # fmt: skip + yield row, image, cells, nuclei + + +def _mark_montage(rows: list[dict]) -> None: + """First crop by name per Cross-platform platform (with cell masks), first two tonsil, first TissueNet tile with 20+ cells.""" + for r in rows: + r["montage"] = False + ordered = sorted(rows, key=lambda r: (r["dataset"], r["crop"])) + seen = Counter() + for r in ordered: + group, limit = (r["platform"], 1) if r["dataset"] == "crossplatform" else (r["dataset"], 2) + need = TISSUENET_MONTAGE_MIN_CELLS if r["dataset"] == "tissuenet" else 1 + limit = 1 if r["dataset"] == "tissuenet" else limit + if r["n_cells"] >= need and seen[group] < limit: + r["montage"] = True + seen[group] += 1 + + +def prepare(raw: Path, out: Path) -> tuple[pd.DataFrame, list]: + raw, out = Path(raw), Path(out) + skipped: list = [] + readers = [] + if (raw / "crossplatform").is_dir(): + readers.append(read_crossplatform(raw / "crossplatform", skipped)) + if (raw / "tonsil").is_dir(): + readers.append(read_tonsil(raw / "tonsil")) + if (raw / "tissuenet" / TISSUENET_TEST).is_file(): + readers.append(read_tissuenet(raw / "tissuenet" / TISSUENET_TEST)) + rows = [] + for reader in readers: + for row, image, cells, nuclei in reader: + folder = out / "crops" / row["dataset"] / row["crop"] + folder.mkdir(parents=True, exist_ok=True) + tifffile.imwrite(folder / "image.tif", image, compression="zlib") + for name, labels in (("cells", cells), ("nuclei", nuclei)): + if labels is not None: + tifffile.imwrite(folder / f"{name}.tif", labels.astype(np.uint32), compression="zlib") + else: + (folder / f"{name}.tif").unlink(missing_ok=True) + rows.append(row) + _mark_montage(rows) + table = pd.DataFrame(rows) + table[COLUMNS].to_csv(out / "crops.csv", index=False) + return table, skipped + + +def main() -> None: + parser = argparse.ArgumentParser(description="Write the benchmark crops and crops.csv.") + parser.add_argument( + "--raw", type=Path, required=True, help="folder with tonsil/, crossplatform/, tissuenet/" + ) + parser.add_argument("--out", type=Path, required=True) + args = parser.parse_args() + args.out.mkdir(parents=True, exist_ok=True) + table, skipped = prepare(args.raw, args.out) + for folder, why in skipped: + print(f"skipped {folder}: {why}", file=sys.stderr) + print( + table.groupby("dataset").agg( + crops=("crop", "size"), cells=("n_cells", "sum"), nuclei=("n_nuclei", "sum"), + nuclei_crops=("n_nuclei", lambda s: int((s > 0).sum())), + max_overlap_cells=("overlap_cells", "max"), max_overlap_nuclei=("overlap_nuclei", "max"), + ).to_string() + ) # fmt: skip + print(f"Vectra DAPI check: {dict(table.loc[table['platform'] == 'Vectra', 'dapi_check'].value_counts())}") + print(f"montage crops: {table.loc[table['montage'], ['dataset', 'crop']].values.tolist()}") + + +if __name__ == "__main__": + main() diff --git a/tools/segmentation_benchmark/preprocess.py b/tools/segmentation_benchmark/preprocess.py new file mode 100644 index 0000000..0dc80a0 --- /dev/null +++ b/tools/segmentation_benchmark/preprocess.py @@ -0,0 +1,103 @@ +"""Crop preprocessing for the segmentation benchmark, equal to the pipeline's. + +project() mirrors bin/project_channels.py (percentiles, rescale, Gaussian, combine, uint16) so +benchmark results transfer; the percentiles come from the crop itself. +""" + +from __future__ import annotations + +import sys +from pathlib import Path + +import numpy as np + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "bin")) + +from project_channels import combine, percentile_bounds, rescale # noqa: E402 + +# Nuclear-localised markers in the Cross-platform and CODEX panels; left out of `membrane`. +NUCLEAR_MARKERS = {"ki67", "foxp3", "tcf1", "tox", "mum1", "pax8", "p63"} +SELECTIONS = ("all", "markers", "membrane") + + +def _marker(name: str) -> str: + """'Foxp3 (Opal 620)' -> 'foxp3'.""" + return name.split("(")[0].strip().lower().replace("-", "") + + +def cell_channels(names: list[str], nuclear: int, selection: str) -> list[int]: + """Indices combined into the cell plane: every non-DNA channel, minus autofluorescence + (`markers`), minus nuclear-localised markers too (`membrane`).""" + if selection not in SELECTIONS: + raise ValueError(f"unknown cell channel selection {selection!r}; expected one of {SELECTIONS}") + keep = [] + for i, name in enumerate(names): + marker = _marker(name) + if i == nuclear: + continue + if selection != "all" and marker.startswith("autofluorescence"): + continue + if selection == "membrane" and marker in NUCLEAR_MARKERS: + continue + keep.append(i) + if not keep: + raise ValueError(f"no cell channels left for selection {selection!r} in {names}") + return keep + + +def _group(planes: np.ndarray, method: str, low: float, high: float, sigma: float) -> np.ndarray: + """One projected plane as uint16; flat channels are left out, none left gives zeros.""" + from scipy.ndimage import gaussian_filter + + stack = [] + for plane in planes: + bounds = percentile_bounds(plane, low, high) + if bounds is None: + continue + x = rescale(plane, *bounds) + stack.append(gaussian_filter(x, sigma) if sigma > 0 else x) + if not stack: + return np.zeros(planes.shape[1:], np.uint16) + return (combine(np.stack(stack), method) * 65535 + 0.5).astype(np.uint16) + + +def project( + image: np.ndarray, + nuclear: int, + method: str, + low: float, + sigma: float, + high: float = 99.9, + cell_idx: list[int] | None = None, +) -> np.ndarray: + """(2, Y, X) uint16 [cell, nuclear]; cell is `cell_idx`, by default every channel but `nuclear`.""" + cells = np.delete(image, nuclear, axis=0) if cell_idx is None else image[cell_idx] + return np.stack( + [_group(cells, method, low, high, sigma), _group(image[[nuclear]], method, low, high, sigma)] + ) + + +def sopa_preprocess(image, gaussian_sigma: float, clip_limit: float): + """sopa.segmentation.stainings._run_patch, before the model.""" + from scipy.ndimage import gaussian_filter + from skimage import exposure + + if gaussian_sigma > 0: + image = np.stack([gaussian_filter(c, sigma=gaussian_sigma) for c in image]) + if clip_limit > 0: + image = np.stack([exposure.equalize_adapthist(c, clip_limit=clip_limit) for c in image]) + return image + + +def pad_to(image: np.ndarray, size: int = 256) -> tuple[np.ndarray, tuple[int, int]]: + """Reflect-pad (C, Y, X) at the bottom/right to at least `size`; also return the old (Y, X).""" + y, x = image.shape[1:] + pad = ((0, 0), (0, max(0, size - y)), (0, max(0, size - x))) + return np.pad(image, pad, mode="reflect"), (y, x) + + +def unpad(labels: np.ndarray, shape: tuple[int, int]) -> np.ndarray: + """Crop labels back to `shape` and renumber them 1..n.""" + from skimage.segmentation import relabel_sequential + + return relabel_sequential(labels[: shape[0], : shape[1]])[0] diff --git a/tools/segmentation_benchmark/report.py b/tools/segmentation_benchmark/report.py new file mode 100755 index 0000000..b6912ce --- /dev/null +++ b/tools/segmentation_benchmark/report.py @@ -0,0 +1,430 @@ +#!/usr/bin/env python3 +"""Tables and figures from the benchmark's results/ directory. + +Cross-platform decides: the best cells setting (0-143) and the best nuclei setting (156-167) +are the ones with the highest mean Cross-platform F1. TissueNet cell settings (144-155) are +ranked on TissueNet alone. Crops whose F1 is NaN (both masks empty) are counted, never averaged. +Writes summary.csv, headline.json, effects_.png, interaction.png, platforms.png and +montage___.png. +""" + +from __future__ import annotations + +import argparse +import itertools +import json +import sys +from pathlib import Path + +import numpy as np +import pandas as pd + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from segmentation_benchmark.settings import today_index # noqa: E402 + +# Ranking blocks: name -> (target, scope, dataset the rank is decided on). +BLOCKS = { + "cells_raw": ("cells", "raw", "crossplatform"), + "nuclei_all": ("nuclei", "all", "crossplatform"), + "cells_tissuenet": ("cells", "tissuenet", "tissuenet"), +} +FACTORS = { + "projection_method": "Projection method", + "low_percentile": "Low percentile", + "projection_sigma": "Projection sigma", + "gaussian_sigma": "Gaussian sigma", + "clip_limit": "CLAHE clip limit", + "thresholds": "Flow / cellprob thresholds", +} +FACTOR_COLUMNS = [c for c in FACTORS if c != "thresholds"] + ["flow_threshold", "cellprob_threshold"] +GROUPS = ["Vectra", "CODEX", "Tonsil", "TissueNet"] + +# dataviz palette, light surface: blue = today, orange = best. +TODAY_COLOR, BEST_COLOR = "#2a78d6", "#eb6834" +INK, INK_2, GRID, POINT = "#0b0b0b", "#52514e", "#e4e3de", "#a9a8a1" +F1_LABEL = "Cross-platform F1 (IoU 0.5)" + + +def load(results: Path, settings: pd.DataFrame) -> pd.DataFrame: + """Per-crop rows of every finished setting, with the setting's factors attached.""" + files = sorted(p for p in results.glob("*.csv") if not p.name.endswith(".partial.csv")) + if not files: + raise SystemExit(f"no results/.csv in {results}") + df = pd.concat([pd.read_csv(p, dtype={"crop": str}) for p in files], ignore_index=True) + df["group"] = np.where(df["dataset"] == "crossplatform", df["platform"], df["dataset"].str.capitalize()) + df.loc[df["dataset"] == "tissuenet", "group"] = "TissueNet" + return df.drop(columns=["target"]).merge(settings, on="index", how="left") + + +def summarise(df: pd.DataFrame) -> pd.DataFrame: + """Per setting x dataset: mean and SD of F1 and mean AP over crops, n crops, n NaN crops.""" + grouped = df.groupby(["index", "target", "scope", "dataset"]) + out = grouped.agg( + mean_f1=("f1", "mean"), + sd_f1=("f1", "std"), + mean_ap=("mean_ap", "mean"), + sd_ap=("mean_ap", "std"), + n_crops=("f1", "size"), + n_nan=("f1", lambda s: int(s.isna().sum())), + ) + return out.reset_index() + + +def _row(summary: pd.DataFrame, settings: pd.DataFrame, index: int, dataset: str) -> dict | None: + """One headline row: factor values and scores of setting `index` on `dataset`.""" + sel = summary[(summary["index"] == index) & (summary["dataset"] == dataset)] + if sel.empty: + return None + s = sel.iloc[0] + factors = settings.set_index("index").loc[index, FACTOR_COLUMNS].to_dict() + by_dataset = summary[summary["index"] == index].set_index("dataset")["mean_f1"] + return { + "index": index, + **{k: (v.item() if hasattr(v, "item") else v) for k, v in factors.items()}, + "dataset": dataset, + "mean_f1": _num(s["mean_f1"]), + "mean_ap": _num(s["mean_ap"]), + "n_crops": int(s["n_crops"]), + "n_nan": int(s["n_nan"]), + "f1_by_dataset": {d: _num(v) for d, v in by_dataset.items()}, + } + + +def _num(value) -> float | None: + return None if pd.isna(value) else float(value) + + +def headline(summary: pd.DataFrame, settings: pd.DataFrame) -> tuple[dict, dict]: + """headline.json content and the best/today index of each block that has results.""" + found = set(summary["index"]) + missing = sorted(set(settings["index"]) - found) + if missing: + print(f"WARNING: {len(missing)} settings have no results: {missing}", file=sys.stderr) + out, picks = {"missing_settings": missing}, {} + for name, (target, scope, dataset) in BLOCKS.items(): + block = settings[(settings["target"] == target) & (settings["scope"] == scope)]["index"] + block_missing = sorted(set(block) - found) + ranked = summary[ + summary["index"].isin(block) & (summary["dataset"] == dataset) & summary["mean_f1"].notna() + ] + if ranked.empty: + print(f"{name}: no results on {dataset}, skipped", file=sys.stderr) + continue + best = int(ranked.loc[ranked["mean_f1"].idxmax(), "index"]) + today = today_index(settings, target, scope) + if block_missing: + print(f"WARNING {name}: {len(block_missing)} of {len(block)} settings missing", file=sys.stderr) + if today in block_missing: + print(f"WARNING {name}: today's setting {today} has no results", file=sys.stderr) + best_row, today_row = _row(summary, settings, best, dataset), _row(summary, settings, today, dataset) + diff = None + if today_row and best_row["mean_f1"] is not None and today_row["mean_f1"] is not None: + diff = best_row["mean_f1"] - today_row["mean_f1"] + out[name] = { + "best": best_row, + "today": today_row, + "f1_difference": diff, + "today_missing": today in block_missing, + "missing_settings": block_missing, + } + picks[name] = (best, today) + return out, picks + + +def _style(): + import matplotlib as mpl + + mpl.use("Agg") + mpl.rcParams.update( + { + "font.size": 16, + "axes.titlesize": 20, + "axes.titleweight": "bold", + "axes.labelsize": 16, + "axes.edgecolor": INK_2, + "axes.labelcolor": INK, + "text.color": INK, + "xtick.color": INK_2, + "ytick.color": INK_2, + "axes.spines.top": False, + "axes.spines.right": False, + "axes.grid": True, + "axes.axisbelow": True, + "grid.color": GRID, + "grid.linewidth": 1, + "figure.facecolor": "white", + "axes.facecolor": "white", + "savefig.facecolor": "white", + "legend.frameon": False, + } + ) + + +def _level_table(block: pd.DataFrame) -> pd.DataFrame: + """Settings of the block with a combined `thresholds` factor column.""" + block = block.copy() + block["thresholds"] = [ + f"flow {f:g}\nprob {p:g}" + for f, p in zip(block["flow_threshold"], block["cellprob_threshold"], strict=True) + ] + return block + + +def effect_ranges(table: pd.DataFrame) -> dict[str, pd.Series]: + """Per factor, the mean F1 of each level, marginalised over the other factors.""" + return {f: table.groupby(f)["mean_f1"].mean() for f in FACTORS if table[f].nunique() > 1} + + +def plot_effects(table: pd.DataFrame, today: pd.Series, out: Path, note: str = "") -> dict[str, pd.Series]: + import matplotlib.pyplot as plt + from matplotlib.lines import Line2D + + means = effect_ranges(table) + lo, hi = table["mean_f1"].min(), table["mean_f1"].max() + pad = 0.08 * max(hi - lo, 0.05) + rng = np.random.default_rng(0) + for factor, level_means in means.items(): + fig, ax = plt.subplots(figsize=(10, 5.6)) + levels = list(level_means.index) + for i, level in enumerate(levels): + ys = table.loc[table[factor] == level, "mean_f1"] + ax.scatter( + i + rng.uniform(-0.18, 0.18, len(ys)), + ys, + s=36, + color=POINT, + alpha=0.7, + linewidths=0, + zorder=2, + ) + ax.scatter(i, level_means[level], s=220, color=INK, edgecolor="white", linewidths=2, zorder=3) + ax.annotate( + f"{level_means[level]:.3f}", + (i, level_means[level]), + xytext=(26, 0), + textcoords="offset points", + va="center", + fontsize=15, + bbox={"fc": "white", "ec": "none", "alpha": 0.85, "pad": 1.5}, + zorder=4, + ) + ticks = [f"{lv:g}" if isinstance(lv, int | float) else str(lv) for lv in levels] + is_today = [str(today[factor]) == str(lv) for lv in levels] + ax.set_xticks( + range(len(levels)), [t + ("\n(today)" if m else "") for t, m in zip(ticks, is_today, strict=True)] + ) + ax.set_xlim(-0.6, len(levels) - 0.4) + ax.set_ylim(lo - pad, hi + pad) + ax.set_xlabel(FACTORS[factor]) + ax.set_ylabel(f"Mean {F1_LABEL}") + ax.set_title(f"{FACTORS[factor]}: mean F1 per level") + ax.grid(axis="x", visible=False) + handles = [ + Line2D([], [], marker="o", ls="", color=POINT, markersize=7, label="one setting"), + Line2D([], [], marker="o", ls="", color=INK, markersize=13, label="mean over settings"), + ] + fig.legend(handles=handles, loc="lower center", ncol=2, fontsize=14) + if note: + fig.text(0.01, 0.01, note, fontsize=12, color=BEST_COLOR, fontweight="bold") + fig.tight_layout(rect=(0, 0.07, 1, 1)) + fig.savefig(out / f"effects_{factor}.png", dpi=200) + plt.close(fig) + return means + + +def plot_interaction(table: pd.DataFrame, means: dict[str, pd.Series], out: Path, note: str = "") -> None: + import matplotlib.pyplot as plt + from matplotlib.colors import LinearSegmentedColormap + + ranked = sorted(means, key=lambda f: means[f].max() - means[f].min(), reverse=True) + if len(ranked) < 2: + print("interaction.png: fewer than two varying factors, skipped", file=sys.stderr) + return + a, b = ranked[:2] + grid = table.pivot_table(index=a, columns=b, values="mean_f1", aggfunc="mean") + cmap = LinearSegmentedColormap.from_list("blue", ["#eaf1fb", "#2a78d6", "#0e3a73"]) + fig, ax = plt.subplots(figsize=(10, 5.6)) + im = ax.imshow(grid.values, cmap=cmap, aspect="auto") + mid = (np.nanmin(grid.values) + np.nanmax(grid.values)) / 2 + for i, j in itertools.product(range(grid.shape[0]), range(grid.shape[1])): + v = grid.values[i, j] + ax.text(j, i, f"{v:.3f}", ha="center", va="center", fontsize=18, color="white" if v > mid else INK) + fmt = lambda lv: f"{lv:g}" if isinstance(lv, int | float) else str(lv) # noqa: E731 + ax.set_xticks(range(grid.shape[1]), [fmt(v) for v in grid.columns]) + ax.set_yticks(range(grid.shape[0]), [fmt(v) for v in grid.index]) + ax.set_xlabel(FACTORS[b]) + ax.set_ylabel(FACTORS[a]) + ax.set_title(f"{FACTORS[a]} x {FACTORS[b]}: mean F1", fontsize=17) + ax.grid(False) + for s in ax.spines.values(): + s.set_visible(False) + fig.colorbar(im, ax=ax, label=f"Mean {F1_LABEL}") + if note: + fig.text(0.01, 0.01, note, fontsize=12, color=BEST_COLOR, fontweight="bold") + fig.tight_layout(rect=(0, 0.04 if note else 0, 1, 1)) + fig.savefig(out / "interaction.png", dpi=200) + plt.close(fig) + + +def plot_platforms(df: pd.DataFrame, picks: dict, out: Path) -> None: + """Best vs today per platform (Vectra, CODEX) and dataset (Tonsil, TissueNet).""" + import matplotlib.pyplot as plt + + rows = [] + for group in GROUPS: + name = "cells_tissuenet" if group == "TissueNet" else "cells_raw" + if name not in picks: + continue + best, today = picks[name] + sub = df[df["group"] == group] + both = ( + sub[sub["index"] == today] + .set_index(["dataset", "crop"])["f1"] + .to_frame("today") + .join(sub[sub["index"] == best].set_index(["dataset", "crop"])["f1"].rename("best"), how="inner") + .dropna() # only crops scored by both settings, so the bars compare like with like + ) + if len(both): + rows.append((group, both, len(both))) + if not rows: + print("platforms.png: no data, skipped", file=sys.stderr) + return + fig, ax = plt.subplots(figsize=(10, 5.6)) + width = 0.36 + for label, color, shift in [("Today", TODAY_COLOR, -1), ("Best", BEST_COLOR, 1)]: + key = label.lower() + for i, (_g, vals, _n) in enumerate(rows): + m = vals[key].mean() + if np.isnan(m): + continue + x = i + shift * width / 2 + ax.bar(x, m, width - 0.04, color=color, label=label if i == 0 else None, zorder=2) + ax.text(x, m + 0.01, f"{m:.2f}", ha="center", va="bottom", fontsize=15) + ax.set_xticks(range(len(rows)), [f"{g}\nn = {n}" for g, _v, n in rows]) + ax.set_ylim(0, 1) + ax.set_ylabel("Mean F1 (IoU 0.5)") + ax.set_title("Best vs today: mean F1 per platform and dataset") + ax.grid(axis="x", visible=False) + ax.legend(loc="upper right", ncol=2, fontsize=15) + fig.text( + 0.01, + 0.01, + "n = crops scored by both settings. TissueNet: best of its own settings (144-155).", + fontsize=12, + color=INK_2, + ) + fig.tight_layout(rect=(0, 0.03, 1, 1)) + fig.savefig(out / "platforms.png", dpi=200) + plt.close(fig) + + +def _crop_preview(data: Path, crop: pd.Series) -> np.ndarray: + """Projection preview as the pipeline makes it: nuclear magenta, cells green.""" + import tifffile + from segmentation_benchmark.preprocess import project # puts bin/ on sys.path + + from project_channels import preview_rgb + + image = tifffile.imread(data / "crops" / crop["dataset"] / crop["crop"] / "image.tif") + sigma = 0 if crop["dataset"] == "tissuenet" else 1 + proj = project(image, int(crop["nuclear"]), "max", 1, sigma) / 65535 + return preview_rgb(proj[1], proj[0]) + + +def _outline(rgb: np.ndarray, labels: np.ndarray) -> np.ndarray: + from skimage.segmentation import find_boundaries + + out = rgb.copy() + out[find_boundaries(labels, mode="inner")] = (255, 255, 0) + return out + + +def plot_montages(df: pd.DataFrame, picks: dict, data: Path, results: Path, out: Path) -> None: + import matplotlib.pyplot as plt + import tifffile + + crops_csv = data / "crops.csv" + if not crops_csv.exists(): + print(f"no {crops_csv}, montages skipped", file=sys.stderr) + return + crops = pd.read_csv(crops_csv, dtype={"crop": str}) + label_root = results.parent / "labels" + for _, crop in crops[crops["montage"].astype(bool)].iterrows(): + name = "cells_tissuenet" if crop["dataset"] == "tissuenet" else "cells_raw" + key = f"{crop['dataset']}__{crop['crop']}" + if name not in picks: + continue + best, today = picks[name] + paths = {i: label_root / str(i) / f"{key}.tif" for i in {best, today}} + truth_path = data / "crops" / crop["dataset"] / crop["crop"] / "cells.tif" + missing = [p for p in [*paths.values(), truth_path] if not p.exists()] + if missing: + print(f"montage {key}: missing {missing[0]}, skipped", file=sys.stderr) + continue + rgb = _crop_preview(data, crop) + sub = df[(df["dataset"] == crop["dataset"]) & (df["crop"] == crop["crop"])].set_index("index")["f1"] + panels = [("Ground truth\n(reference)", tifffile.imread(truth_path))] + for label, i in (("Today", today), ("Best", best)): + f1 = sub.get(i, np.nan) + shown = "n/a" if pd.isna(f1) else f"{f1:.2f}" + panels.append((f"{label} (setting {i})\nF1 (IoU 0.5) {shown}", tifffile.imread(paths[i]))) + fig, axes = plt.subplots(1, 3, figsize=(16, 5.8)) + for ax, (title, labels) in zip(axes, panels, strict=True): + ax.imshow(_outline(rgb, labels), interpolation="nearest") + ax.set_title(title, fontsize=16) + ax.axis("off") + fig.suptitle(f"{crop['dataset']} {crop['crop']}", fontsize=18, fontweight="bold") + fig.text( + 0.01, + 0.01, + "Preview: today's projection settings. Nuclei magenta, cells green.", + fontsize=12, + color=INK_2, + ) + fig.tight_layout(rect=(0, 0.03, 1, 0.94)) + fig.savefig(out / f"montage_{key}.png", dpi=150) + plt.close(fig) + + +def build_report(results: Path, data: Path, out: Path) -> None: + from segmentation_benchmark.settings import build_settings + + out.mkdir(parents=True, exist_ok=True) + settings = build_settings() + df = load(results, settings) + summary = summarise(df) + summary.to_csv(out / "summary.csv", index=False) + head, picks = headline(summary, settings) + (out / "headline.json").write_text(json.dumps(head, indent=2) + "\n") + + _style() + raw = summary[ + (summary["target"] == "cells") & (summary["scope"] == "raw") & (summary["dataset"] == "crossplatform") + ] + if not raw.empty: + table = _level_table(raw.merge(settings.drop(columns=["target", "scope"]), on="index")) + today_row = _level_table( + settings.set_index("index").loc[[today_index(settings, "cells", "raw")]] + ).iloc[0] + n_total = int(((settings["target"] == "cells") & (settings["scope"] == "raw")).sum()) + n_found = int(table["index"].nunique()) + note = f"Incomplete: {n_found} of {n_total} settings" if n_found < n_total else "" + means = plot_effects(table, today_row, out, note) + plot_interaction(table, means, out, note) + plot_platforms(df, picks, out) + plot_montages(df, picks, data, results, out) + print(f"report written to {out}") + + +def main() -> None: + p = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + p.add_argument("--results", type=Path, required=True) + p.add_argument("--data", type=Path, required=True) + p.add_argument("--out", type=Path, required=True) + a = p.parse_args() + build_report(a.results, a.data, a.out) + + +if __name__ == "__main__": + main() diff --git a/tools/segmentation_benchmark/report_round2.py b/tools/segmentation_benchmark/report_round2.py new file mode 100755 index 0000000..3b3eec4 --- /dev/null +++ b/tools/segmentation_benchmark/report_round2.py @@ -0,0 +1,262 @@ +#!/usr/bin/env python3 +"""Tables and figures from the round-2 results (settings_round2.csv). + +The pick, fixed before the run: one (flow_threshold, cellprob_threshold) pair for nuclei and +cells, the one whose worst shortfall from each key result's own best is smallest (ties: higher +mean F1). Key results: cells and nuclei on Cross-platform and TissueNet, `markers` channels, +CLAHE off. Tonsil is reported, not used (partly annotated). +Writes summary_round2.csv, pick.json, channels.csv, clahe.csv, anchors.csv (with --round1), +heatmaps.png, channels.png and clahe.png. +""" + +from __future__ import annotations + +import argparse +import json +import sys +from pathlib import Path + +import numpy as np +import pandas as pd + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from segmentation_benchmark.report import INK, INK_2, _style, load, summarise # noqa: E402 +from segmentation_benchmark.settings import CLAHE_PAIRS, build_round2, build_settings # noqa: E402 + +KEYS = { + "cells_crossplatform": ("cells", "raw", "markers", "crossplatform"), + "cells_tissuenet": ("cells", "tissuenet", "markers", "tissuenet"), + "nuclei_crossplatform": ("nuclei", "all", "markers", "crossplatform"), + "nuclei_tissuenet": ("nuclei", "all", "markers", "tissuenet"), +} +PANELS = { # heatmap title -> (target, scope, cell_channels, dataset) + "Cells · Cross-platform": KEYS["cells_crossplatform"], + "Cells · TissueNet": KEYS["cells_tissuenet"], + "Nuclei · Cross-platform": KEYS["nuclei_crossplatform"], + "Nuclei · TissueNet": KEYS["nuclei_tissuenet"], + "Cells · Cross-platform, all channels": ("cells", "raw", "all", "crossplatform"), + "Cells · Cross-platform, membrane": ("cells", "raw", "membrane", "crossplatform"), + "Cells · Tonsil (not used)": ("cells", "raw", "markers", "tonsil"), + "Nuclei · Tonsil (not used)": ("nuclei", "all", "markers", "tonsil"), +} +SELECTION_COLORS = {"all": "#2a78d6", "markers": "#eb6834", "membrane": "#1baf7a"} # validated, light +PAIR = ["flow_threshold", "cellprob_threshold"] + + +def block(summary: pd.DataFrame, target, scope, selection, dataset, clip=0.0) -> pd.DataFrame: + s = summary + m = (s["target"] == target) & (s["scope"] == scope) & (s["cell_channels"] == selection) + return s[m & (s["dataset"] == dataset) & np.isclose(s["clip_limit"], clip)] + + +def threshold_table(summary: pd.DataFrame) -> pd.DataFrame: + """Long table: key, flow, cellprob, mean F1 for the four key results at CLAHE off.""" + parts = [block(summary, *spec).assign(key=key) for key, spec in KEYS.items()] + return pd.concat(parts)[["key", *PAIR, "mean_f1"]] + + +def pick(table: pd.DataFrame) -> dict: + """The pair with the smallest worst shortfall from each key's best; see the module docstring.""" + wide = table.pivot_table(index=PAIR, columns="key", values="mean_f1") + complete = wide.dropna() + missing = [[float(f), float(p)] for f, p in wide.index.difference(complete.index)] + best_f1 = complete.max() + shortfall = best_f1 - complete + order = pd.DataFrame({"worst": shortfall.max(axis=1), "mean": complete.mean(axis=1)}) + chosen = order.sort_values(["worst", "mean"], ascending=[True, False]).index[0] + return { + "pair": [_num(chosen[0]), _num(chosen[1])], + "worst_shortfall": float(order.loc[chosen, "worst"]), + "f1": {k: float(complete.loc[chosen, k]) for k in complete.columns}, + "shortfall": {k: float(shortfall.loc[chosen, k]) for k in complete.columns}, + "best": { + k: {"pair": [_num(v) for v in complete[k].idxmax()], "f1": float(best_f1[k])} + for k in complete.columns + }, + "missing_pairs": [[_num(f), _num(p)] for f, p in missing], + } + + +def _num(x) -> float | int: + return int(x) if float(x).is_integer() else float(x) + + +def channel_table(df: pd.DataFrame, pair: list) -> pd.DataFrame: + """Mean cells F1 per channel selection and group (Vectra, CODEX, Tonsil) at `pair`, CLAHE off.""" + m = (df["target"] == "cells") & (df["scope"] == "raw") & np.isclose(df["clip_limit"], 0) + m &= np.isclose(df["flow_threshold"], pair[0]) & np.isclose(df["cellprob_threshold"], pair[1]) + sub = df[m] + out = sub.groupby(["cell_channels", "group"])["f1"].agg(mean_f1="mean", n="count").reset_index() + cp = sub[sub["dataset"] == "crossplatform"].groupby("cell_channels")["f1"].agg(mean_f1="mean", n="count") + return pd.concat([out, cp.reset_index().assign(group="Cross-platform")], ignore_index=True) + + +def clahe_table(summary: pd.DataFrame) -> pd.DataFrame: + """Mean F1 at the CLAHE pairs, clip 0 vs 0.01, per key result and Tonsil.""" + specs = dict( + KEYS, + cells_tonsil=("cells", "raw", "markers", "tonsil"), + nuclei_tonsil=("nuclei", "all", "markers", "tonsil"), + ) + rows = [] + for key, spec in specs.items(): + for clip in (0.0, 0.01): + b = block(summary, *spec, clip=clip).set_index(PAIR)["mean_f1"] + for flow, prob in CLAHE_PAIRS: + rows.append({"key": key, "flow_threshold": flow, "cellprob_threshold": prob, "clip_limit": clip, + "mean_f1": b.get((flow, prob), np.nan)}) # fmt: skip + t = ( + pd.DataFrame(rows) + .pivot_table(index=["key", *PAIR], columns="clip_limit", values="mean_f1") + .reset_index() + ) + t.columns = ["key", *PAIR, "f1_clahe_off", "f1_clahe_001"] + return t.assign(difference=t["f1_clahe_001"] - t["f1_clahe_off"]) + + +def anchors(summary: pd.DataFrame, round1: Path) -> pd.DataFrame: + """Round-1 rows that round 2 repeats exactly (same preprocessing and thresholds): mean F1 side by side.""" + r1 = summarise(load(round1, build_settings())).merge(build_settings(), on=["index", "target", "scope"]) + same = {"projection_method": "max", "low_percentile": 1, "projection_sigma": 0, "gaussian_sigma": 0} + rows = [] + for target, scope in [("cells", "raw"), ("cells", "tissuenet")]: + a = r1[(r1["target"] == target) & (r1["scope"] == scope) & np.isclose(r1["clip_limit"], 0)] + # TissueNet ignores the projection factors (run.prepare_input); only the Gaussian matters. + for k, v in (same if scope == "raw" else {"gaussian_sigma": 0}).items(): + a = a[a[k] == v] + for _, r in a.iterrows(): + b = block(summary, target, scope, "all" if scope == "raw" else "markers", r["dataset"]) + b = b[ + np.isclose(b["flow_threshold"], r["flow_threshold"]) + & np.isclose(b["cellprob_threshold"], r["cellprob_threshold"]) + ] + rows.append({"target": target, "dataset": r["dataset"], "flow_threshold": r["flow_threshold"], + "cellprob_threshold": r["cellprob_threshold"], "round1": r["mean_f1"], + "round2": b["mean_f1"].iloc[0] if len(b) else np.nan}) # fmt: skip + t = pd.DataFrame(rows) + return t.assign(difference=t["round2"] - t["round1"]) + + +def plot_heatmaps(summary: pd.DataFrame, chosen: list, out: Path) -> None: + import matplotlib.pyplot as plt + from matplotlib.colors import LinearSegmentedColormap + from matplotlib.patches import Rectangle + + cmap = LinearSegmentedColormap.from_list("blue", ["#eaf1fb", "#2a78d6", "#0e3a73"]) + fig, axes = plt.subplots(2, 4, figsize=(26, 13), constrained_layout=True) + for ax, (title, spec) in zip(axes.flat, PANELS.items(), strict=True): + grid = block(summary, *spec).pivot_table( + index="flow_threshold", columns="cellprob_threshold", values="mean_f1" + ) + ax.grid(False) + ax.set_title(title, fontsize=16) + if grid.empty: + ax.text(0.5, 0.5, "no results", ha="center", va="center", transform=ax.transAxes) + continue + ax.imshow(grid.values, cmap=cmap, aspect="auto") + ax.set_xticks(range(grid.shape[1]), [_fmt(c) for c in grid.columns], fontsize=12) + ax.set_yticks(range(grid.shape[0]), [_fmt(r) for r in grid.index], fontsize=12) + ax.set_xlabel("cellprob_threshold", fontsize=13) + ax.set_ylabel("flow_threshold", fontsize=13) + lo, hi = np.nanmin(grid.values), np.nanmax(grid.values) + for (i, j), v in np.ndenumerate(grid.values): + dark = hi > lo and (v - lo) / (hi - lo) > 0.55 + ax.text(j, i, "" if np.isnan(v) else f"{v:.2f}", ha="center", va="center", fontsize=11, + color="white" if dark else INK) # fmt: skip + bi, bj = np.unravel_index(np.nanargmax(grid.values), grid.shape) + ax.add_patch(Rectangle((bj - 0.5, bi - 0.5), 1, 1, fill=False, ec=INK_2, lw=2, ls="--")) + if chosen[0] in grid.index and chosen[1] in grid.columns: + ci, cj = grid.index.get_loc(chosen[0]), grid.columns.get_loc(chosen[1]) + ax.add_patch(Rectangle((cj - 0.5, ci - 0.5), 1, 1, fill=False, ec=INK, lw=3.5)) + fig.suptitle( + f"Mean F1 (IoU 0.5) by threshold pair. Solid box: pick {chosen}; dashed: panel's best", fontsize=18 + ) + fig.savefig(out / "heatmaps.png", dpi=150) + plt.close(fig) + + +def _fmt(x) -> str: + return f"{x:g}" + + +def plot_channels(table: pd.DataFrame, chosen: list, out: Path) -> None: + import matplotlib.pyplot as plt + + groups = [g for g in ["Cross-platform", "Vectra", "CODEX", "Tonsil"] if g in set(table["group"])] + fig, ax = plt.subplots(figsize=(12, 6.5), constrained_layout=True) + width = 0.26 + for k, (sel, color) in enumerate(SELECTION_COLORS.items()): + t = table[table["cell_channels"] == sel].set_index("group").reindex(groups) + x = np.arange(len(groups)) + (k - 1) * (width + 0.02) + ax.bar(x, t["mean_f1"], width, color=color, label=sel) + for xi, v in zip(x, t["mean_f1"], strict=True): + if not np.isnan(v): + ax.text(xi, v + 0.01, f"{v:.2f}", ha="center", va="bottom", fontsize=12, color=INK) + ax.set_xticks(range(len(groups)), groups) + ax.set_ylim(0, 1) + ax.set_ylabel("Mean cells F1 (IoU 0.5)") + ax.grid(axis="x", visible=False) + ax.legend(title="Cell channels", loc="upper left", ncols=3) + ax.set_title(f"Cell channel selection at thresholds {chosen}, CLAHE off") + fig.savefig(out / "channels.png", dpi=150) + plt.close(fig) + + +def plot_clahe(table: pd.DataFrame, out: Path) -> None: + import matplotlib.pyplot as plt + + keys = list(dict.fromkeys(table["key"])) + fig, ax = plt.subplots(figsize=(12, 6.5), constrained_layout=True) + for i, key in enumerate(keys): + d = table[table["key"] == key]["difference"].dropna() + jitter = np.linspace(-0.15, 0.15, len(d)) if len(d) > 1 else [0] + ax.scatter(np.full(len(d), i) + jitter, d, s=70, color="#a9a8a1", zorder=3) + if len(d): + ax.scatter([i], [d.mean()], s=180, color=INK, zorder=4) + ax.axhline(0, color=INK_2, lw=1.5) + ax.set_xticks(range(len(keys)), [k.replace("_", "\n") for k in keys], fontsize=13) + ax.set_ylabel("F1 with CLAHE 0.01 minus CLAHE off") + ax.grid(axis="x", visible=False) + ax.set_title("CLAHE 0.01 at 9 threshold pairs (grey) and their mean (black)") + fig.savefig(out / "clahe.png", dpi=150) + plt.close(fig) + + +def build_report(results: Path, out: Path, round1: Path | None = None) -> dict: + out.mkdir(parents=True, exist_ok=True) + settings = build_round2() + df = load(results, settings) + summary = summarise(df).merge(settings, on=["index", "target", "scope"]) + missing = sorted(set(settings["index"]) - set(summary["index"])) + if missing: + print(f"WARNING: {len(missing)} settings have no results: {missing}", file=sys.stderr) + summary.to_csv(out / "summary_round2.csv", index=False) + chosen = pick(threshold_table(summary)) + chosen["missing_settings"] = missing + (out / "pick.json").write_text(json.dumps(chosen, indent=2)) + channels = channel_table(df, chosen["pair"]) + channels.to_csv(out / "channels.csv", index=False) + clahe = clahe_table(summary) + clahe.to_csv(out / "clahe.csv", index=False) + if round1 is not None: + anchors(summary, round1).to_csv(out / "anchors.csv", index=False) + _style() + plot_heatmaps(summary, chosen["pair"], out) + plot_channels(channels, chosen["pair"], out) + plot_clahe(clahe, out) + return chosen + + +def main() -> None: + p = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + p.add_argument("--results", type=Path, required=True, help="round-2 results/ directory") + p.add_argument("--out", type=Path, required=True) + p.add_argument("--round1", type=Path, help="round-1 results/, to check the repeated settings") + a = p.parse_args() + chosen = build_report(a.results, a.out, a.round1) + print(json.dumps({k: chosen[k] for k in ("pair", "worst_shortfall", "f1", "best")}, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/tools/segmentation_benchmark/run.py b/tools/segmentation_benchmark/run.py new file mode 100755 index 0000000..41593e2 --- /dev/null +++ b/tools/segmentation_benchmark/run.py @@ -0,0 +1,160 @@ +#!/usr/bin/env python3 +"""Run one benchmark setting (one SLURM array task) over its crops and write results/N.csv. + +Cells on raw datasets: project -> sopa preprocessing -> Cellpose on [cell, nuclear]. +TissueNet: rescale only. Nuclei: the nuclear plane alone. A target is scored on crops that +have its mask file; an all-zero mask is a real "no objects" crop. +""" + +from __future__ import annotations + +import argparse +import sys +import time +from pathlib import Path + +import numpy as np +import pandas as pd +import tifffile + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from segmentation_benchmark.preprocess import cell_channels, pad_to, project, sopa_preprocess, unpad # noqa: E402 +from segmentation_benchmark.scoring import score # noqa: E402 +from segmentation_benchmark.settings import GRIDS # noqa: E402 + +SCOPES = { + "raw": ["crossplatform", "tonsil"], + "tissuenet": ["tissuenet"], + "all": ["crossplatform", "tonsil", "tissuenet"], +} +_models: dict = {} + + +def segment(image: np.ndarray, _channels: list[str], setting: pd.Series, gpu: bool) -> np.ndarray: + """Cellpose-SAM, loaded once per task; sopa's callable reloads the model per call, this mirrors its eval.""" + if gpu not in _models: + import warnings + + from sopa.segmentation.methods._cellpose import load_cellpose_model + + warnings.filterwarnings("ignore", message="You are using `torch.load` with `weights_only=False`") + _models[gpu] = load_cellpose_model( + model_type="cyto3", pretrained_model="cpsam_v2", gpu=gpu, cellpose_model_kwargs=None + ) + mask, *_ = _models[gpu].eval( + image, + diameter=30, + channels=None, # cellpose 4 ignores channel names, as in sopa + flow_threshold=float(setting["flow_threshold"]), + cellprob_threshold=float(setting["cellprob_threshold"]), + ) + return np.asarray(mask) + + +def prepare_input(image: np.ndarray, crop: pd.Series, setting: pd.Series) -> tuple[np.ndarray, list[str]]: + """Preprocessed (C, Y, X) and the channel names to segment.""" + nuclear = int(crop["nuclear"]) + if crop["dataset"] == "tissuenet": # its projection factors do not vary + projected = project(image, nuclear, "max", 1, 0) + else: + names = str(crop["channels"]).split("|") + projected = project( + image, + nuclear, + setting["projection_method"], + setting["low_percentile"], + setting["projection_sigma"], + cell_idx=cell_channels(names, nuclear, setting["cell_channels"]), + ) + if setting["target"] == "nuclei": + projected, channels = projected[1:2], ["nuclear"] + else: + channels = ["cell", "nuclear"] + return sopa_preprocess(projected, setting["gaussian_sigma"], setting["clip_limit"]), channels + + +def run( + data: Path, + index: int, + out: Path, + gpu: bool = False, + limit_crops: int | None = None, + dataset: str | None = None, + grid: str = "round1", +) -> None: + partial = bool(limit_crops or dataset) # partial runs must never look complete + final = out / "results" / (f"{index}.partial.csv" if partial else f"{index}.csv") + if not partial and final.exists(): + print(f"setting {index}: {final} exists, skipping", flush=True) + return + setting = GRIDS[grid]().set_index("index").loc[index] + crops = pd.read_csv(data / "crops.csv", dtype={"crop": str}) + crops = crops[crops["dataset"].isin(SCOPES[setting["scope"]])] + if dataset: + crops = crops[crops["dataset"] == dataset] + mask_name = f"{setting['target']}.tif" + has_mask = [ + (data / "crops" / d / c / mask_name).exists() + for d, c in zip(crops["dataset"], crops["crop"], strict=False) + ] + crops = crops[has_mask] + if limit_crops: + crops = crops.head(limit_crops) + if crops.empty: + raise SystemExit( + f"setting {index}: no crops for scope {setting['scope']!r} and target {setting['target']!r} in {data}" + ) + + rows, start = [], time.time() + for _, crop in crops.iterrows(): + t0 = time.time() + folder = data / "crops" / crop["dataset"] / crop["crop"] + image, truth = tifffile.imread(folder / "image.tif"), tifffile.imread(folder / mask_name) + prepared, channels = prepare_input(image, crop, setting) + padded, shape = pad_to(prepared) + labels = unpad(segment(padded, channels, setting, gpu), shape) + seconds = time.time() - t0 + s = score(truth, labels) + rows.append( + { + "index": index, + "target": setting["target"], + "dataset": crop["dataset"], + "crop": crop["crop"], + "platform": crop["platform"], + **s, + "seconds": round(seconds, 2), + } + ) + if crop["montage"]: + label_dir = out / "labels" / str(index) + label_dir.mkdir(parents=True, exist_ok=True) + tifffile.imwrite(label_dir / f"{crop['dataset']}__{crop['crop']}.tif", labels.astype(np.uint32)) + print(f"{crop['dataset']} {crop['crop']} f1={s['f1']:.3f} {seconds:.1f}s", flush=True) + + final.parent.mkdir(parents=True, exist_ok=True) + tmp = final.with_name(final.name + ".tmp") + pd.DataFrame(rows).to_csv(tmp, index=False) + tmp.replace(final) # atomic on POSIX + mean_f1 = np.nanmean([r["f1"] for r in rows]) if rows else float("nan") + print( + f"setting {index}: {len(rows)} crops, mean f1={mean_f1:.3f}, {time.time() - start:.0f}s", flush=True + ) + + +def main() -> None: + p = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + p.add_argument("--data", type=Path, required=True) + p.add_argument("--setting-index", type=int, required=True) + p.add_argument("--out", type=Path, required=True) + p.add_argument("--gpu", action="store_true") + p.add_argument("--limit-crops", type=int) + p.add_argument("--dataset", choices=["crossplatform", "tonsil", "tissuenet"]) + p.add_argument("--grid", choices=GRIDS, default="round1") + a = p.parse_args() + run(a.data, a.setting_index, a.out, a.gpu, a.limit_crops, a.dataset, a.grid) + + +if __name__ == "__main__": + main() diff --git a/tools/segmentation_benchmark/run_array.sbatch b/tools/segmentation_benchmark/run_array.sbatch new file mode 100755 index 0000000..300009c --- /dev/null +++ b/tools/segmentation_benchmark/run_array.sbatch @@ -0,0 +1,22 @@ +#!/bin/bash +#SBATCH --job-name=seg-bench +#SBATCH --array=0-167%8 +# Set the partition for your cluster, then uncomment: --partition= +##SBATCH --partition= +#SBATCH --gres=gpu:a40:1 +#SBATCH --constraint=ceph +#SBATCH --cpus-per-task=8 +#SBATCH --mem=32G +#SBATCH --time=04:00:00 # generous; tighten after the timing job +#SBATCH --output=logs/%A_%a.out +# Submit from a directory where logs/ exists. Needs SIF, DATA, OUT and REPO in the environment. +set -euo pipefail + +: "${SIF:?set SIF to the sopa 2.3.0 .sif image}" +: "${DATA:?set DATA to the prepared data directory}" +: "${OUT:?set OUT to the results directory}" +: "${REPO:?set REPO to the repository root (sbatch copies this script)}" + +apptainer exec --nv --bind "$DATA" --bind "$OUT" --bind "$REPO" "$SIF" \ + python "$REPO/tools/segmentation_benchmark/run.py" \ + --data "$DATA" --setting-index "$SLURM_ARRAY_TASK_ID" --out "$OUT" --gpu "$@" diff --git a/tools/segmentation_benchmark/scoring.py b/tools/segmentation_benchmark/scoring.py new file mode 100644 index 0000000..6bdf30a --- /dev/null +++ b/tools/segmentation_benchmark/scoring.py @@ -0,0 +1,57 @@ +"""Score predicted instance masks against ground truth by IoU matching. + +Labels are integer instance masks (0 = background); ids need not be sequential or equal +between the two masks. Counts follow cellpose: a pair matches at IoU >= threshold, and +ap = tp / (tp + fp + fn) per threshold. Only overlapping pairs are built, so memory scales +with the number of objects, not with n_true * n_pred. +""" + +from __future__ import annotations + +import numpy as np + +IOU_THRESHOLDS = (0.5, 0.6, 0.7, 0.8, 0.9) +PRIMARY_THRESHOLD = 0.5 + + +def score(true: np.ndarray, pred: np.ndarray) -> dict: + """Object counts, F1 at 0.5, and average precision at each IoU threshold.""" + true = np.asarray(true) + pred = np.asarray(pred) + ids_t, area_t = np.unique(true[true > 0], return_counts=True) + ids_p, area_p = np.unique(pred[pred > 0], return_counts=True) + both = (true > 0) & (pred > 0) + pairs, inter = np.unique(np.stack([true[both], pred[both]], axis=1), axis=0, return_counts=True) + iou = inter / ( + area_t[np.searchsorted(ids_t, pairs[:, 0])] + area_p[np.searchsorted(ids_p, pairs[:, 1])] - inter + ) + n_true, n_pred = len(ids_t), len(ids_p) + order = np.argsort(-iou, kind="stable") + pairs_sorted, iou_sorted = pairs[order].tolist(), iou[order].tolist() + + def counts(threshold: float) -> tuple[int, int, int]: + # One-to-one, greedy by IoU: ties at exactly 0.5 match once. + used_t, used_p, tp = set(), set(), 0 + for (t_id, p_id), value in zip(pairs_sorted, iou_sorted, strict=False): + if value < threshold: + break + if t_id in used_t or p_id in used_p: + continue + used_t.add(t_id) + used_p.add(p_id) + tp += 1 + return tp, n_pred - tp, n_true - tp + + out = {"n_true": n_true, "n_pred": n_pred} + for threshold in IOU_THRESHOLDS: + tp, fp, fn = counts(threshold) + if threshold == PRIMARY_THRESHOLD: + out.update(tp=tp, fp=fp, fn=fn, f1=_ratio(2 * tp, 2 * tp + fp + fn)) + out[f"ap_{round(threshold * 100)}"] = _ratio(tp, tp + fp + fn) + out["mean_ap"] = float(np.mean([out[f"ap_{round(t * 100)}"] for t in IOU_THRESHOLDS])) + return out + + +def _ratio(num: int, den: int) -> float: + """num / den as float, NaN when the denominator is 0 (nothing to score).""" + return num / den if den else float("nan") diff --git a/tools/segmentation_benchmark/settings.csv b/tools/segmentation_benchmark/settings.csv new file mode 100644 index 0000000..34df8ad --- /dev/null +++ b/tools/segmentation_benchmark/settings.csv @@ -0,0 +1,169 @@ +index,target,scope,cell_channels,projection_method,low_percentile,projection_sigma,gaussian_sigma,clip_limit,flow_threshold,cellprob_threshold +0,cells,raw,all,max,1,0,0,0.0,2.0,-6 +1,cells,raw,all,max,1,0,0,0.0,0.4,0 +2,cells,raw,all,max,1,0,0,0.2,2.0,-6 +3,cells,raw,all,max,1,0,0,0.2,0.4,0 +4,cells,raw,all,max,1,0,1,0.0,2.0,-6 +5,cells,raw,all,max,1,0,1,0.0,0.4,0 +6,cells,raw,all,max,1,0,1,0.2,2.0,-6 +7,cells,raw,all,max,1,0,1,0.2,0.4,0 +8,cells,raw,all,max,1,0,2,0.0,2.0,-6 +9,cells,raw,all,max,1,0,2,0.0,0.4,0 +10,cells,raw,all,max,1,0,2,0.2,2.0,-6 +11,cells,raw,all,max,1,0,2,0.2,0.4,0 +12,cells,raw,all,max,1,1,0,0.0,2.0,-6 +13,cells,raw,all,max,1,1,0,0.0,0.4,0 +14,cells,raw,all,max,1,1,0,0.2,2.0,-6 +15,cells,raw,all,max,1,1,0,0.2,0.4,0 +16,cells,raw,all,max,1,1,1,0.0,2.0,-6 +17,cells,raw,all,max,1,1,1,0.0,0.4,0 +18,cells,raw,all,max,1,1,1,0.2,2.0,-6 +19,cells,raw,all,max,1,1,1,0.2,0.4,0 +20,cells,raw,all,max,1,1,2,0.0,2.0,-6 +21,cells,raw,all,max,1,1,2,0.0,0.4,0 +22,cells,raw,all,max,1,1,2,0.2,2.0,-6 +23,cells,raw,all,max,1,1,2,0.2,0.4,0 +24,cells,raw,all,max,1,2,0,0.0,2.0,-6 +25,cells,raw,all,max,1,2,0,0.0,0.4,0 +26,cells,raw,all,max,1,2,0,0.2,2.0,-6 +27,cells,raw,all,max,1,2,0,0.2,0.4,0 +28,cells,raw,all,max,1,2,1,0.0,2.0,-6 +29,cells,raw,all,max,1,2,1,0.0,0.4,0 +30,cells,raw,all,max,1,2,1,0.2,2.0,-6 +31,cells,raw,all,max,1,2,1,0.2,0.4,0 +32,cells,raw,all,max,1,2,2,0.0,2.0,-6 +33,cells,raw,all,max,1,2,2,0.0,0.4,0 +34,cells,raw,all,max,1,2,2,0.2,2.0,-6 +35,cells,raw,all,max,1,2,2,0.2,0.4,0 +36,cells,raw,all,max,50,0,0,0.0,2.0,-6 +37,cells,raw,all,max,50,0,0,0.0,0.4,0 +38,cells,raw,all,max,50,0,0,0.2,2.0,-6 +39,cells,raw,all,max,50,0,0,0.2,0.4,0 +40,cells,raw,all,max,50,0,1,0.0,2.0,-6 +41,cells,raw,all,max,50,0,1,0.0,0.4,0 +42,cells,raw,all,max,50,0,1,0.2,2.0,-6 +43,cells,raw,all,max,50,0,1,0.2,0.4,0 +44,cells,raw,all,max,50,0,2,0.0,2.0,-6 +45,cells,raw,all,max,50,0,2,0.0,0.4,0 +46,cells,raw,all,max,50,0,2,0.2,2.0,-6 +47,cells,raw,all,max,50,0,2,0.2,0.4,0 +48,cells,raw,all,max,50,1,0,0.0,2.0,-6 +49,cells,raw,all,max,50,1,0,0.0,0.4,0 +50,cells,raw,all,max,50,1,0,0.2,2.0,-6 +51,cells,raw,all,max,50,1,0,0.2,0.4,0 +52,cells,raw,all,max,50,1,1,0.0,2.0,-6 +53,cells,raw,all,max,50,1,1,0.0,0.4,0 +54,cells,raw,all,max,50,1,1,0.2,2.0,-6 +55,cells,raw,all,max,50,1,1,0.2,0.4,0 +56,cells,raw,all,max,50,1,2,0.0,2.0,-6 +57,cells,raw,all,max,50,1,2,0.0,0.4,0 +58,cells,raw,all,max,50,1,2,0.2,2.0,-6 +59,cells,raw,all,max,50,1,2,0.2,0.4,0 +60,cells,raw,all,max,50,2,0,0.0,2.0,-6 +61,cells,raw,all,max,50,2,0,0.0,0.4,0 +62,cells,raw,all,max,50,2,0,0.2,2.0,-6 +63,cells,raw,all,max,50,2,0,0.2,0.4,0 +64,cells,raw,all,max,50,2,1,0.0,2.0,-6 +65,cells,raw,all,max,50,2,1,0.0,0.4,0 +66,cells,raw,all,max,50,2,1,0.2,2.0,-6 +67,cells,raw,all,max,50,2,1,0.2,0.4,0 +68,cells,raw,all,max,50,2,2,0.0,2.0,-6 +69,cells,raw,all,max,50,2,2,0.0,0.4,0 +70,cells,raw,all,max,50,2,2,0.2,2.0,-6 +71,cells,raw,all,max,50,2,2,0.2,0.4,0 +72,cells,raw,all,mean,1,0,0,0.0,2.0,-6 +73,cells,raw,all,mean,1,0,0,0.0,0.4,0 +74,cells,raw,all,mean,1,0,0,0.2,2.0,-6 +75,cells,raw,all,mean,1,0,0,0.2,0.4,0 +76,cells,raw,all,mean,1,0,1,0.0,2.0,-6 +77,cells,raw,all,mean,1,0,1,0.0,0.4,0 +78,cells,raw,all,mean,1,0,1,0.2,2.0,-6 +79,cells,raw,all,mean,1,0,1,0.2,0.4,0 +80,cells,raw,all,mean,1,0,2,0.0,2.0,-6 +81,cells,raw,all,mean,1,0,2,0.0,0.4,0 +82,cells,raw,all,mean,1,0,2,0.2,2.0,-6 +83,cells,raw,all,mean,1,0,2,0.2,0.4,0 +84,cells,raw,all,mean,1,1,0,0.0,2.0,-6 +85,cells,raw,all,mean,1,1,0,0.0,0.4,0 +86,cells,raw,all,mean,1,1,0,0.2,2.0,-6 +87,cells,raw,all,mean,1,1,0,0.2,0.4,0 +88,cells,raw,all,mean,1,1,1,0.0,2.0,-6 +89,cells,raw,all,mean,1,1,1,0.0,0.4,0 +90,cells,raw,all,mean,1,1,1,0.2,2.0,-6 +91,cells,raw,all,mean,1,1,1,0.2,0.4,0 +92,cells,raw,all,mean,1,1,2,0.0,2.0,-6 +93,cells,raw,all,mean,1,1,2,0.0,0.4,0 +94,cells,raw,all,mean,1,1,2,0.2,2.0,-6 +95,cells,raw,all,mean,1,1,2,0.2,0.4,0 +96,cells,raw,all,mean,1,2,0,0.0,2.0,-6 +97,cells,raw,all,mean,1,2,0,0.0,0.4,0 +98,cells,raw,all,mean,1,2,0,0.2,2.0,-6 +99,cells,raw,all,mean,1,2,0,0.2,0.4,0 +100,cells,raw,all,mean,1,2,1,0.0,2.0,-6 +101,cells,raw,all,mean,1,2,1,0.0,0.4,0 +102,cells,raw,all,mean,1,2,1,0.2,2.0,-6 +103,cells,raw,all,mean,1,2,1,0.2,0.4,0 +104,cells,raw,all,mean,1,2,2,0.0,2.0,-6 +105,cells,raw,all,mean,1,2,2,0.0,0.4,0 +106,cells,raw,all,mean,1,2,2,0.2,2.0,-6 +107,cells,raw,all,mean,1,2,2,0.2,0.4,0 +108,cells,raw,all,mean,50,0,0,0.0,2.0,-6 +109,cells,raw,all,mean,50,0,0,0.0,0.4,0 +110,cells,raw,all,mean,50,0,0,0.2,2.0,-6 +111,cells,raw,all,mean,50,0,0,0.2,0.4,0 +112,cells,raw,all,mean,50,0,1,0.0,2.0,-6 +113,cells,raw,all,mean,50,0,1,0.0,0.4,0 +114,cells,raw,all,mean,50,0,1,0.2,2.0,-6 +115,cells,raw,all,mean,50,0,1,0.2,0.4,0 +116,cells,raw,all,mean,50,0,2,0.0,2.0,-6 +117,cells,raw,all,mean,50,0,2,0.0,0.4,0 +118,cells,raw,all,mean,50,0,2,0.2,2.0,-6 +119,cells,raw,all,mean,50,0,2,0.2,0.4,0 +120,cells,raw,all,mean,50,1,0,0.0,2.0,-6 +121,cells,raw,all,mean,50,1,0,0.0,0.4,0 +122,cells,raw,all,mean,50,1,0,0.2,2.0,-6 +123,cells,raw,all,mean,50,1,0,0.2,0.4,0 +124,cells,raw,all,mean,50,1,1,0.0,2.0,-6 +125,cells,raw,all,mean,50,1,1,0.0,0.4,0 +126,cells,raw,all,mean,50,1,1,0.2,2.0,-6 +127,cells,raw,all,mean,50,1,1,0.2,0.4,0 +128,cells,raw,all,mean,50,1,2,0.0,2.0,-6 +129,cells,raw,all,mean,50,1,2,0.0,0.4,0 +130,cells,raw,all,mean,50,1,2,0.2,2.0,-6 +131,cells,raw,all,mean,50,1,2,0.2,0.4,0 +132,cells,raw,all,mean,50,2,0,0.0,2.0,-6 +133,cells,raw,all,mean,50,2,0,0.0,0.4,0 +134,cells,raw,all,mean,50,2,0,0.2,2.0,-6 +135,cells,raw,all,mean,50,2,0,0.2,0.4,0 +136,cells,raw,all,mean,50,2,1,0.0,2.0,-6 +137,cells,raw,all,mean,50,2,1,0.0,0.4,0 +138,cells,raw,all,mean,50,2,1,0.2,2.0,-6 +139,cells,raw,all,mean,50,2,1,0.2,0.4,0 +140,cells,raw,all,mean,50,2,2,0.0,2.0,-6 +141,cells,raw,all,mean,50,2,2,0.0,0.4,0 +142,cells,raw,all,mean,50,2,2,0.2,2.0,-6 +143,cells,raw,all,mean,50,2,2,0.2,0.4,0 +144,cells,tissuenet,all,max,1,1,0,0.0,2.0,-6 +145,cells,tissuenet,all,max,1,1,0,0.0,0.4,0 +146,cells,tissuenet,all,max,1,1,0,0.2,2.0,-6 +147,cells,tissuenet,all,max,1,1,0,0.2,0.4,0 +148,cells,tissuenet,all,max,1,1,1,0.0,2.0,-6 +149,cells,tissuenet,all,max,1,1,1,0.0,0.4,0 +150,cells,tissuenet,all,max,1,1,1,0.2,2.0,-6 +151,cells,tissuenet,all,max,1,1,1,0.2,0.4,0 +152,cells,tissuenet,all,max,1,1,2,0.0,2.0,-6 +153,cells,tissuenet,all,max,1,1,2,0.0,0.4,0 +154,cells,tissuenet,all,max,1,1,2,0.2,2.0,-6 +155,cells,tissuenet,all,max,1,1,2,0.2,0.4,0 +156,nuclei,all,all,max,1,1,0,0.0,2.0,-6 +157,nuclei,all,all,max,1,1,0,0.0,0.4,0 +158,nuclei,all,all,max,1,1,0,0.2,2.0,-6 +159,nuclei,all,all,max,1,1,0,0.2,0.4,0 +160,nuclei,all,all,max,1,1,1,0.0,2.0,-6 +161,nuclei,all,all,max,1,1,1,0.0,0.4,0 +162,nuclei,all,all,max,1,1,1,0.2,2.0,-6 +163,nuclei,all,all,max,1,1,1,0.2,0.4,0 +164,nuclei,all,all,max,1,1,2,0.0,2.0,-6 +165,nuclei,all,all,max,1,1,2,0.0,0.4,0 +166,nuclei,all,all,max,1,1,2,0.2,2.0,-6 +167,nuclei,all,all,max,1,1,2,0.2,0.4,0 diff --git a/tools/segmentation_benchmark/settings.py b/tools/segmentation_benchmark/settings.py new file mode 100755 index 0000000..24160f7 --- /dev/null +++ b/tools/segmentation_benchmark/settings.py @@ -0,0 +1,126 @@ +#!/usr/bin/env python3 +"""Settings grid for the segmentation benchmark: one row per SLURM array task. + +Round 1 (settings.csv): rows 0-143 vary the channel projection and Cellpose thresholds on +raw-channel datasets; 144-155 vary Cellpose on TissueNet and 156-167 on nuclei, both with +TODAY's projection. +Round 2 (settings_round2.csv): round 1's best preprocessing (no smoothing, no CLAHE), a +7 x 8 threshold grid per block, three cell channel selections, and CLAHE 0.01 at 9 pairs. +Regenerate: python settings.py --grid round1 --out settings.csv (round2: settings_round2.csv) +""" + +from __future__ import annotations + +import argparse +import itertools +from pathlib import Path + +import pandas as pd + +TODAY = { + "projection_method": "max", + "low_percentile": 1, + "projection_sigma": 1, + "gaussian_sigma": 1, + "clip_limit": 0.2, + "flow_threshold": 2, + "cellprob_threshold": -6, +} + +GAUSSIAN_LEVELS = [0, 1, 2] +CLIP_LEVELS = [0, 0.2] +THRESHOLD_LEVELS = [(2, -6), (0.4, 0)] # (flow_threshold, cellprob_threshold) pairs + +ROUND2_BASE = {"projection_method": "max", "low_percentile": 1, "projection_sigma": 0, "gaussian_sigma": 0} +FLOW_LEVELS = [0.2, 0.4, 0.6, 0.8, 1.0, 1.5, 2.0] +CELLPROB_LEVELS = [-6, -4, -3, -2, -1, 0, 1, 2] +CLAHE_PAIRS = list(itertools.product([0.4, 1.0, 2.0], [-6, -2, 0])) +BLOCKS = [("cells", "raw"), ("cells", "tissuenet"), ("nuclei", "all")] +COLUMNS = [ + "target", + "scope", + "cell_channels", + "projection_method", + "low_percentile", + "projection_sigma", + "gaussian_sigma", + "clip_limit", + "flow_threshold", + "cellprob_threshold", +] + + +def build_settings() -> pd.DataFrame: + """The 168-row grid; the `index` column is the SLURM array task id.""" + rows = [ + ("cells", "raw", "all", method, low, p_sigma, g_sigma, clip, flow, prob) + for method, low, p_sigma, g_sigma, clip, (flow, prob) in itertools.product( + ["max", "mean"], [1, 50], [0, 1, 2], GAUSSIAN_LEVELS, CLIP_LEVELS, THRESHOLD_LEVELS + ) + ] + for target, scope in [("cells", "tissuenet"), ("nuclei", "all")]: + rows += [ + ( + target, + scope, + "all", + TODAY["projection_method"], + TODAY["low_percentile"], + TODAY["projection_sigma"], + g_sigma, + clip, + flow, + prob, + ) + for g_sigma, clip, (flow, prob) in itertools.product( + GAUSSIAN_LEVELS, CLIP_LEVELS, THRESHOLD_LEVELS + ) + ] + return _frame(rows) + + +def build_round2() -> pd.DataFrame: + """The 307-row round-2 grid: thresholds on round 1's best preprocessing.""" + pairs = list(itertools.product(FLOW_LEVELS, CELLPROB_LEVELS)) + blocks = [("cells", "raw", sel, 0.0, pairs) for sel in ("markers", "all", "membrane")] + blocks += [("cells", "tissuenet", "markers", 0.0, pairs), ("nuclei", "all", "markers", 0.0, pairs)] + blocks += [(t, sc, "markers", 0.01, CLAHE_PAIRS) for t, sc in BLOCKS] + base = ROUND2_BASE + rows = [ + (t, sc, sel, base["projection_method"], base["low_percentile"], base["projection_sigma"], + base["gaussian_sigma"], clip, flow, prob) + for t, sc, sel, clip, block_pairs in blocks + for flow, prob in block_pairs + ] # fmt: skip + return _frame(rows) + + +def _frame(rows: list[tuple]) -> pd.DataFrame: + df = pd.DataFrame(rows, columns=COLUMNS) + df.insert(0, "index", range(len(df))) + return df + + +GRIDS = {"round1": build_settings, "round2": build_round2} + + +def today_index(settings: pd.DataFrame, target: str, scope: str) -> int: + """Array index of the TODAY row within one (target, scope) block.""" + match = settings[(settings["target"] == target) & (settings["scope"] == scope)] + for key, value in TODAY.items(): + match = match[match[key] == value] + if len(match) != 1: + raise ValueError(f"TODAY must occur exactly once in block {target}/{scope}, found {len(match)}") + return int(match["index"].iloc[0]) + + +def main() -> None: + parser = argparse.ArgumentParser(description="Write the benchmark settings grid as CSV.") + parser.add_argument("--grid", choices=GRIDS, default="round1") + parser.add_argument("--out", type=Path, required=True) + args = parser.parse_args() + GRIDS[args.grid]().to_csv(args.out, index=False) + + +if __name__ == "__main__": + main() diff --git a/tools/segmentation_benchmark/settings_round2.csv b/tools/segmentation_benchmark/settings_round2.csv new file mode 100644 index 0000000..d625ac6 --- /dev/null +++ b/tools/segmentation_benchmark/settings_round2.csv @@ -0,0 +1,308 @@ +index,target,scope,cell_channels,projection_method,low_percentile,projection_sigma,gaussian_sigma,clip_limit,flow_threshold,cellprob_threshold +0,cells,raw,markers,max,1,0,0,0.0,0.2,-6 +1,cells,raw,markers,max,1,0,0,0.0,0.2,-4 +2,cells,raw,markers,max,1,0,0,0.0,0.2,-3 +3,cells,raw,markers,max,1,0,0,0.0,0.2,-2 +4,cells,raw,markers,max,1,0,0,0.0,0.2,-1 +5,cells,raw,markers,max,1,0,0,0.0,0.2,0 +6,cells,raw,markers,max,1,0,0,0.0,0.2,1 +7,cells,raw,markers,max,1,0,0,0.0,0.2,2 +8,cells,raw,markers,max,1,0,0,0.0,0.4,-6 +9,cells,raw,markers,max,1,0,0,0.0,0.4,-4 +10,cells,raw,markers,max,1,0,0,0.0,0.4,-3 +11,cells,raw,markers,max,1,0,0,0.0,0.4,-2 +12,cells,raw,markers,max,1,0,0,0.0,0.4,-1 +13,cells,raw,markers,max,1,0,0,0.0,0.4,0 +14,cells,raw,markers,max,1,0,0,0.0,0.4,1 +15,cells,raw,markers,max,1,0,0,0.0,0.4,2 +16,cells,raw,markers,max,1,0,0,0.0,0.6,-6 +17,cells,raw,markers,max,1,0,0,0.0,0.6,-4 +18,cells,raw,markers,max,1,0,0,0.0,0.6,-3 +19,cells,raw,markers,max,1,0,0,0.0,0.6,-2 +20,cells,raw,markers,max,1,0,0,0.0,0.6,-1 +21,cells,raw,markers,max,1,0,0,0.0,0.6,0 +22,cells,raw,markers,max,1,0,0,0.0,0.6,1 +23,cells,raw,markers,max,1,0,0,0.0,0.6,2 +24,cells,raw,markers,max,1,0,0,0.0,0.8,-6 +25,cells,raw,markers,max,1,0,0,0.0,0.8,-4 +26,cells,raw,markers,max,1,0,0,0.0,0.8,-3 +27,cells,raw,markers,max,1,0,0,0.0,0.8,-2 +28,cells,raw,markers,max,1,0,0,0.0,0.8,-1 +29,cells,raw,markers,max,1,0,0,0.0,0.8,0 +30,cells,raw,markers,max,1,0,0,0.0,0.8,1 +31,cells,raw,markers,max,1,0,0,0.0,0.8,2 +32,cells,raw,markers,max,1,0,0,0.0,1.0,-6 +33,cells,raw,markers,max,1,0,0,0.0,1.0,-4 +34,cells,raw,markers,max,1,0,0,0.0,1.0,-3 +35,cells,raw,markers,max,1,0,0,0.0,1.0,-2 +36,cells,raw,markers,max,1,0,0,0.0,1.0,-1 +37,cells,raw,markers,max,1,0,0,0.0,1.0,0 +38,cells,raw,markers,max,1,0,0,0.0,1.0,1 +39,cells,raw,markers,max,1,0,0,0.0,1.0,2 +40,cells,raw,markers,max,1,0,0,0.0,1.5,-6 +41,cells,raw,markers,max,1,0,0,0.0,1.5,-4 +42,cells,raw,markers,max,1,0,0,0.0,1.5,-3 +43,cells,raw,markers,max,1,0,0,0.0,1.5,-2 +44,cells,raw,markers,max,1,0,0,0.0,1.5,-1 +45,cells,raw,markers,max,1,0,0,0.0,1.5,0 +46,cells,raw,markers,max,1,0,0,0.0,1.5,1 +47,cells,raw,markers,max,1,0,0,0.0,1.5,2 +48,cells,raw,markers,max,1,0,0,0.0,2.0,-6 +49,cells,raw,markers,max,1,0,0,0.0,2.0,-4 +50,cells,raw,markers,max,1,0,0,0.0,2.0,-3 +51,cells,raw,markers,max,1,0,0,0.0,2.0,-2 +52,cells,raw,markers,max,1,0,0,0.0,2.0,-1 +53,cells,raw,markers,max,1,0,0,0.0,2.0,0 +54,cells,raw,markers,max,1,0,0,0.0,2.0,1 +55,cells,raw,markers,max,1,0,0,0.0,2.0,2 +56,cells,raw,all,max,1,0,0,0.0,0.2,-6 +57,cells,raw,all,max,1,0,0,0.0,0.2,-4 +58,cells,raw,all,max,1,0,0,0.0,0.2,-3 +59,cells,raw,all,max,1,0,0,0.0,0.2,-2 +60,cells,raw,all,max,1,0,0,0.0,0.2,-1 +61,cells,raw,all,max,1,0,0,0.0,0.2,0 +62,cells,raw,all,max,1,0,0,0.0,0.2,1 +63,cells,raw,all,max,1,0,0,0.0,0.2,2 +64,cells,raw,all,max,1,0,0,0.0,0.4,-6 +65,cells,raw,all,max,1,0,0,0.0,0.4,-4 +66,cells,raw,all,max,1,0,0,0.0,0.4,-3 +67,cells,raw,all,max,1,0,0,0.0,0.4,-2 +68,cells,raw,all,max,1,0,0,0.0,0.4,-1 +69,cells,raw,all,max,1,0,0,0.0,0.4,0 +70,cells,raw,all,max,1,0,0,0.0,0.4,1 +71,cells,raw,all,max,1,0,0,0.0,0.4,2 +72,cells,raw,all,max,1,0,0,0.0,0.6,-6 +73,cells,raw,all,max,1,0,0,0.0,0.6,-4 +74,cells,raw,all,max,1,0,0,0.0,0.6,-3 +75,cells,raw,all,max,1,0,0,0.0,0.6,-2 +76,cells,raw,all,max,1,0,0,0.0,0.6,-1 +77,cells,raw,all,max,1,0,0,0.0,0.6,0 +78,cells,raw,all,max,1,0,0,0.0,0.6,1 +79,cells,raw,all,max,1,0,0,0.0,0.6,2 +80,cells,raw,all,max,1,0,0,0.0,0.8,-6 +81,cells,raw,all,max,1,0,0,0.0,0.8,-4 +82,cells,raw,all,max,1,0,0,0.0,0.8,-3 +83,cells,raw,all,max,1,0,0,0.0,0.8,-2 +84,cells,raw,all,max,1,0,0,0.0,0.8,-1 +85,cells,raw,all,max,1,0,0,0.0,0.8,0 +86,cells,raw,all,max,1,0,0,0.0,0.8,1 +87,cells,raw,all,max,1,0,0,0.0,0.8,2 +88,cells,raw,all,max,1,0,0,0.0,1.0,-6 +89,cells,raw,all,max,1,0,0,0.0,1.0,-4 +90,cells,raw,all,max,1,0,0,0.0,1.0,-3 +91,cells,raw,all,max,1,0,0,0.0,1.0,-2 +92,cells,raw,all,max,1,0,0,0.0,1.0,-1 +93,cells,raw,all,max,1,0,0,0.0,1.0,0 +94,cells,raw,all,max,1,0,0,0.0,1.0,1 +95,cells,raw,all,max,1,0,0,0.0,1.0,2 +96,cells,raw,all,max,1,0,0,0.0,1.5,-6 +97,cells,raw,all,max,1,0,0,0.0,1.5,-4 +98,cells,raw,all,max,1,0,0,0.0,1.5,-3 +99,cells,raw,all,max,1,0,0,0.0,1.5,-2 +100,cells,raw,all,max,1,0,0,0.0,1.5,-1 +101,cells,raw,all,max,1,0,0,0.0,1.5,0 +102,cells,raw,all,max,1,0,0,0.0,1.5,1 +103,cells,raw,all,max,1,0,0,0.0,1.5,2 +104,cells,raw,all,max,1,0,0,0.0,2.0,-6 +105,cells,raw,all,max,1,0,0,0.0,2.0,-4 +106,cells,raw,all,max,1,0,0,0.0,2.0,-3 +107,cells,raw,all,max,1,0,0,0.0,2.0,-2 +108,cells,raw,all,max,1,0,0,0.0,2.0,-1 +109,cells,raw,all,max,1,0,0,0.0,2.0,0 +110,cells,raw,all,max,1,0,0,0.0,2.0,1 +111,cells,raw,all,max,1,0,0,0.0,2.0,2 +112,cells,raw,membrane,max,1,0,0,0.0,0.2,-6 +113,cells,raw,membrane,max,1,0,0,0.0,0.2,-4 +114,cells,raw,membrane,max,1,0,0,0.0,0.2,-3 +115,cells,raw,membrane,max,1,0,0,0.0,0.2,-2 +116,cells,raw,membrane,max,1,0,0,0.0,0.2,-1 +117,cells,raw,membrane,max,1,0,0,0.0,0.2,0 +118,cells,raw,membrane,max,1,0,0,0.0,0.2,1 +119,cells,raw,membrane,max,1,0,0,0.0,0.2,2 +120,cells,raw,membrane,max,1,0,0,0.0,0.4,-6 +121,cells,raw,membrane,max,1,0,0,0.0,0.4,-4 +122,cells,raw,membrane,max,1,0,0,0.0,0.4,-3 +123,cells,raw,membrane,max,1,0,0,0.0,0.4,-2 +124,cells,raw,membrane,max,1,0,0,0.0,0.4,-1 +125,cells,raw,membrane,max,1,0,0,0.0,0.4,0 +126,cells,raw,membrane,max,1,0,0,0.0,0.4,1 +127,cells,raw,membrane,max,1,0,0,0.0,0.4,2 +128,cells,raw,membrane,max,1,0,0,0.0,0.6,-6 +129,cells,raw,membrane,max,1,0,0,0.0,0.6,-4 +130,cells,raw,membrane,max,1,0,0,0.0,0.6,-3 +131,cells,raw,membrane,max,1,0,0,0.0,0.6,-2 +132,cells,raw,membrane,max,1,0,0,0.0,0.6,-1 +133,cells,raw,membrane,max,1,0,0,0.0,0.6,0 +134,cells,raw,membrane,max,1,0,0,0.0,0.6,1 +135,cells,raw,membrane,max,1,0,0,0.0,0.6,2 +136,cells,raw,membrane,max,1,0,0,0.0,0.8,-6 +137,cells,raw,membrane,max,1,0,0,0.0,0.8,-4 +138,cells,raw,membrane,max,1,0,0,0.0,0.8,-3 +139,cells,raw,membrane,max,1,0,0,0.0,0.8,-2 +140,cells,raw,membrane,max,1,0,0,0.0,0.8,-1 +141,cells,raw,membrane,max,1,0,0,0.0,0.8,0 +142,cells,raw,membrane,max,1,0,0,0.0,0.8,1 +143,cells,raw,membrane,max,1,0,0,0.0,0.8,2 +144,cells,raw,membrane,max,1,0,0,0.0,1.0,-6 +145,cells,raw,membrane,max,1,0,0,0.0,1.0,-4 +146,cells,raw,membrane,max,1,0,0,0.0,1.0,-3 +147,cells,raw,membrane,max,1,0,0,0.0,1.0,-2 +148,cells,raw,membrane,max,1,0,0,0.0,1.0,-1 +149,cells,raw,membrane,max,1,0,0,0.0,1.0,0 +150,cells,raw,membrane,max,1,0,0,0.0,1.0,1 +151,cells,raw,membrane,max,1,0,0,0.0,1.0,2 +152,cells,raw,membrane,max,1,0,0,0.0,1.5,-6 +153,cells,raw,membrane,max,1,0,0,0.0,1.5,-4 +154,cells,raw,membrane,max,1,0,0,0.0,1.5,-3 +155,cells,raw,membrane,max,1,0,0,0.0,1.5,-2 +156,cells,raw,membrane,max,1,0,0,0.0,1.5,-1 +157,cells,raw,membrane,max,1,0,0,0.0,1.5,0 +158,cells,raw,membrane,max,1,0,0,0.0,1.5,1 +159,cells,raw,membrane,max,1,0,0,0.0,1.5,2 +160,cells,raw,membrane,max,1,0,0,0.0,2.0,-6 +161,cells,raw,membrane,max,1,0,0,0.0,2.0,-4 +162,cells,raw,membrane,max,1,0,0,0.0,2.0,-3 +163,cells,raw,membrane,max,1,0,0,0.0,2.0,-2 +164,cells,raw,membrane,max,1,0,0,0.0,2.0,-1 +165,cells,raw,membrane,max,1,0,0,0.0,2.0,0 +166,cells,raw,membrane,max,1,0,0,0.0,2.0,1 +167,cells,raw,membrane,max,1,0,0,0.0,2.0,2 +168,cells,tissuenet,markers,max,1,0,0,0.0,0.2,-6 +169,cells,tissuenet,markers,max,1,0,0,0.0,0.2,-4 +170,cells,tissuenet,markers,max,1,0,0,0.0,0.2,-3 +171,cells,tissuenet,markers,max,1,0,0,0.0,0.2,-2 +172,cells,tissuenet,markers,max,1,0,0,0.0,0.2,-1 +173,cells,tissuenet,markers,max,1,0,0,0.0,0.2,0 +174,cells,tissuenet,markers,max,1,0,0,0.0,0.2,1 +175,cells,tissuenet,markers,max,1,0,0,0.0,0.2,2 +176,cells,tissuenet,markers,max,1,0,0,0.0,0.4,-6 +177,cells,tissuenet,markers,max,1,0,0,0.0,0.4,-4 +178,cells,tissuenet,markers,max,1,0,0,0.0,0.4,-3 +179,cells,tissuenet,markers,max,1,0,0,0.0,0.4,-2 +180,cells,tissuenet,markers,max,1,0,0,0.0,0.4,-1 +181,cells,tissuenet,markers,max,1,0,0,0.0,0.4,0 +182,cells,tissuenet,markers,max,1,0,0,0.0,0.4,1 +183,cells,tissuenet,markers,max,1,0,0,0.0,0.4,2 +184,cells,tissuenet,markers,max,1,0,0,0.0,0.6,-6 +185,cells,tissuenet,markers,max,1,0,0,0.0,0.6,-4 +186,cells,tissuenet,markers,max,1,0,0,0.0,0.6,-3 +187,cells,tissuenet,markers,max,1,0,0,0.0,0.6,-2 +188,cells,tissuenet,markers,max,1,0,0,0.0,0.6,-1 +189,cells,tissuenet,markers,max,1,0,0,0.0,0.6,0 +190,cells,tissuenet,markers,max,1,0,0,0.0,0.6,1 +191,cells,tissuenet,markers,max,1,0,0,0.0,0.6,2 +192,cells,tissuenet,markers,max,1,0,0,0.0,0.8,-6 +193,cells,tissuenet,markers,max,1,0,0,0.0,0.8,-4 +194,cells,tissuenet,markers,max,1,0,0,0.0,0.8,-3 +195,cells,tissuenet,markers,max,1,0,0,0.0,0.8,-2 +196,cells,tissuenet,markers,max,1,0,0,0.0,0.8,-1 +197,cells,tissuenet,markers,max,1,0,0,0.0,0.8,0 +198,cells,tissuenet,markers,max,1,0,0,0.0,0.8,1 +199,cells,tissuenet,markers,max,1,0,0,0.0,0.8,2 +200,cells,tissuenet,markers,max,1,0,0,0.0,1.0,-6 +201,cells,tissuenet,markers,max,1,0,0,0.0,1.0,-4 +202,cells,tissuenet,markers,max,1,0,0,0.0,1.0,-3 +203,cells,tissuenet,markers,max,1,0,0,0.0,1.0,-2 +204,cells,tissuenet,markers,max,1,0,0,0.0,1.0,-1 +205,cells,tissuenet,markers,max,1,0,0,0.0,1.0,0 +206,cells,tissuenet,markers,max,1,0,0,0.0,1.0,1 +207,cells,tissuenet,markers,max,1,0,0,0.0,1.0,2 +208,cells,tissuenet,markers,max,1,0,0,0.0,1.5,-6 +209,cells,tissuenet,markers,max,1,0,0,0.0,1.5,-4 +210,cells,tissuenet,markers,max,1,0,0,0.0,1.5,-3 +211,cells,tissuenet,markers,max,1,0,0,0.0,1.5,-2 +212,cells,tissuenet,markers,max,1,0,0,0.0,1.5,-1 +213,cells,tissuenet,markers,max,1,0,0,0.0,1.5,0 +214,cells,tissuenet,markers,max,1,0,0,0.0,1.5,1 +215,cells,tissuenet,markers,max,1,0,0,0.0,1.5,2 +216,cells,tissuenet,markers,max,1,0,0,0.0,2.0,-6 +217,cells,tissuenet,markers,max,1,0,0,0.0,2.0,-4 +218,cells,tissuenet,markers,max,1,0,0,0.0,2.0,-3 +219,cells,tissuenet,markers,max,1,0,0,0.0,2.0,-2 +220,cells,tissuenet,markers,max,1,0,0,0.0,2.0,-1 +221,cells,tissuenet,markers,max,1,0,0,0.0,2.0,0 +222,cells,tissuenet,markers,max,1,0,0,0.0,2.0,1 +223,cells,tissuenet,markers,max,1,0,0,0.0,2.0,2 +224,nuclei,all,markers,max,1,0,0,0.0,0.2,-6 +225,nuclei,all,markers,max,1,0,0,0.0,0.2,-4 +226,nuclei,all,markers,max,1,0,0,0.0,0.2,-3 +227,nuclei,all,markers,max,1,0,0,0.0,0.2,-2 +228,nuclei,all,markers,max,1,0,0,0.0,0.2,-1 +229,nuclei,all,markers,max,1,0,0,0.0,0.2,0 +230,nuclei,all,markers,max,1,0,0,0.0,0.2,1 +231,nuclei,all,markers,max,1,0,0,0.0,0.2,2 +232,nuclei,all,markers,max,1,0,0,0.0,0.4,-6 +233,nuclei,all,markers,max,1,0,0,0.0,0.4,-4 +234,nuclei,all,markers,max,1,0,0,0.0,0.4,-3 +235,nuclei,all,markers,max,1,0,0,0.0,0.4,-2 +236,nuclei,all,markers,max,1,0,0,0.0,0.4,-1 +237,nuclei,all,markers,max,1,0,0,0.0,0.4,0 +238,nuclei,all,markers,max,1,0,0,0.0,0.4,1 +239,nuclei,all,markers,max,1,0,0,0.0,0.4,2 +240,nuclei,all,markers,max,1,0,0,0.0,0.6,-6 +241,nuclei,all,markers,max,1,0,0,0.0,0.6,-4 +242,nuclei,all,markers,max,1,0,0,0.0,0.6,-3 +243,nuclei,all,markers,max,1,0,0,0.0,0.6,-2 +244,nuclei,all,markers,max,1,0,0,0.0,0.6,-1 +245,nuclei,all,markers,max,1,0,0,0.0,0.6,0 +246,nuclei,all,markers,max,1,0,0,0.0,0.6,1 +247,nuclei,all,markers,max,1,0,0,0.0,0.6,2 +248,nuclei,all,markers,max,1,0,0,0.0,0.8,-6 +249,nuclei,all,markers,max,1,0,0,0.0,0.8,-4 +250,nuclei,all,markers,max,1,0,0,0.0,0.8,-3 +251,nuclei,all,markers,max,1,0,0,0.0,0.8,-2 +252,nuclei,all,markers,max,1,0,0,0.0,0.8,-1 +253,nuclei,all,markers,max,1,0,0,0.0,0.8,0 +254,nuclei,all,markers,max,1,0,0,0.0,0.8,1 +255,nuclei,all,markers,max,1,0,0,0.0,0.8,2 +256,nuclei,all,markers,max,1,0,0,0.0,1.0,-6 +257,nuclei,all,markers,max,1,0,0,0.0,1.0,-4 +258,nuclei,all,markers,max,1,0,0,0.0,1.0,-3 +259,nuclei,all,markers,max,1,0,0,0.0,1.0,-2 +260,nuclei,all,markers,max,1,0,0,0.0,1.0,-1 +261,nuclei,all,markers,max,1,0,0,0.0,1.0,0 +262,nuclei,all,markers,max,1,0,0,0.0,1.0,1 +263,nuclei,all,markers,max,1,0,0,0.0,1.0,2 +264,nuclei,all,markers,max,1,0,0,0.0,1.5,-6 +265,nuclei,all,markers,max,1,0,0,0.0,1.5,-4 +266,nuclei,all,markers,max,1,0,0,0.0,1.5,-3 +267,nuclei,all,markers,max,1,0,0,0.0,1.5,-2 +268,nuclei,all,markers,max,1,0,0,0.0,1.5,-1 +269,nuclei,all,markers,max,1,0,0,0.0,1.5,0 +270,nuclei,all,markers,max,1,0,0,0.0,1.5,1 +271,nuclei,all,markers,max,1,0,0,0.0,1.5,2 +272,nuclei,all,markers,max,1,0,0,0.0,2.0,-6 +273,nuclei,all,markers,max,1,0,0,0.0,2.0,-4 +274,nuclei,all,markers,max,1,0,0,0.0,2.0,-3 +275,nuclei,all,markers,max,1,0,0,0.0,2.0,-2 +276,nuclei,all,markers,max,1,0,0,0.0,2.0,-1 +277,nuclei,all,markers,max,1,0,0,0.0,2.0,0 +278,nuclei,all,markers,max,1,0,0,0.0,2.0,1 +279,nuclei,all,markers,max,1,0,0,0.0,2.0,2 +280,cells,raw,markers,max,1,0,0,0.01,0.4,-6 +281,cells,raw,markers,max,1,0,0,0.01,0.4,-2 +282,cells,raw,markers,max,1,0,0,0.01,0.4,0 +283,cells,raw,markers,max,1,0,0,0.01,1.0,-6 +284,cells,raw,markers,max,1,0,0,0.01,1.0,-2 +285,cells,raw,markers,max,1,0,0,0.01,1.0,0 +286,cells,raw,markers,max,1,0,0,0.01,2.0,-6 +287,cells,raw,markers,max,1,0,0,0.01,2.0,-2 +288,cells,raw,markers,max,1,0,0,0.01,2.0,0 +289,cells,tissuenet,markers,max,1,0,0,0.01,0.4,-6 +290,cells,tissuenet,markers,max,1,0,0,0.01,0.4,-2 +291,cells,tissuenet,markers,max,1,0,0,0.01,0.4,0 +292,cells,tissuenet,markers,max,1,0,0,0.01,1.0,-6 +293,cells,tissuenet,markers,max,1,0,0,0.01,1.0,-2 +294,cells,tissuenet,markers,max,1,0,0,0.01,1.0,0 +295,cells,tissuenet,markers,max,1,0,0,0.01,2.0,-6 +296,cells,tissuenet,markers,max,1,0,0,0.01,2.0,-2 +297,cells,tissuenet,markers,max,1,0,0,0.01,2.0,0 +298,nuclei,all,markers,max,1,0,0,0.01,0.4,-6 +299,nuclei,all,markers,max,1,0,0,0.01,0.4,-2 +300,nuclei,all,markers,max,1,0,0,0.01,0.4,0 +301,nuclei,all,markers,max,1,0,0,0.01,1.0,-6 +302,nuclei,all,markers,max,1,0,0,0.01,1.0,-2 +303,nuclei,all,markers,max,1,0,0,0.01,1.0,0 +304,nuclei,all,markers,max,1,0,0,0.01,2.0,-6 +305,nuclei,all,markers,max,1,0,0,0.01,2.0,-2 +306,nuclei,all,markers,max,1,0,0,0.01,2.0,0 diff --git a/tools/site_reference.py b/tools/site_reference.py index d63dd7f..4a0f8a8 100755 --- a/tools/site_reference.py +++ b/tools/site_reference.py @@ -41,6 +41,8 @@ ], "cellpose": ["modules/local/segment_patch"], "instanseg": ["modules/local/segment_patch"], + "nimbus": ["modules/local/nimbus"], + "virtues": ["modules/local/virtues"], "projection": ["modules/local/project_channels"], "linking": ["modules/local/link_compartments"], "quantification": ["modules/local/aggregate"], @@ -68,6 +70,11 @@ "doi": "10.48550/arXiv.2408.15954", "package": "instanseg", }, + "nimbus": { + "name": "Nimbus", + "homepage": "https://github.com/angelolab/Nimbus-Inference", + "doi": "10.1038/s41592-025-02826-9", + }, "qc-report": {"name": "pipeline scripts (`bin/`)"}, } diff --git a/tools/virtues_parity.py b/tools/virtues_parity.py new file mode 100755 index 0000000..95d9ed3 --- /dev/null +++ b/tools/virtues_parity.py @@ -0,0 +1,189 @@ +#!/usr/bin/env python3 +"""Parity of our VirTues runner with upstream on the bundled example core; run in the virtues image on a GPU. + +Upstream runs as notebook 2_demo_cell_phenotyping (spora-io standardiser with the blur, 120 px pad, +compute_cell_tokens) at chunk_size 32 and 8. Ours runs cell_embeddings on the same raw image, mask and +statistics (through a virtues_stats.json), with the bundled marker embeddings, so only the runner is +compared; our ESM-2 embeddings of the same IDs are compared with the bundled ones separately. +--cpu-only stops before the model (no FlashAttention on CPU): input and ESM-2 only. + +Usage: virtues_parity.py OUT.json [--cpu-only] +""" + +import argparse +import json +import os +import sys +import tempfile +from pathlib import Path + +import numpy as np + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "bin")) +import virtues_cells as vc # noqa: E402 +import virtues_stats as vs # noqa: E402 + +TISSUE_ID = "cords2024cancer_ocmzljpb_0001" # the bundled example core + + +def compare(a, b): + """Per-row cosine (min, median) and max abs difference of two (n, D) arrays.""" + a, b = np.asarray(a, dtype=np.float64), np.asarray(b, dtype=np.float64) + cos = (a * b).sum(1) / (np.linalg.norm(a, axis=1) * np.linalg.norm(b, axis=1)) + return { + "n": len(a), + "cosine_min": float(cos.min()), + "cosine_median": float(np.median(cos)), + "max_abs_diff": float(np.abs(a - b).max()), + } + + +def upstream_inputs(src): + """Notebook 2 up to the standardised input: dataset, tissue, padded mask, x, channel metadata.""" + import torch + from omegaconf import OmegaConf + from spora_io import MultiplexImagingDataset + + conf = OmegaConf.load(f"{src}/configs/base_config.yaml") + c = OmegaConf.load(f"{src}/configs/datasets/example_config.yaml")["datasets"]["example_dataset"] + ds = MultiplexImagingDataset( + name=c.name, + path=str(Path(src) / c.path), + modality=c.modality, + standardization=c.standardization, + resolution=c.resolution, + tile_size=conf.data.tile_size, + disable_quantile_mask=True, + filter_list=["gaussian_blur"], + use_mean_std=True, + ) + t = ds.get_tissue(tissue_id=TISSUE_ID, kind="uniprot_filtered", preprocess=False) + pad = (vc.PAD,) * 4 + x = torch.nn.functional.pad(t.image, pad=pad, mode="constant", value=0) + mask = torch.nn.functional.pad( + ds.get_cell_instance_mask(TISSUE_ID).mask, pad=pad, mode="constant", value=0 + ) + x, refined = ds.standardizer.apply(x, TISSUE_ID, t.measured_mask, t.image_loading_mask) + _, names, ids = ds._refine_channel_metadata(t.image_loading_mask, t.channel_names, t.uniprot_ids, refined) + # notebook 2 indexes markers with the unrefined IDs, so its recipe holds only if nothing was dropped + if list(ids) != list(t.uniprot_ids) or x.shape[0] != len(ids): + sys.exit(f"standardiser dropped channels: {list(t.uniprot_ids)} -> {list(ids)}") + stats = [ + s.flatten().numpy() for s in ds.standardizer._get_cached_stats(TISSUE_ID, t.measured_mask, refined) + ] + return t, mask, x, list(names), list(ids), stats + + +def our_source(mask): + """CellSource from a padded instance mask: compact labels 1..n, centroids and boxes from its pixels.""" + ids = np.unique(mask) + ids = ids[ids > 0] + labels = np.where(mask > 0, np.searchsorted(ids, mask) + 1, 0).astype(np.int32) + ys, xs = np.nonzero(labels) + lab = labels[ys, xs] - 1 + n = len(ids) + count = np.bincount(lab, minlength=n) + centroids = np.stack([np.bincount(lab, ys, n) / count, np.bincount(lab, xs, n) / count], axis=1) + bboxes = np.zeros((n, 4), dtype=np.int64) + bboxes[:, 0], bboxes[:, 2] = ys.max() + 1, xs.max() + 1 + np.minimum.at(bboxes[:, 0], lab, ys) + np.maximum.at(bboxes[:, 1], lab, ys + 1) + np.minimum.at(bboxes[:, 2], lab, xs) + np.maximum.at(bboxes[:, 3], lab, xs + 1) + return ids, vc.CellSource(lambda y0, y1, x0, x1: labels[y0:y1, x0:x1], centroids, bboxes) + + +def main(argv=None): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("output", help="JSON report") + ap.add_argument("--cpu-only", action="store_true", help="input and ESM-2 only, no model") + args = ap.parse_args(argv) + import torch + from virtues.utils.utils import load_marker_embedding_dict, load_marker_embeddings + + src = os.environ["VIRTUES_SRC"] + emb_dir = f"{src}/assets/example_dataset/marker_embeddings" + device = "cpu" if args.cpu_only else "cuda" + report = { + "tissue_id": TISSUE_ID, + "virtues_commit": os.environ.get("VIRTUES_COMMIT", "unknown"), + "torch": torch.__version__, + "gpu": None if args.cpu_only else torch.cuda.get_device_name(0), + } + + t, mask, x, names, ids, (upper, lower, mean, std) = upstream_inputs(src) + if np.any(lower != 0): + sys.exit(f"upstream lower quantiles are not 0 ({lower}); our runner clips only from above") + raw = t.image.numpy() + report.update(n_channels=len(ids), padded_shape=list(mask.shape), raw_min=float(raw.min())) + + # the statistics upstream used, through our statistics file format and loader + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / f"{TISSUE_ID}_virtues_stats.json" + markers = { + n: {"uniprot_id": u, "cap": float(c), "mean": float(m), "sd": float(s), "tissue_pixels": 0} + for n, u, c, m, s in zip(names, ids, upper, mean, std, strict=True) + } + path.write_text(json.dumps({"format": vs.STATS_FORMAT, "slide": TISSUE_ID, "markers": markers})) + st = vc.stats_arrays(vs.load_stats(path, list(zip(names, ids, strict=True))), names) + padded = tuple(mask.shape) + + def read_raw(c, y0, y1, x0, x1): + # upstream clamps from below at its lower quantile, 0 + return np.maximum(vs.resample_window(raw, c, y0, y1, x0, x1, 1.0), 0) + + def read_input(y0, y1, x0, x1): + return vc.model_input(read_raw, st, y0, y1, x0, x1, padded) + + report["input_max_abs_diff"] = float(np.abs(read_input(0, padded[0], 0, padded[1]) - x.numpy()).max()) + + bundled = load_marker_embeddings(emb_dir) + emb_dict = load_marker_embedding_dict(emb_dir) + midxs = torch.tensor([emb_dict[u] for u in ids], dtype=torch.long) + # ruling R4: UniProt changed some sequences since the bundled embeddings, so report ESM-2 alone + seqs = vc.uniprot_sequences(os.environ["VIRTUES_UNIPROT"], sorted(set(ids))) + ours_esm = vc.esm_embeddings([seqs[u] for u in ids], device) + diff = (ours_esm - bundled[midxs]).abs().amax(dim=1).numpy() + report["esm_max_abs_diff"] = float(diff.max()) + report["esm_markers_over_1e-5"] = {u: float(d) for u, d in zip(ids, diff, strict=True) if d > 1e-5} + + if not args.cpu_only: + from safetensors.torch import load_file + from virtues.modules.multiplex_virtues import MultiplexVirtues + from virtues.utils.cell_tokens import compute_cell_tokens + + weights = os.environ["VIRTUES_WEIGHTS"] + up_model = MultiplexVirtues(prior_bias_embeddings=bundled) # notebook 2, cells 4 and 6 + up_model.load_state_dict(load_file(weights, device="cuda")) + up_model = up_model.cuda().eval() + up = {} + for chunk in (32, 8): + cell_ids, tokens, _, _ = compute_cell_tokens(up_model, x, midxs, mask, chunk_size=chunk) + up[chunk] = (cell_ids.numpy(), tokens.float().numpy()) + if not np.array_equal(up[32][0], up[8][0]): + sys.exit("upstream's cells differ between chunk sizes") + del up_model + + cell_ids, source = our_source(mask.numpy()) + if not np.array_equal(cell_ids, up[32][0]): + sys.exit("upstream's cells differ from the mask's labels") + encode = vc.virtues_encoder(vc.build_model(weights, bundled[midxs], device), len(ids), device) + ours = {} + for run, tile, batch in [("b32", vc.TILE, 32), ("b8", vc.TILE, 8), ("t512", 512, 32)]: + out = vc.cell_embeddings(read_input, {"cells": source}, padded, encode, tile=tile, batch=batch) + ours[run] = out["cells"][0] + report.update( + n_cells=len(cell_ids), + upstream_chunk32_vs_chunk8=compare(up[32][1], up[8][1]), + ours_vs_upstream=compare(ours["b32"], up[32][1]), + ours_batch32_vs_batch8=compare(ours["b32"], ours["b8"]), + ours_tile512_vs_tile2048=compare(ours["t512"], ours["b32"]), + ) + + Path(args.output).write_text(json.dumps(report, indent=2) + "\n") + print(json.dumps(report, indent=2)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/uv.lock b/uv.lock index b755455..3ff485c 100644 --- a/uv.lock +++ b/uv.lock @@ -728,6 +728,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/0c/d5/c5db1ea3394c6e1732fb3286b3bd878b59507a8f77d32a2cebda7d7b7cd4/donfig-0.8.1.post1-py3-none-any.whl", hash = "sha256:2a3175ce74a06109ff9307d90a230f81215cbac9a751f4d1c6194644b8204f9d", size = 21592, upload-time = "2024-05-23T14:13:55.283Z" }, ] +[[package]] +name = "et-xmlfile" +version = "2.0.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d3/38/af70d7ab1ae9d4da450eeec1fa3918940a5fafb9055e934af8d6eb0c2313/et_xmlfile-2.0.0.tar.gz", hash = "sha256:dab3f4764309081ce75662649be815c4c9081e88f0837825f90fd28317d4da54", size = 17234, upload-time = "2024-10-25T17:25:40.039Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c1/8b/5fe2cc11fee489817272089c4203e679c63b570a5aaeb18d852ae3cbba6a/et_xmlfile-2.0.0-py3-none-any.whl", hash = "sha256:7a91720bc756843502c3b7504c77b8fe44217c85c537d85037f0f536151b2caa", size = 18059, upload-time = "2024-10-25T17:25:39.051Z" }, +] + [[package]] name = "fonttools" version = "4.68.0" @@ -946,10 +955,13 @@ dev = [ { name = "matplotlib" }, { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, { name = "numpy", version = "2.5.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, + { name = "openpyxl" }, { name = "pandas" }, { name = "pyarrow" }, { name = "pytest" }, { name = "pyyaml" }, + { name = "roifile", version = "2026.2.10", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, + { name = "roifile", version = "2026.11.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, { name = "scikit-image" }, { name = "spatialdata", version = "0.7.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, { name = "spatialdata", version = "0.8.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, @@ -966,10 +978,12 @@ dev = [ { name = "imagecodecs", specifier = ">=2024.1" }, { name = "matplotlib", specifier = ">=3.8" }, { name = "numpy", specifier = ">=1.26" }, + { name = "openpyxl", specifier = ">=3.1" }, { name = "pandas", specifier = ">=2" }, { name = "pyarrow", specifier = ">=15" }, { name = "pytest", specifier = ">=8" }, { name = "pyyaml", specifier = ">=6" }, + { name = "roifile", specifier = ">=2026.2.10" }, { name = "scikit-image", specifier = ">=0.22" }, { name = "spatialdata", specifier = ">=0.4" }, { name = "tifffile", specifier = ">=2024.1" }, @@ -1757,6 +1771,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/2d/70/9ab676f57fe2cb5457db80dd0cc4648b02cbe777d47f159e357391a1e00a/ome_zarr_models-1.8.1-py3-none-any.whl", hash = "sha256:8231b4f2ceae70992c0b3bbf0e7405016eb14998aaf1546d83c9ff87c0349638", size = 75524, upload-time = "2026-09-02T10:25:42.456Z" }, ] +[[package]] +name = "openpyxl" +version = "3.1.5" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "et-xmlfile" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/3d/f9/88d94a75de065ea32619465d2f77b29a0469500e99012523b91cc4141cd1/openpyxl-3.1.5.tar.gz", hash = "sha256:cf0e3cf56142039133628b5acffe8ef0c12bc902d2aadd3e0fe5878dc08d1050", size = 186464, upload-time = "2024-06-28T14:03:44.161Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c0/da/977ded879c29cbd04de313843e76868e6e13408a94ed6b987245dc7c8506/openpyxl-3.1.5-py2.py3-none-any.whl", hash = "sha256:5282c12b107bffeef825f4617dc029afaf41d0ea60823bbb665ef3079dc79de2", size = 250910, upload-time = "2024-06-28T14:03:41.161Z" }, +] + [[package]] name = "packaging" version = "26.3" @@ -2403,6 +2429,41 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/82/3b/64d4899d73f91ba49a8c18a8ff3f0ea8f1c1d75481760df8c68ef5235bf5/rich-15.0.0-py3-none-any.whl", hash = "sha256:33bd4ef74232fb73fe9279a257718407f169c09b78a87ad3d296f548e27de0bb", size = 310654, upload-time = "2026-04-12T08:24:02.83Z" }, ] +[[package]] +name = "roifile" +version = "2026.2.10" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version > '3.11' and python_full_version < '3.12' and sys_platform == 'win32'", + "python_full_version <= '3.11' and sys_platform == 'win32'", + "python_full_version < '3.12' and sys_platform == 'emscripten'", + "python_full_version < '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +dependencies = [ + { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" } }, +] +sdist = { url = "https://files.pythonhosted.org/packages/59/cf/49d9a139e292415d669dccd0c283d99a4d027b9edbd533d7f56db8ff85e0/roifile-2026.2.10.tar.gz", hash = "sha256:87d2b685b00a4ca15125187727e634ae5c00b902362de302b592f892259f3751", size = 27311, upload-time = "2026-02-11T19:54:35.027Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/34/78/3cc84d58e13234861adf91d2897254cd84d3d4a90534d91c960b672e67d1/roifile-2026.2.10-py3-none-any.whl", hash = "sha256:5928a616b58a8ff1c9f89a0590db3616ccbf069c6692f8ecec2a7349f8bbb6ec", size = 21201, upload-time = "2026-02-11T19:54:34.137Z" }, +] + +[[package]] +name = "roifile" +version = "2026.11.6" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "python_full_version >= '3.12' and sys_platform == 'win32'", + "python_full_version >= '3.12' and sys_platform == 'emscripten'", + "python_full_version >= '3.12' and sys_platform != 'emscripten' and sys_platform != 'win32'", +] +dependencies = [ + { name = "numpy", version = "2.5.2", source = { registry = "https://pypi.org/simple" } }, +] +sdist = { url = "https://files.pythonhosted.org/packages/76/7f/0a1d0768be7a686a7e83648b2bf36d91d33d7910965d3680eaddfc76678b/roifile-2026.11.6.tar.gz", hash = "sha256:ec82880c154ba1548c83b5bbc52db63ca94fcf73d4b601e5aea2e0ec5f1b3208", size = 31890, upload-time = "2026-11-07T00:04:11.457Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/73/60/550b745097cabe1458a844dee81ed21f9a58352ff2b96d40df30d33876c3/roifile-2026.11.6-py3-none-any.whl", hash = "sha256:50f98abfe4bdac14224262648f8a304a6f5a61cede361dfb77de5fe276167845", size = 23813, upload-time = "2026-11-07T00:04:10.218Z" }, +] + [[package]] name = "s3fs" version = "2026.9.0" diff --git a/workflows/histo.nf b/workflows/histo.nf index 34bdc62..4c60ca6 100644 --- a/workflows/histo.nf +++ b/workflows/histo.nf @@ -16,11 +16,12 @@ include { SET_CHANNEL_NAMES } from '../modules/local/set_channel_names' include { PROJECT_CHANNELS } from '../modules/local/project_channels' include { PUBLISH_SPATIALDATA } from '../modules/local/publish_spatialdata' include { SEGMENTATION } from '../subworkflows/local/segmentation' +include { LEARNED_FEATURES } from '../subworkflows/local/learned_features' include { QC } from '../subworkflows/local/qc' include { COMPARE_SEGMENTATIONS } from '../modules/local/compare_segmentations' -include { argsCLI; segmentationSpecs } from '../modules/local/utils' +include { argsCLI; featureSpecs; segmentationSpecs } from '../modules/local/utils' /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ RUN MAIN WORKFLOW @@ -108,26 +109,38 @@ workflow HISTO { ch_segmented = SEGMENTATION.out.sdata ch_versions = ch_versions.mix(SEGMENTATION.out.versions) + // Learned features are written after segmentation and before QC, which reads the store. + def feature_specs = featureSpecs(params) + if (feature_specs) { + LEARNED_FEATURES(ch_segmented, ch_markers, feature_specs, specs*.method.unique()) + ch_featured = LEARNED_FEATURES.out.sdata + ch_versions = ch_versions.mix(LEARNED_FEATURES.out.versions) + } + else { + ch_featured = ch_segmented + } + // Ashlar's QC directory, keyed by its own meta.id (sample, or slide on a TMA). def ch_registration_qc = params.use_preprocessing ? PREPROCESS_IMAGES.out.registration_qc : channel.empty() - // QC needs the aggregated tables. Nothing writes to the store after WRITE_SEGMENTATIONS, + // QC needs the aggregated tables. Nothing writes to the store after the last write, // so QC and the merge can read it concurrently. if (params.use_qc) { + // Same sample keys as the stores, or QC's join on meta misses and drops the before-image. def ch_unsubtracted = params.use_preprocessing - ? PREPROCESS_IMAGES.out.unsubtracted + ? PREPROCESS_IMAGES.out.unsubtracted.map { meta, tif -> [addSampleKeys(meta), tif] } : channel.empty() - QC(ch_segmented, ch_markers, ch_unsubtracted, ch_registration_qc, specs*.method.unique()) + QC(ch_featured, ch_markers, ch_unsubtracted, ch_registration_qc, specs*.method.unique()) ch_versions = ch_versions.mix(QC.out.versions) // A second opinion when both methods segmented cells; reads the written store beside QC. // From the specs, so it follows segmentationTargets' truthiness (a bare flag is "true"). def cell_methods = specs.findAll { spec -> spec.target == 'cells' }*.method as Set if (cell_methods == ['cellpose', 'instanseg'] as Set) { - COMPARE_SEGMENTATIONS(ch_segmented) + COMPARE_SEGMENTATIONS(ch_featured) ch_versions = ch_versions.mix(COMPARE_SEGMENTATIONS.out.versions) } } @@ -135,7 +148,7 @@ workflow HISTO { // TMA cores are merged last so each core is segmented and QCed on its own. // `sample` is set because downstream processes tag on meta.sample. if (params.use_tma_dearray) { - ch_cores_by_slide = ch_segmented + ch_cores_by_slide = ch_featured .map { meta, sdata -> [[id: meta.slide, sample: meta.slide], sdata] } .groupTuple() @@ -169,7 +182,7 @@ workflow HISTO { } } else { - ch_publish = ch_segmented + ch_publish = ch_featured } PUBLISH_SPATIALDATA(ch_publish)