diff --git a/itrialspace/.dockerignore b/itrialspace/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..1462a9301dbe2de81242a9581c7a9fc08d61b83e --- /dev/null +++ b/itrialspace/.dockerignore @@ -0,0 +1,39 @@ +.git +.github +**/__pycache__ +*.py[cod] +*.egg-info +.pytest_cache +.ruff_cache +.ipynb_checkpoints + +# Never copy heavy/host-specific artifacts into the image +models/ +weights/ +logs/ +*.log +*.out +*.err +*_artifacts/ +outputs/ +generated_cts/ +inserted_masks/ +paper_analysis/ +*.pt +*.pth +*.ckpt +*.nii +*.nii.gz +*.parquet + +# Local config & secrets +.env +configs/datasets.yaml +configs/paths.yaml +configs/integration.yaml +configs/mask_inserter.yaml +configs/eval.yaml + +docs/_build/ +.venv/ +venv/ diff --git a/itrialspace/.env b/itrialspace/.env new file mode 100644 index 0000000000000000000000000000000000000000..3bfe0caaa38b73a6689707efe0d263618804dd83 --- /dev/null +++ b/itrialspace/.env @@ -0,0 +1,35 @@ +# iTrialSpace environment — this machine (Duke DRCC). Gitignored; edit freely. +# Read automatically by infra/slurm/env.sh and itrialspace.config.settings. + +# ── Data root (inputs: raw_ct/ masks/ profiles/ meta/) ────────────────────── +ITRIALSPACE_DATA_DIR=/path/to/iTrialSpace + +# ── Output root (generated: manifests/ inserted_masks/ generated_cts/ ...) ── +# Defaults to ITRIALSPACE_DATA_DIR. Uncomment to send all outputs elsewhere: +ITRIALSPACE_OUTPUT_DIR=/path/to/outputs_iTrialSpace + +# ── NoduleMap build artifacts (embeddings, edges, metadata) ───────────────── +# Default would be $ITRIALSPACE_OUTPUT_DIR/nodulemap_artifacts; set explicitly here: +NODULEMAP_ARTIFACTS=/path/to/outputs_iTrialSpace/nodulemap_artifacts + +# ── Conda env used by SLURM scripts ───────────────────────────────────────── +ITRIALSPACE_CONDA_ENV=itrialspace + +# ── Service ports ──────────────────────────────────────────────────────────── +NODULEMAP_PORT=8422 +RETRIEVER_API_PORT=8421 +RETRIEVER_UI_PORT=8501 + +# ── SLURM partitions (Duke DRCC) ──────────────────────────────────────────── +SLURM_PARTITION_GPU=vram48 +SLURM_PARTITION_CPU=defq + +# ── NodMAISI synthesis model weights (Step 3 of the pipeline) ─────────────── +NODMAISI_MODELS_DIR=/path/to/nodmaisi_synth/models + +# ── Optional CADe/CADx external dependencies (see docs) ───────────────────── +# EVAL_WEIGHTS_DIR=/path/to/weights +# EVAL_CONFIGS_DIR=/path/to/configs + +# HuggingFace access token (gitignored; local only). Clear before sharing. +HF_TOKEN= "Put your HuggingFace token here if you want to use HuggingFace APIs for model loading, dataset access, etc. Clear this before sharing!" diff --git a/itrialspace/.env.example b/itrialspace/.env.example new file mode 100644 index 0000000000000000000000000000000000000000..6b379d95af34870b7f8862b086fb26c7ea699c79 --- /dev/null +++ b/itrialspace/.env.example @@ -0,0 +1,51 @@ +# iTrialSpace environment configuration — copy to `.env` and edit for your machine. +# These variables drive ALL path resolution; nothing is hardcoded in code or configs. +# +# cp .env.example .env +# +# `itrialspace.config.settings` reads these (falling back to the defaults shown). + +# ── Data root ──────────────────────────────────────────────────────────────── +# Single base directory holding the unified data layout: +# $ITRIALSPACE_DATA_DIR/{raw_ct,masks,profiles,meta,manifests,...} +# Default: ~/.itrialspace/data +ITRIALSPACE_DATA_DIR=/path/to/iTrialSpace/data + +# Repo root (auto-detected from the installed package if unset). +# ITRIALSPACE_ROOT=/home/you/itrialspace + +# Directory for generated outputs (manifests, inserted masks, synthetic CTs, reports). +# Default: $ITRIALSPACE_DATA_DIR +# ITRIALSPACE_OUTPUT_DIR=/path/to/iTrialSpace/outputs + +# ── Build artifacts ────────────────────────────────────────────────────────── +# Where NoduleMap build artifacts (embeddings, edge graphs, metadata) are written — +# and read back from when serving. Set this to point the server at pre-built artifacts, +# or to choose where `its-nodulemap build/edges` (and rebuild_nodulemap.sub) save them. +# Default: $ITRIALSPACE_OUTPUT_DIR/nodulemap_artifacts +# NODULEMAP_ARTIFACTS=/path/to/iTrialSpace/outputs/nodulemap_artifacts +# NODULEMAP_EXPORTS=/path/to/iTrialSpace/outputs/nodulemap_exports # neighbour/donor exports + +# ── HuggingFace access token (VLM eval: MedGemma is gated; some LLaVA-Med too) ── +# Create one at https://huggingface.co/settings/tokens and accept each gated model's +# license. Read by itrialspace.config.settings.hf_token() and passed to the model +# loaders — NEVER hardcoded in code. Leave blank for public-only models (BiomedCLIP +# needs no token). When sharing this repo, clear this value; each user supplies their +# own. (Both HF_TOKEN and the legacy HUGGING_FACE_HUB_TOKEN are honoured.) +# HF_TOKEN= + +# ── Model weights (NOT bundled — see docs/installation.md) ────────────────── +# NodMAISI synthesis model weights (autoencoder.pt, diffusion_unet.pt, controlnet *.pt) +# NODMAISI_MODELS_DIR=/path/to/nodmaisi/models + +# ── Service ports ──────────────────────────────────────────────────────────── +NODULEMAP_PORT=8422 +RETRIEVER_API_PORT=8421 +RETRIEVER_UI_PORT=8501 + +# ── HPC / SLURM (only used by infra/slurm/*) ──────────────────────────────── +ITRIALSPACE_CONDA_ENV=itrialspace +SLURM_PARTITION_GPU=vram48 +SLURM_PARTITION_CPU=defq +# SLURM_ACCOUNT= +# CONDA_PROFILE=/cm/shared/apps/miniconda/etc/profile.d/conda.sh diff --git a/itrialspace/.gitignore b/itrialspace/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..68823423dbd65296da86e04032856ea5376de789 --- /dev/null +++ b/itrialspace/.gitignore @@ -0,0 +1,79 @@ +# ── Python ────────────────────────────────────────────────────────────────── +__pycache__/ +*.py[cod] +*.egg-info/ +*.egg +.eggs/ +build/ +dist/ +.installed.cfg +.Python +.venv/ +venv/ +env/ + +# ── Caches / tooling ──────────────────────────────────────────────────────── +.pytest_cache/ +.ruff_cache/ +.mypy_cache/ +.ipynb_checkpoints/ +.coverage +htmlcov/ + +# ── Model weights (host externally; see docs/installation.md) ─────────────── +*.pt +*.pth +*.ckpt +*.safetensors +models/ +weights/ +# …but DO track source-code packages named "models" (model *adapters*, not weights). +!src/itrialspace/evaluation/vlm_eval/models/ +!src/itrialspace/evaluation/vlm_eval/models/*.py + +# ── Logs & SLURM output ───────────────────────────────────────────────────── +logs/* +!logs/.gitkeep +*.log +*.out +*.err +slurm-*.out + +# ── Generated data / artifacts (regenerate; not source) ───────────────────── +*_artifacts/ +nodulemap_artifacts/ +nodulemap_exports/ +exports/ +outputs/ +generated_cts/ +inserted_masks/ +manifests/ +paper_analysis/ + +# ── Large medical data (never committed; use ITRIALSPACE_DATA_DIR) ────────── +*.nii +*.nii.gz +*.parquet +*.csv + +# ── Local config & secrets ────────────────────────────────────────────────── +# Path-sensitive configs are shipped as *.example.yaml; the resolved local copies +# (datasets.yaml, paths.yaml, integration.yaml, mask_inserter.yaml, eval.yaml) are +# user-specific and ignored. Non-path configs (trials.yaml, features.yaml) ARE committed. +.env +configs/datasets.yaml +configs/paths.yaml +configs/integration.yaml +configs/mask_inserter.yaml +configs/eval.yaml + +# ── Study / manuscript layer (not part of the public release) ─────────────── +# Paper-specific analysis orchestration + narrative. It *uses* the public engine +# (itrialspace.evaluation.vlm_eval.eval_analysis) but is kept private. +studies/ + +# ── OS / editor ───────────────────────────────────────────────────────────── +.DS_Store +*.swp +.idea/ +.vscode/ diff --git a/itrialspace/.pre-commit-config.yaml b/itrialspace/.pre-commit-config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9c10e59248cec00b22e2f5861cc4147d1d0451b1 --- /dev/null +++ b/itrialspace/.pre-commit-config.yaml @@ -0,0 +1,31 @@ +repos: + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.6.0 + hooks: + - id: trailing-whitespace + - id: end-of-file-fixer + - id: check-yaml + exclude: ^infra/slurm/ # SLURM headers contain non-standard directives + - id: check-added-large-files + args: ["--maxkb=2048"] + - id: check-merge-conflict + - id: mixed-line-ending + + - repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.4.10 + hooks: + - id: ruff + args: ["--fix"] + + - repo: https://github.com/psf/black + rev: 24.4.2 + hooks: + - id: black + + - repo: local + hooks: + - id: check-portability + name: check for hardcoded absolute paths + entry: python tools/check_portability.py + language: system + pass_filenames: false diff --git a/itrialspace/CHANGELOG.md b/itrialspace/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..8e567bf8117638b1b0d182454cea53e6a35845f4 --- /dev/null +++ b/itrialspace/CHANGELOG.md @@ -0,0 +1,34 @@ +# Changelog + +All notable changes to iTrialSpace are documented here. The format is based on +[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres +to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +### Added +- Public-release monorepo layout: single installable `itrialspace` distribution + (`src/` layout) with optional-dependency extras (`imaging`, `web`, `synthesis`, + `vlm`, `eval`, `dev`, `all`). +- Configuration/portability layer (`itrialspace.config.settings`): all paths are + resolved from `ITRIALSPACE_DATA_DIR` and friends — no hardcoded absolute paths. +- Console entry points: `its`, `its-insert`, `its-trials`, `its-nodulemap`, + `its-retriever`. +- Packaging, container, and CI tooling: `pyproject.toml`, `environment.yml`, + `docker/Dockerfile`, GitHub Actions CI, pre-commit, portability guard. +- Consolidated documentation under `docs/`. + +### Changed +- Components re-namespaced under `itrialspace.*` (was top-level `itrialspace_mask_inserter`, + `nodulemap`, `retriever`, `site_trials`, `nodmaisi_synth`, `vlm_evaluation`). +- CADe/CADx evaluation moved to optional `itrialspace.evaluation` extra; external model + dependencies documented rather than bundled. + +### Removed +- Large artifacts excluded from source control (model weights, `paper_analysis/`, logs, + generated outputs) — see `docs/installation.md` and `docs/data.md` for how to obtain them. +- Experimental `agent` (`itrialagent`) orchestration layer — never run or integrated in + the research repo; the pipeline is driven directly via the CLI and SLURM scripts. + +## [0.1.0] — research snapshot +- Original research implementation (pre-public-release). Preserved at the source repo. diff --git a/itrialspace/CODE_OF_CONDUCT.md b/itrialspace/CODE_OF_CONDUCT.md new file mode 100644 index 0000000000000000000000000000000000000000..89307f8e20cd71804142f3fe05b6706bddb8d6e6 --- /dev/null +++ b/itrialspace/CODE_OF_CONDUCT.md @@ -0,0 +1,32 @@ +# Code of Conduct + +## Our Pledge + +We as members, contributors, and maintainers pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body size, +visible or invisible disability, ethnicity, sex characteristics, gender identity and +expression, level of experience, education, socio-economic status, nationality, +personal appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to a positive environment: + +- Demonstrating empathy and kindness toward other people +- Being respectful of differing opinions, viewpoints, and experiences +- Giving and gracefully accepting constructive feedback +- Accepting responsibility and apologizing to those affected by our mistakes + +Unacceptable behavior includes harassment, trolling, insulting or derogatory +comments, public or private harassment, and publishing others' private information +without explicit permission. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported +to the project maintainers. All complaints will be reviewed and investigated promptly +and fairly. + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.1. + +[homepage]: https://www.contributor-covenant.org diff --git a/itrialspace/CONTRIBUTING.md b/itrialspace/CONTRIBUTING.md new file mode 100644 index 0000000000000000000000000000000000000000..c25e7c24c627741b922cbee89b9524131389ab78 --- /dev/null +++ b/itrialspace/CONTRIBUTING.md @@ -0,0 +1,74 @@ +# Contributing to iTrialSpace + +Thanks for your interest in improving iTrialSpace! This guide covers the development +workflow, coding standards, and how to extend the framework. + +## Development setup + +```bash +git clone +cd itrialspace + +# Create the environment (conda recommended for the imaging/ML stack) +conda env create -f environment.yml +conda activate itrialspace + +# Editable install with dev tooling +pip install -e ".[dev]" + +# Configure paths (copy and edit) +cp .env.example .env + +# Install git hooks +pre-commit install +``` + +## Project layout + +The repo is a single installable package under `src/itrialspace/`. See +[docs/architecture.md](docs/architecture.md) for the full component map. + +| Path | Purpose | +|------|---------| +| `src/itrialspace/{core,io,index,query,site}` | Nodule index, querying, trial specs | +| `src/itrialspace/trials` | Trial manifest runner (the 13 modes) | +| `src/itrialspace/mask_inserter` | Voxel-level nodule mask insertion | +| `src/itrialspace/synthesis` | NodMAISI CT synthesis (model weights external) | +| `src/itrialspace/apps/{nodulemap,retriever}` | Interactive web tools | +| `src/itrialspace/evaluation/vlm_eval` | Vision-language model evaluation | +| `src/itrialspace/evaluation/{cade,cadx}` | Optional CADe/CADx eval (external deps) | +| `infra/slurm` | HPC submission scripts (cluster-portable via `env.sh`) | +| `configs/` | Example configs (`*.example.yaml`) | +| `tests/` | Unit tests (run with no external data) | + +## Coding standards + +- **Formatting/linting**: `black` + `ruff` (run automatically via pre-commit). +- **No hardcoded paths**: never write `/home/...` or `/scratch/...` in code, configs, or + scripts. Resolve paths through `itrialspace.config.settings` or env vars. CI enforces this + via `tools/check_portability.py`. +- **NIfTI orientation**: always canonicalize to RAS+ (`nib.as_closest_canonical()`). +- **Determinism**: seed with `42` and derive per-case seeds deterministically. + +## Running checks locally + +```bash +ruff check . && black --check . +pytest -m "not full_volume" # unit tests, no external data +python tools/check_portability.py # no stray absolute paths +pre-commit run --all-files +``` + +## Extending the framework + +- **New dataset**: see [docs/data.md](docs/data.md) and `src/itrialspace/io/adapters/`. +- **New trial mode**: add a factory in `src/itrialspace/site/trial_modes.py` and wire it + into `src/itrialspace/trials/run_trial.py`. +- **New VLM**: add a wrapper in `src/itrialspace/evaluation/vlm_eval/models/`. + +## Pull requests + +1. Branch from `main`. +2. Keep changes focused; update docs and tests. +3. Ensure CI passes (lint + tests + portability gate). +4. Describe the change and link any related issue. diff --git a/itrialspace/LICENSE b/itrialspace/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..f669fe740e05d90c59bd4deaa0a7c29becc6745e --- /dev/null +++ b/itrialspace/LICENSE @@ -0,0 +1,20 @@ +LICENSE — PLACEHOLDER (TO BE CONFIRMED BEFORE PUBLIC RELEASE) +============================================================ + +The license for iTrialSpace has not yet been finalized. + +Until a license is chosen and this file is replaced, all rights are reserved by +the authors. Do not redistribute. + +Recommended options under consideration: + - Apache-2.0 (permissive + explicit patent grant) + - MIT (simplest, most permissive) + - BSD-3-Clause (permissive + non-endorsement clause) + +ACTION REQUIRED: Replace the entire contents of this file with the full text of +the chosen license, update `license` in pyproject.toml and CITATION.cff, and add +SPDX headers if desired. + +Note on data: source CT datasets (DLCS24, LUNA16, LUNA25, LUNGx, LNDb, NSCLC-Radiomics, +etc.) carry their own licenses and are NOT redistributed by this repository. See +docs/data.md. diff --git a/itrialspace/README.md b/itrialspace/README.md new file mode 100644 index 0000000000000000000000000000000000000000..ff07178da9c285a7195d4471250d94e4fba4b76d --- /dev/null +++ b/itrialspace/README.md @@ -0,0 +1,336 @@ + + + +
+ +# iTrialSpace + +**A Synthetic Imaging Clinical-Trial Engine for lung-CT AI evaluation.** + +*Specify the cohort you need — then manufacture anatomically grounded synthetic CTs to match, +and evaluate detectors and vision-language models under controlled, one-variable-at-a-time conditions.* + +
+ +> ⚠️ **License pending.** The license is being finalized — see [`LICENSE`](LICENSE). Please do +> not redistribute until it is confirmed. **Research use only — not for clinical use.** + +--- + +## What it is + +iTrialSpace turns medical-imaging AI evaluation from *"find more data"* into *"specify the data +you need."* It harmonizes **13,140 nodule profiles** from **7 public lung-CT datasets**, plans +virtual clinical-trial cohorts across **13 trial modes**, inserts donor nodule masks into real +host anatomy, synthesizes CT volumes with a ControlNet-conditioned diffusion model +(**NodMAISI**), and evaluates **vision-language models (VLMs)** under systematically controlled +conditions. + +**Why it exists.** Public lung-screening datasets are each narrow in their own way — some are +enriched for heavy smokers, some lack malignancy labels, some contain only large cancers — so AI +models end up tested on data that under-represents where they fail. iTrialSpace lets you declare a +cohort by its *statistical properties* (prevalence, size distribution, lobe distribution, +demographics) and generates synthetic CTs to match, enabling controlled experiments that fixed +retrospective datasets cannot support. + +**What this repository is.** A clean, installable, **code-only** monorepo. Source CT *images* and +trained model *weights* are not redistributed here (they carry their own licenses and are large); +the derived synthetic data is released separately as a dataset (see [Data & release](#7-data--release)). + +--- + +## Track — how to read this README + +A guided path from zero to a full evaluation. Each row is a section below; follow them in order, +or jump to what you need. + +| # | Section | What you'll get | +|---|---------|-----------------| +| 1 | [Highlights](#1-highlights) | The capabilities at a glance | +| 2 | [Architecture](#2-architecture) | The five-stage engine and how the pieces connect | +| 3 | [Installation](#3-installation) | Environment, the package, and the extras matrix | +| 4 | [Configuration](#4-configuration) | The one env var that makes it run anywhere | +| 5 | [Quickstart](#5-quickstart) | Install → configure → smoke-test in five commands | +| 6 | [The end-to-end pipeline](#6-the-end-to-end-pipeline) | index → trials → masks → synthesis → evaluation | +| 7 | [Data & release](#7-data--release) | The 7 datasets, what is shared, how to assemble it | +| 8 | [Trial modes](#8-trial-modes) | The 13 cohort designs you can synthesize | +| 9 | [VLM evaluation (end to end)](#9-vlm-evaluation-end-to-end) | Build → run → analyze, locally or on SLURM | +| 10 | [Reproducibility](#10-reproducibility) | Frozen splits, the reporting convention, checksums | +| 11 | [Apps: NoduleMap & Retriever](#11-apps-nodulemap--retriever) | Explore and search the nodule space | +| 12 | [Command reference](#12-command-reference) | Console scripts and module entry points | +| 13 | [Project layout](#13-project-layout) | Where everything lives | +| 14 | [Citation, contributing, license](#14-citation-contributing-license) | How to cite and contribute | + +--- + +## 1. Highlights + +- **Cohort-by-specification.** Plan trials by prevalence, size, lobe, and demographics — not by + whatever a retrospective dataset happens to contain. +- **Anatomically grounded synthesis.** Donor nodule masks are pasted into real host lung anatomy + and rendered by **NodMAISI**, a ControlNet-conditioned diffusion model. +- **13 trial modes**, from controlled-prevalence and size/location sensitivity curves to digital + twins of real patients. +- **Zero-shot VLM evaluation** — BiomedCLIP, LLaVA-Med, and MedGemma across 3 clinical tasks × + 4 spatial-guidance conditions, on synthetic and real CT. +- **Portable by construction.** All paths resolve from a single env var; the same code runs on a + laptop, a workstation, or an HPC cluster. A CI portability gate enforces it. +- **Reproducible reporting.** Frozen, checksummed evaluation splits and a documented reporting + convention keep every published number tied to an exact, verifiable case set. + +--- + +## 2. Architecture + +``` + itrialspace → trials → mask_inserter → synthesis → evaluation + (nodule index + (cohort (donor mask (NodMAISI (VLM + query + features) manifests) → host anatomy) CT volumes) zero-shot) + │ + ├─ nodulemap — interactive embedding-graph explorer + └─ retriever — faceted search, similarity & donor matching + CT viewer +``` + +One installable package, `itrialspace`, with sub-packages for each stage. Configuration, I/O, and +path resolution are centralized so nothing hardcodes a machine-specific path. Full component map: +[blinded_doc/architecture.md](blinded_doc/architecture.md). + +--- + +## 3. Installation + +```bash +# 1) Environment (conda/mamba) +conda env create -f environment.yml && conda activate itrialspace + +# 2) Install the package with the extras you need +pip install -e ".[all]" # or a subset — see the matrix +``` + +**Extras matrix** + +| Extra | Installs | For | +|-------|----------|-----| +| *(base)* | pandas, numpy, pyyaml | Index, query, trial planning | +| `imaging` | nibabel, scipy, SimpleITK | Mask insertion, NIfTI handling | +| `web` | fastapi, streamlit, faiss, umap | NoduleMap + Retriever UIs | +| `synthesis` | monai, (torch) | NodMAISI CT synthesis ¹ | +| `vlm` | transformers, accelerate, open_clip | VLM evaluation ¹ | +| `dev` | pytest, ruff, black, pre-commit | Development | +| `all` | imaging + web + vlm + dev | Everything bundled | + +¹ PyTorch is platform-specific — install it per [blinded_doc/installation.md](blinded_doc/installation.md). +A `docker/Dockerfile` is provided for a containerized setup. + +--- + +## 4. Configuration + +Everything is driven by environment variables (loaded from a gitignored `.env`); nothing is +hardcoded. + +```bash +cp .env.example .env # then edit: +# ITRIALSPACE_DATA_DIR → the dataset root (raw_ct/ masks/ profiles/ …) +# ITRIALSPACE_OUTPUT_DIR → where generated artifacts go (default: = data dir) +# HF_TOKEN → HuggingFace token for gated VLMs (kept local; never committed) +``` + +Any config YAML may reference these with `${VAR}` interpolation. `its config` prints the resolved +paths. Details: [blinded_doc/configuration.md](blinded_doc/configuration.md). + +--- + +## 5. Quickstart + +```bash +conda activate itrialspace +pip install -e ".[all]" +cp .env.example .env # set ITRIALSPACE_DATA_DIR (+ HF_TOKEN for VLMs) + +pytest -m "not full_volume" # unit tests — no external data needed +its config # verify resolved paths +its index stats # build the nodule index + print stats (needs profiles/) +``` + +A guided first cohort is in [blinded_doc/walkthrough_mode1.md](blinded_doc/walkthrough_mode1.md). + +--- + +## 6. The end-to-end pipeline + +Five stages take you from a raw nodule index to evaluated models. Each stage is a CLI command and +a documented module. + +| Stage | What it does | Entry point | +|-------|--------------|-------------| +| **1. Index** | Harmonize 7 datasets into one nodule index with reinsertion features | `its index` | +| **2. Trials** | Plan cohort **manifests** for the 13 trial modes (donor → host, location, scale) | `its-trials` | +| **3. Mask insertion** | Paste donor nodule masks into host organ/lobe masks (nodule = label 23) | `its-insert` | +| **4. Synthesis** | Render CT volumes from the combined masks with **NodMAISI** | `its` (synthesis) | +| **5. Evaluation** | Score **VLMs** (zero-shot) under controlled conditions | `its-vlm` | + +Full walkthrough: [blinded_doc/pipeline.md](blinded_doc/pipeline.md) and +[blinded_doc/running_the_pipeline.md](blinded_doc/running_the_pipeline.md). HPC orchestration scripts are under +[`infra/slurm/`](infra/slurm/). + +--- + +## 7. Data & release + +iTrialSpace harmonizes **7 public lung-CT datasets** (13,140 nodule profiles): + +| Dataset | Nodule profiles | Dataset | Nodule profiles | +|---------|----------------:|---------|----------------:| +| LUNA25 | 6,163 | LUNA16 | 1,186 | +| DLCS24 | 2,487 | LNDbv4 | 768 | +| IMDCT | 2,032 | NSCLCR | 421 | +| LUNGx | 83 | **Total** | **13,140** | + +**What the release ships** (derived artifacts): nodule `profiles/`, `masks/`, cohort +`manifests/`, combined `inserted_masks/`, the **synthetic CT volumes** (`generated_cts/` — +**44,174** volumes across all 13 modes), and the **VLM evaluation dataset** (`vlm_dataset/` — +**42,858** synthetic and **13,087** real evaluation cases). + +**What it does not ship.** The real CT **images** are not redistributed — download them from each +provider under their own license and place them under `raw_ct/{DATASET}/`. The data contract, +counts, ground-truth definitions, and assembly instructions are in +[blinded_doc/dataset_card.md](blinded_doc/dataset_card.md) and [blinded_doc/data.md](blinded_doc/data.md). + +--- + +## 8. Trial modes + +Thirteen cohort designs, each producing a manifest you can synthesize and evaluate: + +| # | Mode | Question it answers | +|---|------|---------------------| +| 1 | `controlled_prevalence` | How does performance change with cancer prevalence? | +| 2 | `size_detection_curve` | Detection sensitivity vs. nodule size (FROC) | +| 3 | `location_sensitivity` | Detection vs. anatomical lobe | +| 4 | `demographic_stratification` | Performance across demographic strata | +| 5 | `counterfactual` | The same patient, with vs. without a nodule | +| 6 | `cross_dataset` | Generalization across acquisition sources | +| 7 | `bootstrap_confidence` | Confidence intervals via resampled cohorts | +| 8 | `algorithm_comparison` | Standardized head-to-head model comparison | +| 9 | `screening_simulation` | Multi-round screening with prevalence decay | +| 10 | `multi_nodule_realism` | Impact of companion nodules in context | +| 11 | `digital_twin_isolation` | Each native nodule isolated within its host anatomy | +| 12 | `digital_twin_complete` | All native nodules of a scan, reconstructed | +| 13 | `digital_twin_cross` | Donor nodules placed in cross-patient host anatomy | + +Details and per-mode parameters: [blinded_doc/trial_modes.md](blinded_doc/trial_modes.md). + +--- + +## 9. VLM evaluation (end to end) + +Evaluate **BiomedCLIP**, **LLaVA-Med**, and **MedGemma** on three zero-shot tasks — +**presence** (binary), **lobe** (5-class), **size** (4-class) — under four image **conditions** +(`plain`, `bbox`, `contour`, `bbox_contour`), on synthetic and real CT. + +The whole workflow is **three steps**, identical for a small demo and the full dataset (only the +paths/env change): + +```bash +# 1) BUILD the 2-D eval dataset (slices + overlays + ground truth) +python -m itrialspace.evaluation.vlm_eval.build_dataset --manifest … --output-dir … --overlays +# (real CTs: itrialspace.evaluation.vlm_eval.build_real_dataset) + +# 2) RUN a model across all conditions × tasks +python -m itrialspace.evaluation.vlm_eval.runners.run_conditions \ + --model biomedclip --run-all-conditions --dataset-csv …/eval_dataset.csv --output-dir … + +# 3) ANALYZE → tables, figures, statistics, report.md +python -m itrialspace.evaluation.vlm_eval.eval_analysis --results … --out analysis/ +``` + +On a cluster, the same three steps are env-driven SLURM jobs — +`build_dataset.sub → run_vlm.sub → analyze.sub` — see +[infra/slurm/vlm_eval/README.md](infra/slurm/vlm_eval/README.md). + +The **analysis suite** (`eval_analysis`) auto-discovers whatever models/conditions/tasks are +present and emits accuracy and Δ-vs-baseline tables, per-mode / per-dataset / per-size / per-lobe +breakdowns, confusion matrices, per-class accuracy, **bootstrap confidence intervals**, **McNemar +significance**, publication-style figures, and an assembled `report.md`. + +- User guide: [blinded_doc/vlm_eval.md](blinded_doc/vlm_eval.md) +- Architecture & module reference: [blinded_doc/vlm_eval_implementation.md](blinded_doc/vlm_eval_implementation.md) +- Headline results: [blinded_doc/vlm_results.md](blinded_doc/vlm_results.md) + +--- + +## 10. Reproducibility + +- **Frozen splits.** Each result is reported on a checksummed case list (`vlm_dataset/splits/`): + `release_v1` (the headline set) and `release_v1_full` (cases scored under all four conditions). + `splits.json` records counts, SHA-256, and provenance — regenerate and the hash must match. +- **One reporting N.** Accuracy is always computed on the cases scored in *every* + (model × condition × task), keyed by a stable canonical slice id (not a positional index), so + all reported numbers are directly comparable. +- **Determinism & audit trails.** Every synthesis case carries an audit record; see + [blinded_doc/reproducibility.md](blinded_doc/reproducibility.md). +- **Quality gates.** CI runs lint (`ruff`/`black`), unit tests, and a portability check that + fails on any hardcoded machine-specific path. + +--- + +## 11. Apps: NoduleMap & Retriever + +- **NoduleMap** (`its-nodulemap`) — an interactive embedding-graph explorer of the nodule space. + See [blinded_doc/nodulemap.md](blinded_doc/nodulemap.md). +- **Retriever** (`its-retriever`) — faceted search, similarity and donor matching, with an + integrated CT viewer. See [blinded_doc/retriever.md](blinded_doc/retriever.md). + +--- + +## 12. Command reference + +| Command | Purpose | +|---------|---------| +| `its` | Umbrella CLI — index, query, config, synthesis subcommands | +| `its-trials` | Generate cohort manifests for the 13 trial modes | +| `its-insert` | Insert donor nodule masks into host anatomy from a manifest | +| `its-vlm` | VLM evaluation utilities | +| `its-nodulemap` | Launch the NoduleMap server | +| `its-retriever` | Launch the Retriever API + UI | + +VLM modules: `…vlm_eval.build_dataset` · `…build_real_dataset` · `…runners.run_conditions` · +`…make_split` · `…eval_analysis` · `…report`. + +--- + +## 13. Project layout + +``` +itrialspace/ +├── src/itrialspace/ # the package +│ ├── core/ io/ index/ query/ site/ # nodule index, query, path resolution +│ ├── config/ # env-driven settings + ${VAR} interpolation +│ ├── trials/ # the 13 trial-mode cohort planners +│ ├── mask_inserter/ # donor mask → host anatomy +│ ├── synthesis/ # NodMAISI CT synthesis (code; weights external) +│ ├── nodulemap/ retriever/ # the two apps +│ └── evaluation/ +│ └── vlm_eval/ # build → run → analyze (incl. eval_analysis suite) +├── configs/ # example, env-interpolated configs +├── infra/slurm/ # cluster job scripts (env-driven) +├── blinded_doc/ # full documentation set (blinded) +├── tests/ docker/ +└── pyproject.toml environment.yml .env.example +``` + +--- + +## 14. Citation, contributing, license + +- **Citation** — withheld for double-blind review. (Cite each underlying CT dataset you + download into `raw_ct/` per its own terms.) +- **Contribute** via [`CONTRIBUTING.md`](CONTRIBUTING.md) — all PRs run through CI (lint + tests + + portability gate). +- **License** — see [`LICENSE`](LICENSE) (being finalized). Research use only; not a medical + device and not for clinical use. + +
+iTrialSpace — specify the cohort, synthesize the data, evaluate with control. +
diff --git a/itrialspace/blinded_doc/architecture.md b/itrialspace/blinded_doc/architecture.md new file mode 100644 index 0000000000000000000000000000000000000000..68b19cbbd6de5f63fb9a3019a7a1af25bc6bf4c2 --- /dev/null +++ b/itrialspace/blinded_doc/architecture.md @@ -0,0 +1,65 @@ + + +# Architecture + +iTrialSpace is one installable package, `itrialspace`, using a `src/` layout. Each former +top-level project is now a subpackage under a single namespace. + +``` +src/itrialspace/ +├── config/ Portable path/settings resolution (settings.py) +├── core/ Data model: NoduleProfile, LabelNormaliser, schema, enums +├── io/ Dataset loading: DatasetLoader, DatasetRegistry, adapters +├── index/ NoduleIndex — merged multi-dataset DataFrame +├── query/ NoduleQuery (fluent filters), ReinsertionMatcher (k-NN) +├── site/ Synthetic trial engine: specs, sampling, planner, cohort builder +├── trials/ Trial manifest runner (the 13 modes) +├── mask_inserter/ Voxel-level nodule mask insertion (label 23) +├── synthesis/ NodMAISI CT synthesis (model weights external) +├── apps/ +│ ├── nodulemap/ Embedding graph viz (FastAPI + sigma.js) +│ └── retriever/ Faceted search + similarity UI (FastAPI + Streamlit) +├── evaluation/ OPTIONAL evaluation extras +│ ├── vlm_eval/ Vision-language model evaluation +├── utils/ Shared helpers +└── cli.py Umbrella `its` CLI +``` + +Supporting top-level directories: + +``` +configs/ Example configs (*.example.yaml) + non-path configs (trials, features) +infra/slurm/ HPC submission scripts, cluster-portable via env.sh +docs/ This documentation +tests/ Unified pytest suite (runs with no external data) +docker/ Container build +``` + +## Component map (old → new) + +| Original top-level | New namespace | Console script | +|--------------------|---------------|----------------| +| `itrialspace/` (core) | `itrialspace.{core,io,index,query,site}` | `its` | +| `itrialspace_mask_inserter/` | `itrialspace.mask_inserter` | `its-insert` | +| `site_trials/` | `itrialspace.trials` | `its-trials` | +| `nodmaisi_synth/` (code) | `itrialspace.synthesis` | (subprocess) | +| `nodulemap/` | `itrialspace.apps.nodulemap` | `its-nodulemap` | +| `retriever/` | `itrialspace.apps.retriever` | `its-retriever` | +| `vlm_evaluation/` | `itrialspace.evaluation.vlm_eval` | (module/scripts)* | + +\* VLM evaluation runs via its module scripts (`python -m itrialspace.evaluation.vlm_eval...`) +rather than a console entry point. + +## Data flow + +``` +NoduleIndex ──▶ CohortBuilder ──▶ mask_inserter ──▶ synthesis ──▶ evaluation + (7 datasets) (TrialSpec → (donor mask (NodMAISI (VLM eval) + manifest) @ label 23) CT volume) + │ + ├─▶ nodulemap (graph viz) + └─▶ retriever (search) +``` + +See [pipeline.md](pipeline.md) for the full end-to-end flow and +[SKILL.md](../SKILL.md) for an exhaustive per-file reference. diff --git a/itrialspace/blinded_doc/configuration.md b/itrialspace/blinded_doc/configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..1523ca88f92d3cf67c5d31bd1ed0cc220d9e3808 --- /dev/null +++ b/itrialspace/blinded_doc/configuration.md @@ -0,0 +1,79 @@ + + +# Configuration & path model + +iTrialSpace resolves **every** filesystem path from environment variables (with sensible +defaults), so the same code and configs run unchanged on a laptop, a workstation, or an +HPC cluster. Nothing is hardcoded. + +The single source of truth is [`itrialspace.config.settings`](../src/itrialspace/config/settings.py). + +## Environment variables + +Copy `.env.example` → `.env` and edit. (`infra/slurm/env.sh` and the synthesis +config loaders all read these.) + +| Variable | Default | Meaning | +|----------|---------|---------| +| `ITRIALSPACE_DATA_DIR` | `~/.itrialspace/data` | Root of the unified data layout | +| `ITRIALSPACE_OUTPUT_DIR` | `=DATA_DIR` | Where generated artifacts are written | +| `ITRIALSPACE_ROOT` | auto-detected | Repo root (for resolving `configs/`) | +| `NODMAISI_MODELS_DIR` | — | NodMAISI model weights directory | +| `ITRIALSPACE_CONDA_ENV`, `SLURM_PARTITION_*` | `itrialspace`, … | HPC/SLURM only | + +Check what resolved: + +```bash +its config +``` + +## YAML interpolation + +Any string in a config YAML may reference these variables with `${VAR}` syntax. The +config loaders expand them (falling back to the documented defaults even when the variable +is not exported): + +```yaml +# configs/paths.yaml +base_dir: ${ITRIALSPACE_DATA_DIR} +``` + +## Config file resolution + +Path-bearing configs ship as `configs/*.example.yaml`. Resolution order +(`settings.find_config`): + +1. `ITRIALSPACE__CONFIG` env override (e.g. `ITRIALSPACE_DATASETS_CONFIG`) +2. `configs/.yaml` (your local copy — gitignored) +3. `configs/.example.yaml` (shipped example) +4. the default bundled inside the package + +To customize, copy the example and edit: + +```bash +cp configs/paths.example.yaml configs/paths.yaml +``` + +| Config | Example file | Used by | +|--------|--------------|---------| +| Dataset registry | `configs/datasets.example.yaml` | `DatasetRegistry.from_yaml()` | +| Data layout | `configs/paths.example.yaml` | `PathResolver` | +| NodMAISI integration | `configs/integration.example.yaml` | synthesis pipeline | +| Mask inserter | `configs/mask_inserter.example.yaml` | mask insertion | +| Trial templates | `configs/trials.yaml` | trial knowledge base (no paths) | +| Embedding features | `configs/features.yaml` | NoduleMap (no paths) | + +## Using the API directly + +```python +from itrialspace.config import settings +settings.data_dir() # Path to the data root +settings.load_yaml("configs/paths.example.yaml") # loads + expands ${VARS} +settings.find_config("datasets.yaml") # resolves a config path +``` + +## Portability guard + +`tools/check_portability.py` (run by pre-commit and CI) fails the build if any tracked +file reintroduces a hardcoded absolute path. Always resolve paths through `settings` or +env vars. diff --git a/itrialspace/blinded_doc/data.md b/itrialspace/blinded_doc/data.md new file mode 100644 index 0000000000000000000000000000000000000000..e067c7991c68b71af88ab20346dac6141388fe8f --- /dev/null +++ b/itrialspace/blinded_doc/data.md @@ -0,0 +1,62 @@ + + +# Data preparation + +iTrialSpace ships **code only**. The source CT datasets and trained model weights are not +redistributed (they carry their own licenses and are large). This guide describes the +expected layout and how to obtain the data. + +The repo bundles **no data** — point `ITRIALSPACE_DATA_DIR` at your real data root (set it +once in `.env`; see [configuration.md](configuration.md)). Examples and data-dependent +tests read from there and skip cleanly when it isn't present (e.g. in CI). + +## Unified data layout + +Point `ITRIALSPACE_DATA_DIR` (in `.env`) at a directory with this structure: + +``` +$ITRIALSPACE_DATA_DIR/ +├── raw_ct/{DATASET}/ CT scans (NIfTI, RAS+) +├── masks/{DATASET}/ +│ ├── nodule_seg/ Individual nodule masks +│ ├── combined_seg/ Combined per-patient masks +│ ├── organ_seg/ VISTA3D organ segs (raw, deprecated) +│ └── refined_seg/ Refined organ + body segs (default) +├── profiles/ {DATASET}_nodule_profiles.csv (53-column schema) +├── meta/ Original dataset metadata CSVs +├── manifests/ Generated cohort manifests +├── inserted_masks/ Mask-insertion outputs +└── generated_cts/ NodMAISI synthesis outputs +``` + +`ct_path` values in the profile CSVs are **relative** to `raw_ct/`, e.g. +`DLCS24/DLCS_0001.nii.gz`. Verify resolution with `its config` and the `PathResolver`. + +## The 7 supported datasets + +| Dataset | Source | Notes | +|---------|--------|-------| +| **DLCS24** | Institutional Lung Cancer Screening | Binary label, Lung-RADS, demographics | +| **LUNA25** | LUNA25 challenge | Largest; multi-nodule screening | +| **LUNA16** | LUNA16 / LIDC-IDRI | No malignancy label (anatomy only) | +| **LUNGx** | SPIE-AAPM LUNGx | Malignancy classification benchmark, ~49% malignant | +| **LNDbv4** | LNDb | Multi-radiologist ratings (float → threshold) | +| **NSCLCR** | NSCLC-Radiomics (TCIA) | 100% malignant, staging/survival | +| **IMDCT** | Internal multi-modal diagnostic CT | PET, spiculation, benign/cancer | + +> `NLST3D` was permanently removed from the core pipeline for data-quality reasons and is +> guarded against at multiple layers. + +Each public dataset must be obtained from its original source under its own license. Once +downloaded, harmonize each into the 53-column `CORE_COLS` schema (see +`itrialspace.core.schema`) as `{DATASET}_nodule_profiles.csv` and place CTs/masks per the +layout above. + +## Adding a new dataset + +1. Produce `{DATASET}_nodule_profiles.csv` matching `CORE_COLS` (incl. the 12 + `reinsertion_*` columns). +2. Add an adapter in `src/itrialspace/io/adapters/adapters.py`. +3. Register it in `core/schema.py` (`DATASET_NAMES`, `DATASET_FLAGS`), `core/label.py`, + and `configs/datasets.example.yaml` + `configs/paths.example.yaml`. +4. Add tests. diff --git a/itrialspace/blinded_doc/dataset_card.md b/itrialspace/blinded_doc/dataset_card.md new file mode 100644 index 0000000000000000000000000000000000000000..fe6d816d98e1944ea2a03dbcb47f08064fb5cae7 --- /dev/null +++ b/itrialspace/blinded_doc/dataset_card.md @@ -0,0 +1,250 @@ + + +# iTrialSpace — public dataset card + +This card describes the iTrialSpace data release: what is included, how it is organised, what +is **not** redistributed (the real CT volumes), and how to obtain and assemble everything for +use. It accompanies the [iTrialSpace code](https://github.com/anonymous/itrialspace). + +> **Research use only — not for clinical use.** The synthetic CTs are generated for method +> development and evaluation; they are not medical devices and must not be used for diagnosis. + +## What this release is + +iTrialSpace harmonises lung-nodule data from **7 public CT datasets** and uses it to (a) plan +synthetic clinical-trial cohorts, (b) insert donor nodule masks into host anatomy, (c) +synthesise CT volumes (NodMAISI), and (d) build VLM evaluation datasets. This release ships the +**derived** artifacts (profiles, masks, manifests, inserted masks, synthetic CTs, VLM eval +sets). It does **not** redistribute the **real CT images** — you obtain those from the original +dataset providers under their own licenses (see [§ Obtaining `raw_ct/`](#obtaining-raw_ct)). + +**NLST3D is excluded** from this release. It was permanently removed from the project; no +NLST3D profiles, masks, metadata, synthetic data, or VLM data are shared. + +## Directory layout (what is shared) + +``` +iTrialSpace/ +├── profiles/ # per-dataset nodule profile CSVs ({DATASET}_nodule_profiles.csv) — 13,140 nodules, 7 datasets +├── meta/ # per-dataset metadata CSVs (demographics, acquisition, labels) +├── masks/ # segmentation masks per dataset (nodule_seg/, refined_seg/, ...) +├── manifests/ # synthetic cohort manifests for the 13 trial modes +├── inserted_masks/ # combined organ+nodule masks (nodule = label 23) used as synthesis input +├── generated_cts/ # 3-D SYNTHETIC CT volumes (the headline synthetic data) — see below +├── generated_cts_qc/ # (optional, may be withheld) QC montages — these embed real CT pixels +└── vlm_dataset/ # VLM evaluation dataset (2-D slices + ground truth + model results) + ├── synthetic/ # merged standard + digital-twin (modes 1–13): lung_axial/, lung_axial_medgemma/, cross_model_comparison/ + ├── real/ # real-CT eval set (7 datasets): lung_axial/, lung_axial_medgemma/, cross_model_comparison/ + └── splits/ # frozen, checksummed evaluation splits (the exact cases each result is reported on) + +# NOT shared — you provide it: +└── raw_ct/ # the real CT volumes ({DATASET}/.nii.gz) — obtain from sources below +``` + +All paths inside the shipped CSVs/JSONs are **relative to the dataset root** (or basenames), so +the release is portable once `raw_ct/` is populated. Set `ITRIALSPACE_DATA_DIR` to this root. + +## Components + +| Dir | Contents | Notes | +|-----|----------|-------| +| `profiles/` | One CSV per dataset: nodule coordinates, diameter, lobe/zone/side, distances, label, 12 reinsertion features | Derived metadata; 13,140 nodules | +| `meta/` | Per-dataset metadata (age/sex/smoking where available, acquisition, label source) | Derived from source datasets — see licensing | +| `masks/` | `{DATASET}/nodule_seg/` (per-nodule), `refined_seg/` (organ+body) NIfTI | Derived segmentations | +| `manifests/` | `mode{1..13}_*/…csv` cohort manifests (which donor → which host, at what location/scale) | Synthetic specs; no real images | +| `inserted_masks/` | Combined organ+nodule masks (label 23) + `audit.json` | Synthesis input | +| `generated_cts/` | `mode*//{synthetic_ct.nii.gz, input_mask.nii.gz, input_mask_label.nii.gz, dataset.json, nodmaisi_audit.json}` | 44,174 synthetic CTs; ~3 TB | +| `generated_cts_qc/` | `mode*//qc/*.png` QC montages | **Embed real host-CT pixels** — withhold unless source licenses permit | +| `vlm_dataset/` | 2-D slices (4 conditions × 3 z), `eval_dataset.csv`, per-model results, cross-model comparison | Synthetic = 42,858 cases; real = 13,087 cases (7 datasets) | + +`generated_cts/` case dirs have been cleaned for release: real-CT symlinks removed, intermediate +temp files dropped, QC moved to `generated_cts_qc/`, and `nodmaisi_audit.json` scrubbed of +real-CT paths. + +## Dataset counts + +**Nodules per dataset** (`profiles/`, `masks/`) — NLST3D excluded: + +| Dataset | Nodule profiles | Nodule masks | +|---------|----------------:|-------------:| +| DLCS24 | 2,487 | 2,473 | +| LUNA25 | 6,163 | 6,156 | +| IMDCT | 2,032 | 2,032 | +| LUNA16 | 1,186 | 1,184 | +| LNDbv4 | 768 | 743 | +| NSCLCR | 421 | 421 | +| LUNGx | 83 | 83 | +| **Total** | **13,140** | **13,112** | + +(Mask count is slightly lower where a per-nodule segmentation was unavailable.) + +**Synthetic** — 3-D CTs in `generated_cts/`: **44,174** complete volumes (all 13 trial modes); +VLM eval cases in `vlm_dataset/synthetic/` (per profile): **42,858** (the slice-level subset +that passed extraction). Per mode: + +| Mode | CTs | Mode | CTs | Mode | CTs | +|------|----:|------|----:|------|----:| +| 1 controlled_prevalence | 999 | 6 cross_dataset | 1,499 | 11 digital_twin_isolation | 12,448 | +| 2 size_detection | 598 | 7 bootstrap | 3,984 | 12 digital_twin_complete | 8,981 | +| 3 location | 500 | 8 algo_comparison | 499 | 13 digital_twin_cross | 9,378 | +| 4 demographic | 799 | 9 screening | 1,495 | | | +| 5 counterfactual | 2,496 | 10 multi_nodule | 498 | **Total** | **44,174** | + +**Real** — VLM eval cases in `vlm_dataset/real/` (per profile): **13,087** (LUNA25 6,156 · +DLCS24 2,473 · IMDCT 2,032 · LUNA16 1,179 · LNDbv4 743 · NSCLCR 421 · LUNGx 83). + +**Images per case (VLM)** — 4 conditions (`plain`, `bbox`, `contour`, `bbox_contour`) × 3 +z-slices (`z`, `z-1`, `z+1`) = up to **12 PNGs/case**. Total extracted slices ≈ **502k** per +synthetic profile and ≈ **157k** per real profile. Two profiles are provided per set: +`lung_axial` (BiomedCLIP/LLaVA-Med) and `lung_axial_medgemma` (MedGemma). + +## VLM ground truth + +Each row of `vlm_dataset/**/eval_dataset.csv` is one nodule slice with the ground-truth labels +for **three zero-shot evaluation tasks** (columns in the CSV): + +| Task | Column | Classes | +|------|--------|---------| +| **Presence** (binary) | `ground_truth_presence` | `present`, `absent` | +| **Lobe** (5-class localisation) | `ground_truth_lobe` | `right_lung_upper_lobe`, `right_lung_middle_lobe`, `right_lung_lower_lobe`, `left_lung_upper_lobe`, `left_lung_lower_lobe` | +| **Size** (4-class) | `ground_truth_size_bucket` | `<5mm`, `5-10mm`, `10-20mm`, `>20mm` | + +How the labels are derived: + +- **Synthetic set** — ground truth is **known by construction**, not predicted: the nodule is + *inserted* at a chosen lobe and scaled to a chosen effective diameter, so `ground_truth_lobe` + comes from the insertion lobe and `ground_truth_size_bucket` from binning `effective_diam_mm`. + `ground_truth_presence` is `present` for inserted cases and `absent` for the deliberately + nodule-free cases (e.g. the counterfactual mode). This exactness — automatic, leakage-free + labels at a controlled lobe/size — is the point of the synthetic pipeline. +- **Real set** — ground truth comes from each source dataset's annotations: `ground_truth_lobe` + from the profile's lobe (normalised to the 5 canonical classes) and `ground_truth_size_bucket` + from binning `nodule_mean_diam_mm`; all real cases are `present`. + +The models output a predicted label per task; `correct = (prediction == ground_truth)`, and +accuracy = mean(`correct`). Results are reported per image **condition** (`plain`, `bbox`, +`contour`, `bbox_contour`) so the effect of spatial guidance can be measured. Size buckets use +half-open bins (`<5`, `[5,10)`, `[10,20)`, `≥20` mm); lobe accepts the standard `RUL/RML/RLL/ +LUL/LLL` aliases on input. + +### Slices: stored vs used for evaluation + +Each profile (`lung_axial`, `lung_axial_medgemma`) stores, per case, **3 z-slices** (`z`, `z-1`, +`z+1`) × **4 conditions** = up to 12 PNGs. **Evaluation uses the center (middle-z) slice** — that +is what `eval_dataset.csv` references for each condition. The `z±1` slices are stored as +multi-slice **context** (used by MedGemma, which loads center + neighbours; **BiomedCLIP and +LLaVA-Med use the center slice only**). The **3 tasks share the same slice** (only the text prompt +differs), so tasks do not multiply the slice count. + +| | Synthetic (per profile) | Real (per profile) | +|---|---:|---:| +| Cases (nodes) | 42,858 | 13,087 | +| Conditions | 4 | 4 | +| z-slices per case | 3 (`z`, `z-1`, `z+1`) | 3 | +| **Slices stored** (all z × conditions) | ≈ 502,048 | ≈ 156,678 | +| **Center slices = used for evaluation** (1 / case / condition) | 167,364 | 52,228 | +| ↳ per condition: `plain` | 42,858 | 13,087 | +| ↳ per condition: `bbox` / `contour` / `bbox_contour` (each) | 41,502 | 13,047 | + +(The overlay conditions cover slightly fewer cases than `plain` — a small number of cases had no +overlay generated.) **Predictions per run** = one per case per (model × condition × task); e.g. a +single BiomedCLIP × `plain` × `presence` run scores 42,858 synthetic / 13,087 real center slices. + +### Reporting convention (evaluation N) — read before comparing to the paper + +Accuracy is **reported on the set of cases that have a completed prediction in *every* +(task × condition × model)** so that all reported numbers share a single N — i.e. the same cases +are scored for presence, lobe, and size. In **this released dataset that set is the full case +count** (42,858 synthetic / 13,087 real): every row in `eval_dataset.csv` is complete for all +three tasks (verified — 0 rows missing presence/lobe/size). + +The original paper analysis reported a **smaller synthetic N (42,382)** for exactly this reason: +at analysis time 334 mode-13 cases (and a few others) had slices extracted but **inference not yet +run**, so they were excluded to keep N consistent across all tasks — the same "score every case in +every task" rule, applied before inference was finished. The intermediate counts seen in the +frozen paper folder reconcile as: + +| Count | Meaning | +|------:|---------| +| **42,382** | synthetic cases with **inference complete in all 3 tasks** → the paper's accuracy tables | +| 42,716 | slices **extracted on disk** at paper time (= 42,382 + 334 mode-13 pending inference) | +| **42,858** | the **finished** release: inference complete for all extracted cases (after re-extraction: mode-7 +10, mode-11 +213, mode-13 −81) | + +So the paper's 42,382 and the release's 42,858 are the *same convention* at two points in time, not +a conflicting count. Result-analysis scripts must apply this intersection so released numbers stay +self-consistent — see [vlm_eval.md § Reporting convention](vlm_eval.md#4a-reporting-convention--keeping-released-numbers-aligned) +and `metrics.common_case_ids()`. + +**Frozen splits — the exact cases reported on.** `vlm_dataset/splits/` ships the case lists so a +result can always be tied to (and reproduced on) its exact case set. Each `*.txt` holds one +**canonical uid** per line (`mode/case`, condition-independent); `splits.json` records the count, a +SHA-256 of the list, the source result files, and the code commit (verifiable — regenerate and the +hash must match). The case identity is the slice path, **not** the `case_id` column (which is a +non-unique positional index in the CSVs). + +| Split | Synthetic | Real | Scope | +|-------|----------:|-----:|-------| +| `release_v1` | 42,858 | 13,087 | scored by all 3 models on `plain`, all 3 tasks (the headline counts) | +| `release_v1_full` | 41,502 | 13,047 | strict ∩ across all 3 models × all 4 conditions × 3 tasks (use for condition-comparison tables) | + +Run on exactly a split with the runners' `--case-ids` flag, e.g. +`--case-ids vlm_dataset/splits/release_v1.synthetic.txt`. Details, verification, and regeneration: +`vlm_dataset/splits/README.md` and [vlm_eval.md § Reporting convention](vlm_eval.md#4a-reporting-convention--keeping-released-numbers-aligned). + +## Obtaining `raw_ct/` + +The real CT volumes are **not** redistributed. Download each dataset from its original provider +(honouring its license and citation requirements) and place the volumes under +`raw_ct/{DATASET}/` to match the `ct_path` values in `profiles/`. + +> ⚠ **Action for maintainers:** verify each dataset's exact citation, license, and access URL +> before publishing, and replace the bracketed fields below with the official text. + +| `{DATASET}` | Dataset | Source / access | Citation | +|-------------|---------|-----------------|----------| +| `DLCS24` | Institutional Lung Cancer Screening (2024) | [add access URL] | [add official citation] | +| `LUNA25` | LUNA25 challenge | [add access URL, e.g. luna25.grand-challenge.org] | [add citation] | +| `LUNA16` | LUNA16 challenge (LIDC-IDRI subset) | https://luna16.grand-challenge.org | Setio et al., *Med. Image Anal.* 2017 [verify] | +| `LUNGx` | SPIE-AAPM-NCI LUNGx Challenge | TCIA: SPIE-AAPM Lung CT Challenge | Armato et al. [verify] | +| `LNDbv4` | LNDb challenge (v4) | https://lndb.grand-challenge.org | Pedrosa et al. 2019 [verify] | +| `NSCLCR` | NSCLC-Radiomics | TCIA: NSCLC-Radiomics | Aerts et al., *Nat. Commun.* 2014 [verify] | +| `IMDCT` | [add full name] | [add access URL] | [add citation] | + +Expected layout after download: +``` +raw_ct/ +├── DLCS24/.nii.gz +├── LUNA25/.nii.gz +├── LUNA16/.nii.gz +├── LUNGx/.nii.gz +├── LNDbv4/.nii.gz +├── NSCLCR/.nii.gz +└── IMDCT/.nii.gz +``` +The exact filenames are the ones referenced in `profiles/{DATASET}_nodule_profiles.csv` +(`ct_path` column). Convert DICOM→NIfTI (RAS+) if the source ships DICOM. + +## Licensing & governance + +- **Synthetic data** (`generated_cts/`, `inserted_masks/`, synthetic `vlm_dataset/`) is generated + by iTrialSpace from public-dataset host anatomy; released under [LICENSE — to be finalised]. +- **Derived annotations** (`profiles/`, `meta/`, `masks/`, real `vlm_dataset/`) are derived from + the source datasets. Redistribution of derived data is subject to each source's license — + confirm per dataset before publishing; remove any field a source disallows. +- **Real CT images** are never redistributed here. +- **NLST3D** is excluded entirely (purged from the project). + +## How to use + +```bash +export ITRIALSPACE_DATA_DIR=/path/to/iTrialSpace # this dataset root +# 1) populate raw_ct/ from the sources above +# 2) install the code (see the repo) and point at the data: +its config # verify resolved paths +``` +See the repo docs: [data.md](data.md), [vlm_eval.md](vlm_eval.md), [pipeline.md](pipeline.md). + +## Citation + +If you use this dataset, cite each underlying CT dataset you downloaded into `raw_ct/` +(table above), honouring its license and citation requirements. diff --git a/itrialspace/blinded_doc/index.md b/itrialspace/blinded_doc/index.md new file mode 100644 index 0000000000000000000000000000000000000000..96fb25f37d5202707656625bc30b4d84b515ff50 --- /dev/null +++ b/itrialspace/blinded_doc/index.md @@ -0,0 +1,32 @@ + + +# iTrialSpace Documentation + +**Synthetic Imaging Clinical Trial Engine for lung CT AI evaluation.** + +iTrialSpace harmonizes 13,140 nodule profiles from 7 public lung CT datasets, builds +virtual clinical-trial cohorts across 13 trial modes, inserts donor nodule masks into +real host anatomy, synthesizes CT volumes with a ControlNet-conditioned diffusion model +(NodMAISI), and evaluates vision-language models. + +## Start here + +| Guide | What it covers | +|-------|----------------| +| [Installation](installation.md) | Environments, extras, GPU/torch, Docker | +| [Quickstart](quickstart.md) | First commands; build the index; run a trial | +| [Walkthrough: Mode 1 end-to-end](walkthrough_mode1.md) | 200 cases: plan → insert → generate CTs | +| [Running the pipeline (runbook + smoke test)](running_the_pipeline.md) | All 13 modes via SLURM; copy-paste commands for every step | +| [Configuration](configuration.md) | The env-driven path model (runs anywhere) | +| [Data preparation](data.md) | Laying out the 7 datasets; sample fixtures | +| [Dataset card](dataset_card.md) | Public data release: shared dirs, `raw_ct` sources/citations, NLST3D exclusion | +| [Architecture](architecture.md) | Components and how they fit together | +| [Pipeline](pipeline.md) | End-to-end flow: index → trials → masks → CT → eval | +| [Trial modes](trial_modes.md) | The 13 trial modes | +| [NoduleMap](nodulemap.md) | Build + serve the embedding graph explorer (`its-nodulemap`) | +| [Retriever](retriever.md) | Faceted search, similarity & donor matching + CT viewer (`its-retriever`) | +| [VLM evaluation](vlm_eval.md) | Evaluate BiomedCLIP / LLaVA-Med / MedGemma on nodule CT (synthetic + real) | +| [VLM evaluation — implementation](vlm_eval_implementation.md) | Engineering/architecture reference for the VLM eval subsystem | +| [VLM results](vlm_results.md) | Headline accuracy tables on the fixed all-conditions split | +| [NoduleMap similarity design](nodulemap_similarity.md) | Donor-matching metric + optional appearance (radiomics/foundation) roadmap | +| [Reproducibility](reproducibility.md) | Determinism, audit trails, HPC orchestration | diff --git a/itrialspace/blinded_doc/installation.md b/itrialspace/blinded_doc/installation.md new file mode 100644 index 0000000000000000000000000000000000000000..a78fd4b873bf30dc31720b1197709e464fd491fd --- /dev/null +++ b/itrialspace/blinded_doc/installation.md @@ -0,0 +1,179 @@ + + +# Installation + +iTrialSpace is a single installable package (`itrialspace`) with **optional-dependency +extras** so you install only what a given task needs. It runs on a workstation or an HPC +cluster — nothing is hardcoded to a specific machine. + +## 1. Get the code + +```bash +git clone +cd itrialspace +``` + +## 2. Create an environment + +**Conda (recommended for the imaging/ML stack)** — versions pinned to the dev env (Python 3.10): + +```bash +conda env create -f environment.yml +conda activate itrialspace +``` + +**Exact clone of the development environment** (Python 3.10.13, +torch 2.4.1+cu121, git-pinned MONAI, full pinned set) — the "give me exactly what worked" +option: + +```bash +conda env create -f environment.lock.yml # one command; uses requirements.lock.txt +conda activate itrialspace +# or into a plain venv: +# python3.10 -m venv .venv && . .venv/bin/activate +# pip install -r requirements.lock.txt && pip install -e . +``` + +> The lock includes torch + MONAI and some packages from the original shared env; it +> targets linux-64 / CUDA 12.1. Trim `requirements.lock.txt` if you only need certain stages. + +**Or a minimal plain venv:** + +```bash +python -m venv .venv && source .venv/bin/activate +pip install --upgrade pip +``` + +## 3. Install with the extras you need + +```bash +pip install -e ".[imaging,web]" # core pipeline + web tools +pip install -e ".[dev]" # + tests/lint/format +pip install -e ".[all]" # imaging + web + vlm + dev +``` + +| Extra | Installs | Enables | +|-------|----------|---------| +| *(base)* | pandas, numpy, pyyaml | Index, query, trial planning | +| `imaging` | nibabel, scipy, SimpleITK | Mask insertion, NIfTI I/O | +| `web` | fastapi, streamlit, faiss, umap-learn, pyarrow | NoduleMap + Retriever | +| `synthesis` | monai | NodMAISI synthesis* | +| `vlm` | transformers, open_clip_torch | VLM evaluation* | +| `dev` | pytest, ruff, black, pre-commit | Development | + +\* **PyTorch is not declared as a dependency** — install the build matching your CUDA: + +```bash +# match the dev env: CUDA 12.1 +pip install torch==2.4.1 --index-url https://download.pytorch.org/whl/cu121 +pip install -e ".[synthesis,vlm]" +``` + +\*\* The `eval` extra also needs **external** models/repos that are not bundled — see +[evaluation_external_dependencies.md](evaluation_external_dependencies.md). + +## 4. Configure paths + +```bash +cp .env.example .env # then edit ITRIALSPACE_DATA_DIR etc. +its config # prints the resolved paths — verify them +``` + +See [configuration.md](configuration.md) for the full path model. + +## 5. Verify + +```bash +pytest -m "not full_volume" # unit tests (no external data needed) +python tools/check_portability.py # no hardcoded paths +``` + +## Model weights (NodMAISI synthesis) + +Synthesis model weights (`autoencoder.pt`, `diffusion_unet.pt`, the ControlNet +checkpoint) are **not** in the repo. Obtain them (see the NodMAISI release / Hugging Face) +and point to their directory: + +```bash +export NODMAISI_MODELS_DIR=/path/to/nodmaisi/models +``` + +## Containers + +**Mental model:** the image ships **code only**. Data, model weights, and outputs are +**mounted at runtime** (`-v host:container`) and pointed to with env vars — they're never +baked into the image. There are three deployment routes: + +| Target | Use | +|--------|-----| +| New HPC cluster | conda env (`environment.yml`) + SLURM (`infra/slurm/`) — Docker usually unavailable on compute nodes | +| Standalone server / cloud VM (CPU) | **Docker (CPU)** image | +| GPU server / synthesis & VLM | **Docker (GPU)** image, or **Apptainer** on HPC | + +### Docker — CPU image (core + imaging + web) + +```bash +docker build -t itrialspace -f docker/Dockerfile . + +# verify resolved paths +docker run --rm -e ITRIALSPACE_DATA_DIR=/data -v /host/iTrialSpace:/data \ + itrialspace its config + +# generate a manifest (mount data + outputs) +docker run --rm \ + -e ITRIALSPACE_DATA_DIR=/data -e ITRIALSPACE_OUTPUT_DIR=/out \ + -v /host/iTrialSpace:/data -v /host/outputs:/out \ + itrialspace its-trials --mode controlled_prevalence --n-cases 200 --output-dir /out/manifests/mode1 + +# launch a web tool (publish the port) +docker run --rm -p 8422:8422 -e ITRIALSPACE_DATA_DIR=/data -v /host/iTrialSpace:/data \ + itrialspace its-nodulemap serve --port 8422 +``` +The entrypoint is `its`, so the trailing args are the subcommand. For a shell: +`docker run --rm -it --entrypoint bash itrialspace`. This image has **no PyTorch/CUDA** — +it cannot run synthesis/VLM. + +### Docker — GPU image (synthesis + VLM) + +```bash +docker build -t itrialspace-gpu -f docker/Dockerfile.gpu . + +# Step 3 synthesis — mount data, outputs, AND the NodMAISI weights +docker run --rm --gpus all \ + -e ITRIALSPACE_DATA_DIR=/data -e ITRIALSPACE_OUTPUT_DIR=/out -e NODMAISI_MODELS_DIR=/models \ + -v /host/iTrialSpace:/data -v /host/outputs:/out -v /host/nodmaisi/models:/models \ + --entrypoint python itrialspace-gpu \ + -m itrialspace.synthesis.tools.run_itrialspace_to_ct \ + --audit /out/inserted_masks/mode1_controlled_prevalence/audit.json \ + --config src/itrialspace/synthesis/tools/integration_config.yaml \ + --outdir /out/generated_cts/mode1_controlled_prevalence +``` +Built on `nvidia/cuda:12.1.1-cudnn8-runtime` + torch 2.4.1 (cu121). Requires the NVIDIA Container +Toolkit on the host (`--gpus all`). Adjust the CUDA tag in `docker/Dockerfile.gpu` to match +your driver. + +### Apptainer / Singularity (HPC clusters) + +Most clusters disallow Docker but support Apptainer (rootless, no daemon): + +```bash +# build from the recipe (run at repo root), or convert a built Docker image +apptainer build itrialspace.sif docker/itrialspace.def +# apptainer build itrialspace.sif docker-daemon://itrialspace-gpu:latest + +# run the CLI (bind data/outputs/weights; --nv exposes GPUs) +apptainer run --nv \ + --env ITRIALSPACE_DATA_DIR=/data,ITRIALSPACE_OUTPUT_DIR=/out,NODMAISI_MODELS_DIR=/models \ + -B /scratch/.../iTrialSpace:/data,/scratch/.../outputs:/out,/path/models:/models \ + itrialspace.sif config + +# synthesis +apptainer exec --nv \ + --env ITRIALSPACE_DATA_DIR=/data,ITRIALSPACE_OUTPUT_DIR=/out,NODMAISI_MODELS_DIR=/models \ + -B /host/iTrialSpace:/data,/host/outputs:/out,/host/models:/models \ + itrialspace.sif \ + python -m itrialspace.synthesis.tools.run_itrialspace_to_ct \ + --audit /out/inserted_masks/mode1_controlled_prevalence/audit.json \ + --config /opt/itrialspace/src/itrialspace/synthesis/tools/integration_config.yaml \ + --outdir /out/generated_cts/mode1_controlled_prevalence +``` diff --git a/itrialspace/blinded_doc/nodulemap.md b/itrialspace/blinded_doc/nodulemap.md new file mode 100644 index 0000000000000000000000000000000000000000..29e029b89bec2f8ebf77b4d67f67fc91a7cf5e01 --- /dev/null +++ b/itrialspace/blinded_doc/nodulemap.md @@ -0,0 +1,286 @@ + + +# NoduleMap — embedding graph explorer + +NoduleMap is an interactive web tool for exploring the **13,140-nodule index** as a +similarity graph. Each nodule is a node placed by a 2-D embedding (PCA / UMAP / t-SNE) of its +anatomy-aware *reinsertion* features; edges connect each nodule to its k nearest neighbours. +You can filter by dataset / label / lobe / zone / side / size, recolour the graph, inspect a +node's full metadata and an axial CT thumbnail, and export a node's neighbours as a +candidate-donor list. + +- **Backend**: FastAPI (default port **8422**), served by `uvicorn`. +- **Frontend**: single-page sigma.js app (no build step — loaded from CDN). +- **Engine**: FAISS `IndexFlatL2` k-NN (sklearn fallback). +- **Package**: `itrialspace.apps.nodulemap` · **CLI**: `its-nodulemap`. + +The tool runs in two phases: you **build artifacts once** (embeddings + edges), then +**serve** them. Everything is path-portable through `itrialspace.config.settings`. + +--- + +## 1. Prerequisites + +```bash +conda activate itrialspace +pip install -e ".[apps]" # fastapi, uvicorn, faiss-cpu, umap-learn, scikit-learn, pyarrow, … +cp .env.example .env # set ITRIALSPACE_DATA_DIR (where the 7 profile CSVs live) +its config # verify the resolved data/output dirs +``` + +NoduleMap reads the nodule index from the dataset registry +(`configs/datasets.example.yaml` → your local `configs/datasets.yaml` → package default), +which points at `$ITRIALSPACE_DATA_DIR/profiles/{DATASET}_nodule_profiles.csv`. No CT volumes +are needed to build or browse the graph — they're only read on demand for the axial +thumbnails (step 5). + +### Where artifacts live (`$NODULEMAP_ARTIFACTS`) + +Like the model-weights path, the artifact location is an env var. Set it once in `.env`: + +```bash +NODULEMAP_ARTIFACTS=/path/to/iTrialSpace/outputs/nodulemap_artifacts +``` + +- **Default** (if unset): `$ITRIALSPACE_OUTPUT_DIR/nodulemap_artifacts`. +- Every `its-nodulemap` subcommand and both SLURM jobs read it, so once it's in `.env` you + can **omit `--outdir` / `--artifact-dir`** entirely. +- A `--outdir` / `--artifact-dir` flag always wins over the env var (handy for one-offs). +- To **serve pre-built artifacts** from elsewhere, just point `NODULEMAP_ARTIFACTS` (or the + flag) at that directory. + +> **HPC note:** the build is CPU-only and quick (a couple of minutes). On SLURM, source +> `infra/slurm/env.sh` first so the env, `.env`, and `PYTHONNOUSERSITE=1` are set, then run +> the same commands below. + +--- + +## 2. Build the artifacts + +Pick a directory for the artifacts. Anything ending in `_artifacts/` is gitignored; here we +keep them next to the other outputs: + +```bash +export ART="$ITRIALSPACE_OUTPUT_DIR/nodulemap_artifacts" + +# Build all three 2-D layouts (PCA + UMAP + t-SNE) on the default feature set +its-nodulemap build --all-2d --feature-set reinsertion_core --outdir "$ART" + +# Build the k-NN edge lists for each layout (k = 3, 5, 10, 25) +for M in PCA_2D UMAP_2D TSNE_2D; do + its-nodulemap edges --model "$M" --feature-set reinsertion_core --all-k --outdir "$ART" +done +``` + +What gets written (per `model`): + +| File | Contents | +|------|----------| +| `embeddings___.npy` | N×D coordinate matrix | +| `metadata___.parquet` | per-node metadata (dataset, label, lobe, diameter, …) | +| `preprocessor___.pkl` | fitted scaler/encoder (for projecting new points) | +| `info___.yaml` | build parameters + provenance | +| `edges_____k__.parquet` | k-NN edge list | + +**Models** (from `configs/features.yaml`): `PCA_2D`, `UMAP_2D`, `TSNE_2D` (layouts) and +`PCA_32`, `UMAP_16`, `UMAP_32` (higher-D, for search/neighbour quality). +**Feature sets**: `reinsertion_core` (12 reinsertion columns, **0 NaN — recommended**) or +`core_53` (all 53 columns, needs imputation). +**Edge options**: `--k`, `--mode {closest,farthest}`, `--scope {cross_dataset,within_dataset}`, +`--space {weighted,feature_l2,embedding}` (default **weighted** — the clinical donor-matching +metric; see §5). `build` also writes one `features_.npy` (the standardized search +space, shared across models). + +Single-model build instead of `--all-2d`: + +```bash +its-nodulemap build --model UMAP_2D --feature-set reinsertion_core --outdir "$ART" +its-nodulemap edges --model UMAP_2D --feature-set reinsertion_core --k 5 --outdir "$ART" +``` + +--- + +## 3. Inspect what you built + +```bash +its-nodulemap info --artifact-dir "$ART" +``` + +Lists every embedding (nodes × dims), edge list (edge count), and metadata table +(nodes × datasets). Use this to confirm a build before serving. + +--- + +## 4. Serve the web app + +```bash +its-nodulemap serve --artifact-dir "$ART" --port 8422 +# → open http://localhost:8422 +``` + +On a remote/HPC node, forward the port over SSH from your laptop: + +```bash +ssh -N -L 8422::8422 you@cluster # then browse http://localhost:8422 +``` + +In the browser: a top **app bar** (brand + version + GitHub + About); left sidebar = filters +(dataset, label, lobe, zone, side, size, diameter range); centre = the sigma.js graph; right = +node detail + neighbours; a footer with the research-use disclaimer. Recolour with the +**color-by** control (`dataset`, `label`, `lobe`, `size`, `zone`, `side`). Hover for a +tooltip, click a node for full metadata, its axial CT thumbnail, and ranked donor neighbours. + +> **Use a real browser** (Chrome/Firefox) via the port forward — **not** an in-editor +> webview (e.g. VSCode Simple Browser). sigma.js uses WebGL for click/hover *picking*; in a +> webview the graph may render but clicking a node won't select it. + +### Branding / About + +The header, favicon, About dialog, and footer disclaimer are baked into +`apps/nodulemap/frontend/static/index.html` (served live — edits show on browser refresh, no +restart). External links are driven by one `BRAND` config block near the bottom of that file: + +```js +var BRAND = { version: "0.1.0", + links: { GitHub: "https://github.com/anonymous/itrialspace", Docs: "", Paper: "" } }; +``` + +Empty links are hidden (no dead links); fill `Docs`/`Paper` to surface them in the bar. The +lab/institution wordmark and the “Research use only — not for clinical use” disclaimer live in +the same file. + +### Axial thumbnails (rendered on the fly) + +Thumbnails are **generated per request** from the source CT — nothing is pre-rendered or saved +to disk. `GET /api/node/{id}/axial_thumbnail` resolves the node's CT (+ nodule mask) under +`$ITRIALSPACE_DATA_DIR`, reorients to RAS+, windows the lung, overlays the mask + crosshair + +R/L/A/P labels, and returns PNG bytes. A small in-memory LRU (last **8** CT volumes) speeds +repeat clicks; there is **no on-disk PNG cache**. Implications: the viewer stores zero image +artifacts and always reflects current data, but a node's CT must be present (else the +thumbnail is omitted), and the first click into a new CT pays one NIfTI read. + +### HTTP API (also usable without the UI) + +| Method | Endpoint | Purpose | +|--------|----------|---------| +| GET | `/health` | status + available models | +| GET | `/api/models` | per-model readiness (embeddings + edges present) | +| GET | `/api/filters?model=UMAP_2D` | unique filter values + diameter range | +| GET/POST | `/api/graph` | filtered nodes + edges (params: `vis_model`, `search_model`, `k`, `mode`, `scope`, `color_by`, `datasets`, `label`, `lobe`, …) | +| GET | `/api/node/{id}` | full node metadata | +| GET | `/api/node/{id}/axial_thumbnail` | CT slice PNG (needs `$ITRIALSPACE_DATA_DIR` CTs) | +| GET | `/api/node/{id}/neighbors?k=10&scope=cross_dataset` | ranked neighbours | +| POST | `/api/export` | export neighbours (csv / json / donors) | + +```bash +curl "http://localhost:8422/health" +curl "http://localhost:8422/api/graph?vis_model=UMAP_2D&color_by=lobe&datasets=DLCS24,LUNA25&k=5" +``` + +--- + +## 5. Offline (no server): query & export neighbours + +Handy for scripting candidate-donor selection straight from the artifacts: + +```bash +# Print the 10 nearest neighbours of a node +its-nodulemap query --node DLCS24_DLCS_0001_01 --model UMAP_2D --k 10 --artifact-dir "$ART" + +# Export them — formats: csv | json | donors (a reinsertion candidate-donor manifest) +its-nodulemap export --node DLCS24_DLCS_0001_01 --model UMAP_2D --k 10 \ + --format donors --artifact-dir "$ART" -o "$ITRIALSPACE_OUTPUT_DIR/nodulemap_exports" +``` + +Node IDs are `{DATASET}_{annotation_id}`; copy one from the UI, from a metadata parquet, or +from `its-nodulemap query` output. + +### Search backend (`--search-backend`) + +"Similar donors" / edges are ranked in a **search space**, decoupled from the 2D layout: + +| backend | what | when | +|---------|------|------| +| `weighted` (default) | clinical `ReinsertionMatcher` metric (L1: lobe penalty + cc% + pleural + diameter) | donor matching for reinsertion | +| `feature_l2` | exact L2 on the standardized 22-D feature vector | neutral anatomy similarity | +| `embedding` | L2 on the reduced 2D/16D embedding | legacy / comparison only — not recommended | + +```bash +its-nodulemap query --node DLCS24_DLCS_0001_01 --search-backend weighted +its-nodulemap edges --model UMAP_2D --all-k --space weighted # graph edges +``` + +Why this matters (measured, see [nodulemap_similarity.md](nodulemap_similarity.md)): searching +the 2D PCA embedding gives only **0.53** lobe concordance vs **1.00** for `weighted`. The 2D +embeddings are for *display*; retrieval runs on the full feature space. Run +`python -m itrialspace.apps.nodulemap.tools.similarity_report` to regenerate the numbers. + +--- + +## 6. Rebuilding after the index changes + +If you add a dataset or regenerate profiles, rebuild the artifacts (embeddings depend on the +full index): + +```bash +its-nodulemap build --all-2d --feature-set reinsertion_core --outdir "$ART" +for M in PCA_2D UMAP_2D TSNE_2D; do + its-nodulemap edges --model "$M" --feature-set reinsertion_core --all-k --outdir "$ART"; done +``` + +The purge verifier and tests assert the removed NLST3D dataset never appears in any artifact: + +```bash +python -m itrialspace.apps.nodulemap.tools.verify_purge --artifact-dir "$ART" +pytest tests/nodulemap/ # 54 tests: model integrity + NLST3D purge +``` + +(`rebuild_nodulemap.sub` runs both automatically after every rebuild.) + +--- + +## 7. On HPC (SLURM): two separate jobs + +Building is a one-time step (rerun only when the index changes); serving is a long-running +job. They are **two separate subs** under `infra/slurm/nodulemap/`: + +```bash +# 1) Build artifacts ONCE (CPU, ~minutes; cleans + rebuilds all models + edges, verifies NLST3D purge) +sbatch infra/slurm/nodulemap/rebuild_nodulemap.sub + +# 2) Serve (long-running; does NOT rebuild — fails fast if artifacts are missing) +sbatch infra/slurm/nodulemap/nodulemap.sub +squeue -u $USER # find the NODE it landed on +tail -f logs/nodulemap-.out # prints node, port, and the SSH-tunnel line +scancel # stop the server when done +``` + +Both default the artifact location to `$ITRIALSPACE_OUTPUT_DIR/nodulemap_artifacts` +(override with `NODULEMAP_ARTIFACTS=...`); the server port is `8422` (override with +`NODULEMAP_PORT=...`). Both source `infra/slurm/env.sh`, so the env, `.env` paths, and +`PYTHONNOUSERSITE` are handled automatically. + +**Auto-publish:** `nodulemap.sub` reverse-tunnels its port back to `$SLURM_SUBMIT_HOST` (the +login node you submitted from), so you always open `http://localhost:8422` regardless of which +compute node it landed on — no manual `ssh -L`. With VS Code on the login node it just works. +Needs passwordless SSH compute→login; disable with `ITS_AUTOTUNNEL=0` (the log prints a manual +tunnel fallback). + +## 8. Troubleshooting + +| Symptom | Fix | +|---------|-----| +| `No embeddings found` on `serve`/`info` | Point `--artifact-dir` at the dir you built into; run `build` first. | +| Index loads `~/.itrialspace/data` (empty) | `.env` not loaded — `set -a; . ./.env; set +a` (or source `infra/slurm/env.sh`), then check `its config`. | +| `FileNotFoundError: …profiles/*.csv` | `ITRIALSPACE_DATA_DIR` doesn't contain `profiles/{DATASET}_nodule_profiles.csv` — see [data.md](data.md). | +| Graph is empty in the browser | Filters too narrow, or the selected `vis_model` has no edge list — build edges for that model. | +| Clicking a node does nothing (no detail/image) | You're in an in-editor webview without WebGL picking — open in a real browser (Chrome/Firefox) via the port forward. | +| Axial thumbnail 404/blank | Raw CTs for that dataset aren't under `$ITRIALSPACE_DATA_DIR` (thumbnails are optional). | +| First thumbnail click feels slow | Normal — the CT is read/decoded once then cached (LRU of 8 volumes); repeats are instant. | +| `ModuleNotFoundError: faiss/umap/fastapi` | `pip install -e ".[apps]"`. | +| Port already in use | `--port `; on HPC also change the SSH tunnel's local port. | + +See also: [retriever.md](retriever.md) — the `its-retriever` faceted-search companion tool, +[architecture.md](architecture.md), and +[nodulemap_similarity.md](nodulemap_similarity.md) — the similarity/donor-matching design +and the optional appearance-based (radiomics / foundation-model) roadmap. diff --git a/itrialspace/blinded_doc/pipeline.md b/itrialspace/blinded_doc/pipeline.md new file mode 100644 index 0000000000000000000000000000000000000000..40f8a7c86dd2e7b595a74f90a3fc3dbbfb7b36f7 --- /dev/null +++ b/itrialspace/blinded_doc/pipeline.md @@ -0,0 +1,36 @@ + + +# End-to-end pipeline + +The full flow from raw datasets to evaluation results. + +``` +1. INDEX NoduleIndex loads 7 dataset CSVs → unified DataFrame (13,140 × 53 cols) +2. PLAN CohortBuilder applies a TrialSpec (1 of 13 modes) → CohortManifest CSV +3. INSERT mask_inserter pastes donor nodule masks into host organ segs @ label 23 +4. SYNTHESIZE NodMAISI (ControlNet rectified-flow diffusion) → synthetic CT volumes +5. EVALUATE VLM zero-shot evaluation (presence / lobe / size) +6. EXPLORE NoduleMap (graph) and Retriever (search) over the index +``` + +## Commands per stage + +```bash +# 2. Plan +its-trials --mode controlled_prevalence --n-cases 200 --output-dir "$ITRIALSPACE_OUTPUT_DIR/manifests/mode1" + +# 3. Insert +its-insert run --manifest --output-dir "$ITRIALSPACE_OUTPUT_DIR/inserted_masks/mode1" + +# 4. Synthesize (needs NODMAISI_MODELS_DIR) +python -m itrialspace.synthesis.tools.run_itrialspace_to_ct \ + --mask-root "$ITRIALSPACE_OUTPUT_DIR/inserted_masks/mode1" \ + --config configs/integration.example.yaml \ + --outdir "$ITRIALSPACE_OUTPUT_DIR/generated_cts/mode1" + +# 5. Evaluate (VLM) +python -m itrialspace.evaluation.vlm_eval.build_dataset --profile lung_axial ... +python -m itrialspace.evaluation.vlm_eval.run_all ... +``` + +Each stage also has SLURM scripts under `infra/slurm/`. diff --git a/itrialspace/blinded_doc/quickstart.md b/itrialspace/blinded_doc/quickstart.md new file mode 100644 index 0000000000000000000000000000000000000000..9b791cb7c4ca5d7083729991e1100ba429a62b36 --- /dev/null +++ b/itrialspace/blinded_doc/quickstart.md @@ -0,0 +1,74 @@ + + +# Quickstart + +Assumes you've [installed](installation.md) the package and run `cp .env.example .env`. + +## Verify your setup + +```bash +its config # prints resolved data dir, output dir, configs dir +its --help +``` + +## With your datasets + +Point `ITRIALSPACE_DATA_DIR` at your data root (set in `.env`) so the 7 datasets are laid +out under `$ITRIALSPACE_DATA_DIR/profiles/` etc. (see [data.md](data.md)): + +```bash +# Build the unified index and print stats +its index stats + +# List configured datasets +its info +``` + +```python +from itrialspace import NoduleIndex, DatasetRegistry + +idx = NoduleIndex.from_registry(DatasetRegistry.from_yaml()) +malignant_upper = ( + idx.query() + .malignant() + .lobe(["right_upper", "left_upper"]) + .diameter(8, 20) + .fetch() +) +print(len(malignant_upper)) +``` + +## Generate a trial cohort manifest + +```bash +its-trials --mode controlled_prevalence --n-cases 200 --prevalence 0.05 \ + --output-dir "$ITRIALSPACE_OUTPUT_DIR/manifests/mode1" +``` + +See [trial_modes.md](trial_modes.md) for all 13 modes. + +## Insert nodule masks → synthesize CTs + +```bash +# Insert donor masks into host organ segmentations (label 23) +its-insert run --manifest "$ITRIALSPACE_OUTPUT_DIR/manifests/mode1/.csv" \ + --output-dir "$ITRIALSPACE_OUTPUT_DIR/inserted_masks/mode1" + +# Synthesize CTs (needs NODMAISI_MODELS_DIR; see installation.md) +python -m itrialspace.synthesis.tools.run_itrialspace_to_ct \ + --mask-root "$ITRIALSPACE_OUTPUT_DIR/inserted_masks/mode1" \ + --config configs/integration.example.yaml \ + --outdir "$ITRIALSPACE_OUTPUT_DIR/generated_cts/mode1" +``` + +## Explore interactively + +```bash +its-nodulemap serve --port 8422 # graph visualization (needs built artifacts) +its-retriever serve # faceted search API + Streamlit UI +``` + +## On HPC + +Every stage has SLURM scripts under `infra/slurm/` that are cluster-portable via +`infra/slurm/env.sh`. See [infra/slurm/README.md](../infra/slurm/README.md). diff --git a/itrialspace/blinded_doc/reproducibility.md b/itrialspace/blinded_doc/reproducibility.md new file mode 100644 index 0000000000000000000000000000000000000000..ce70a2e33248571ab14aa38b1003b77d568f1434 --- /dev/null +++ b/itrialspace/blinded_doc/reproducibility.md @@ -0,0 +1,24 @@ + + +# Reproducibility + +iTrialSpace is designed for exact reproduction. + +- **Determinism**: `seed=42` throughout. Per-case placement seeds are derived as + `SHA-256(trial_name + case_id + nodule_idx + global_seed)` — identical inputs produce + identical outputs. +- **Audit trails**: mask insertion writes `audit.json` (24-field provenance per case); + synthesis writes `nodmaisi_audit.json` and a `pipeline_summary.json`. +- **NIfTI orientation**: all volumes are canonicalized to RAS+ (`nib.as_closest_canonical`) + before any voxel operation. +- **Config-pinned paths**: every path comes from `ITRIALSPACE_DATA_DIR` / configs, so a + run is fully described by its `.env` + config + seed. +- **HPC orchestration**: `infra/slurm/` scripts are cluster-portable via `env.sh`. + +## Reproducing a run + +```bash +cp .env.example .env # set ITRIALSPACE_DATA_DIR, seed defaults to 42 +its-trials --mode --seed 42 --output-dir +# inspect /_run_config.json for the exact parameters used +``` diff --git a/itrialspace/blinded_doc/retriever.md b/itrialspace/blinded_doc/retriever.md new file mode 100644 index 0000000000000000000000000000000000000000..200d3f02d490fd7eb704e382442b5a05d90fe178 --- /dev/null +++ b/itrialspace/blinded_doc/retriever.md @@ -0,0 +1,246 @@ + + +# Retriever — browse, visualize & extract lung-nodule data + +The Retriever is a query engine over the **13,140-nodule index**. Its two everyday uses: + +1. **Visualize the nodules** — filter the library, browse results as a table, and view each + nodule's **CT slice** (with mask overlay and radiology window presets); compare similar + nodules side by side. +2. **Extract the data** — export the matching nodules (with all metadata **and resolved CT/mask + file paths**) to **CSV/JSON** for downstream work. + +It also ranks reinsertion-donor candidates for a target anatomy. It complements +[NoduleMap](nodulemap.md) (similarity *graph*) with a **table + CT-viewer + export** interface. + +- **No build step** — it loads the index live from the dataset registry; no precomputed artifacts. +- **Backend**: FastAPI (default **8421**). **UI**: Streamlit (default **8501**). +- **Package**: `itrialspace.apps.retriever` · **CLI**: `its-retriever`. +- Three modes: **UI** (Streamlit), **API** (HTTP), **CLI** (offline) — same engine underneath. + +## Three query types + +| Query | What it does | Engine | +|-------|--------------|--------| +| **Faceted search** | filter by dataset, label, lobe, zone, side, position, diameter, pleural/airway distance, population, label source, reinsertion facets, … | `FacetedSearch` | +| **Similarity** (by example) | given a reference `annotation_id`, the k most similar nodules (weighted k-NN over the 12 reinsertion features) | `SimilarityEngine` | +| **Reinsertion matching** | given a target anatomy (lobe + cc% + pleural + diameter), the best donor nodules to place there | `ReinsertionMatcher` | + +Reinsertion matching uses the **same clinical metric** as NoduleMap's `weighted` donor search. + +--- + +## 1. Prerequisites + +```bash +conda activate itrialspace +pip install -e ".[apps]" # fastapi, uvicorn, streamlit, nibabel, pillow, … +cp .env.example .env # set ITRIALSPACE_DATA_DIR (the 7 profile CSVs) +its config # verify resolved paths +``` + +The index is read from the dataset registry (`configs/datasets.example.yaml` → local +`configs/datasets.yaml` → package default) at `$ITRIALSPACE_DATA_DIR/profiles/`. CT volumes are +only needed for the **CT-slice viewer** and for `--include-paths` exports. + +--- + +## 2. Launch the app (API + UI) + +The simplest path on HPC is the "hit and run" sub, which starts **both** servers in one job: + +```bash +sbatch infra/slurm/retriever/app.sub +tail -f logs/retriever-app-.out # prints node, ports, and the SSH-tunnel line +``` + +Or run locally: + +```bash +its-retriever serve --port 8421 & # FastAPI +streamlit run src/itrialspace/apps/retriever/ui/app.py -- --api-url http://localhost:8421 +# → open http://localhost:8501 +``` + +From your laptop, forward the **UI** port and open it in a real browser: + +```bash +ssh -N -L 8501::8501 you@ # → http://localhost:8501 +``` + +You only need **8501**: the Streamlit server calls the API on the compute node itself +(`localhost:8421` *there*), so that hop never leaves the node. Forward **8421 too only if you +want the raw API / `/docs`** from your laptop (`-L 8421::8421`). The UI also runs in +**direct mode** — loads the index in-process, no API — if you omit `--api-url`. + +--- + +## 3. Visualize the nodules (the UI) + +The Streamlit UI has a left **Filters** sidebar and a **Mode** switch — Search / Similarity / +Matcher: + +- **Search** → set facets in the sidebar, hit **Search**, get a results **table**. Pick any row + in **Nodule detail** to render its **axial CT slice** (nodule mask overlaid), then export + (§4). +- **Similarity** → enter a reference `annotation_id` → top-k similar nodules as a table **plus a + side-by-side CT comparison** so you can eyeball how alike they are. +- **Matcher** → choose a target lobe (+ optional cc% / pleural / diameter / label) → ranked + donor candidates with CT views and full metadata. + +All CT views share **window presets**: `lung` (default), `mediastinum`, `soft_tissue`, `bone` +(centre/width from `NIfTISlicer.WINDOW_PRESETS`). Volumes are read on demand from +`$ITRIALSPACE_DATA_DIR` and reoriented to RAS+; if a dataset's CTs aren't present the table and +metadata still work, only the image is omitted. + +Headless / programmatic CT rendering is available via the API (`/ct/slice`, `/ct/nodule-view`, +`/ct/info`) or `engine.get_slice(...)` / `engine.get_nodule_view(...)`. + +--- + +## 4. Extract the data (CSV / JSON) + +Export the **matching nodules** — every column of the search result **plus**, when +`include_paths` is on (default), the **resolved absolute paths** `ct_path`, +`nodule_mask_path`, `organ_seg_path` (so the CSV is directly usable downstream). Columns +include identity (`annotation_id`, `dataset`, `patient_id`), label, anatomy (`lobe_name`, +`lung_side`, `lung_zone`, `central_peripheral`), `nodule_mean_diam_mm`, `pleural_distance_mm`, +and the `reinsertion_*` fields. + +Three equivalent ways: + +```bash +# A) CLI — write a CSV (or --format json); --no-paths to omit resolved paths +its-retriever export --label 1 --lobe right_lung_upper_lobe --diam-min 8 \ + --format csv -o "$ITRIALSPACE_OUTPUT_DIR/malignant_rul.csv" +``` + +```bash +# B) API — returns a downloadable file +curl -X POST localhost:8421/export -H 'Content-Type: application/json' \ + -d '{"filters":{"label":1,"lobe":["right_lung_upper_lobe"]},"format":"csv","include_paths":true}' \ + -o malignant_rul.csv +``` + +**C) UI** — every result view (Search / Similarity / Matcher) has an **Export** panel with +one-click **Download CSV** / **Download JSON** buttons (the current result, downloaded straight +to your machine). + +JSON exports also embed the `filters` used and a result count, so an export is self-describing +and reproducible. + +--- + +## 5. CLI quickstart (offline, no server) + +```bash +its-retriever info # index summary + per-dataset stats +its-retriever search --label 1 --lobe right_lung_upper_lobe --diam-min 8 --limit 20 +its-retriever similar --id DLCS_0007_01 --k 10 +its-retriever match --lobe left_lung_lower_lobe --diameter 12 --cc-pct 60 --k 10 +its-retriever detail --id DLCS_0007_01 # full record + resolved paths +``` + +IDs are `annotation_id` values (e.g. `DLCS_0007_01`) — note this differs from NoduleMap's +`{DATASET}_{annotation_id}` node IDs. + +> The CLI flags expose a **subset** of the facets. The full filter surface (`SearchFilters`) — +> `central_peripheral`, airway distance, every `reinsertion_*` facet, `n_nodules` range, +> sampling (`sample_n`/`sample_seed`), `offset`, and `sort_by` — is available via the API +> (`POST /search`) and the UI. + +--- + +## 6. HTTP API + +| Method | Endpoint | Purpose | +|--------|----------|---------| +| GET | `/health` | version, nodule count, datasets | +| GET | `/filters` | available facet values | +| POST | `/search` | faceted search (JSON `SearchFilters`) | +| POST | `/similar` | query-by-example similarity | +| POST | `/matcher` | reinsertion donor matching | +| GET | `/nodule/{annotation_id}` | full detail + resolved paths | +| GET | `/ct/slice`, `/ct/nodule-view`, `/ct/info` | CT slice PNG / nodule view / volume info | +| POST | `/export` | download results (csv/json, `include_paths`) | + +Interactive docs at `http://localhost:8421/docs`. + +--- + +## 7. Run it on SLURM (step by step) + +There's **no build step** — `app.sub` starts the API + Streamlit UI in one job. Scripts live +under `infra/slurm/retriever/` and all source `infra/slurm/env.sh` (env, `.env`, conda). Ports +come from `$RETRIEVER_API_PORT` / `$RETRIEVER_UI_PORT` / `$RETRIEVER_JUPYTER_PORT` +(default **8421 / 8501 / 8888**). + +```bash +# 1) Launch (API on 8421 + Streamlit UI on 8501, in one job) +sbatch infra/slurm/retriever/app.sub + +# 2) Open the UI — that's it +# The job auto-publishes its port back to the login node you submitted from, so it's +# always at the SAME address no matter which compute node it landed on. With VS Code on +# the login node, just open: +http://localhost:8501 + +# 3) Stop when done +scancel +``` + +**Auto-publish (no manual tunnel):** `app.sub` reverse-tunnels its ports back to +`$SLURM_SUBMIT_HOST` (the login node you ran `sbatch` from). So you connect at +`login-node:8501` every time — the *"job moved to a new node"* problem is gone. It needs +passwordless SSH compute→login (standard on HPC); disable with `ITS_AUTOTUNNEL=0`. +`tail -f logs/retriever-app-.out` shows whether the auto-tunnel came up. + +**Manual fallback** (if you set `ITS_AUTOTUNNEL=0`, or compute→login SSH is blocked) — forward +the UI port to the node from your laptop: + +```bash +squeue -u $USER # read the node, e.g. node004 +ssh -N -L 8501::8501 you@ # → http://localhost:8501 +``` + +**Why only one port:** 8501 is the Streamlit UI (what the browser talks to). The UI calls the +API on the compute node itself (`localhost:8421` *there*), so only **8501** is published/needed. +The API (8421) is also auto-published — use it only for the raw API / `http://localhost:8421/docs`. + +Other scripts: + +```bash +sbatch infra/slurm/retriever/jupyter.sub # JupyterLab (8888) + API, for notebook use +sbatch infra/slurm/retriever/cli.sub # one-off batch CLI queries +``` + +Notebook helper: `from itrialspace.apps.retriever.notebook import RetrieverClient`. + +--- + +## 8. Retriever vs NoduleMap + +| | **Retriever** | **NoduleMap** | +|--|---------------|---------------| +| Interface | table + CT viewer + export | interactive similarity graph | +| Strength | precise filtering, CT inspection, **data export** | visual structure of the whole library | +| Build step | none (live) | embeddings + edges (one-time) | +| Donor matching | `match` / `/matcher` | `weighted` search backend | + +They share the index and the `ReinsertionMatcher` metric — Retriever to *query/inspect/export*, +NoduleMap to *see the landscape*. + +--- + +## 9. Troubleshooting + +| Symptom | Fix | +|---------|-----| +| Index loads `~/.itrialspace/data` (empty) | `.env` not loaded — `set -a; . ./.env; set +a` (or source `infra/slurm/env.sh`); check `its config`. | +| `FileNotFoundError: …profiles/*.csv` | `ITRIALSPACE_DATA_DIR` lacks `profiles/{DATASET}_nodule_profiles.csv` — see [data.md](data.md). | +| `ModuleNotFoundError: fastapi/streamlit` | `pip install -e ".[apps]"`. | +| CT view blank / export paths empty | raw CTs for that dataset aren't under `$ITRIALSPACE_DATA_DIR` (viewer + `--include-paths` need them; metadata/CSV columns still export). | +| Streamlit can't reach the API | start the API first; pass the matching `--api-url`; forward **both** ports. | +| Port already in use | change `--port` (and the matching env var / SSH tunnel). | + +See also: [NoduleMap](nodulemap.md), [architecture.md](architecture.md). diff --git a/itrialspace/blinded_doc/running_the_pipeline.md b/itrialspace/blinded_doc/running_the_pipeline.md new file mode 100644 index 0000000000000000000000000000000000000000..8658413e9cdefd86bebbf13a33655bcb097651a2 --- /dev/null +++ b/itrialspace/blinded_doc/running_the_pipeline.md @@ -0,0 +1,277 @@ + + +# Running the pipeline (runbook + smoke test) + +A self-contained, copy-paste guide to run iTrialSpace end-to-end on an HPC cluster +(SLURM) — for **all 13 trial modes**, from a 5-case smoke test up to full runs. Every +command is here; you should not need to invent any. + +> ⚠️ **The scripts ship as a QUICK DEMO run with deliberately small numbers** (≈5 cases +> per mode) so the whole pipeline finishes in minutes for validation. These are **not** +> the paper/production sizes. To reproduce the real run, change the case counts as shown +> in **[§5](#5-run-size--demo-vs-paperproduction-run)** (which also lists the exact +> paper-run values and the file + line to edit for every mode). + +**Pipeline:** `trials (manifest) → insertion (label-23 masks + audit) → synthesis (CT)` +→ optional evaluation (VLM). + +--- + +## 0. One-time setup + +```bash +git clone && cd itrialspace # always run commands from the repo root + +# Create the environment (matches the verified dev versions). One of: +conda env create -f environment.yml # curated, pinned +# or an exact clone: +# conda env create -f environment.lock.yml + +# Configure paths/env for this machine +cp .env.example .env +``` + +Edit `.env` (read automatically by every SLURM job via `infra/slurm/env.sh`): + +```bash +ITRIALSPACE_DATA_DIR=/scratch/.../iTrialSpace # INPUTS: raw_ct/ masks/ profiles/ meta/ +ITRIALSPACE_OUTPUT_DIR=/scratch/.../my_outputs # OUTPUTS: manifests/ inserted_masks/ generated_cts/ +ITRIALSPACE_CONDA_ENV=itrialspace # the conda env to activate +NODMAISI_MODELS_DIR=/path/to/nodmaisi/models # synthesis weights (Step 3 only) +SLURM_PARTITION_GPU=vram48 # your GPU partition +SLURM_PARTITION_CPU=defq # your CPU partition +``` + +Verify resolution: + +```bash +its config # prints the resolved data/output dirs and config locations +``` + +> **Cluster notes baked in** (no action needed): jobs run with `PYTHONNOUSERSITE=1` +> (isolated from `~/.local`) and put the env's CUDA libs on `LD_LIBRARY_PATH` (so cuDNN +> initializes). `#SBATCH --partition/--account/--time` are in each `.sub` — edit them for +> your cluster. **Always `sbatch` from the repo root** so `env.sh` is found. + +--- + +## 1. The easy way — one command per mode + +`infra/slurm/run_pipeline.sh` chains all three stages with SLURM dependencies and builds +the manifest/case lists the array jobs need. + +```bash +# Full pipeline for one mode (trials → insertion → synthesis): +infra/slurm/run_pipeline.sh 1 + +# All 13 modes: +for m in $(seq 1 13); do infra/slurm/run_pipeline.sh $m; done + +# Just one stage: +infra/slurm/run_pipeline.sh 2 trials # manifests only +infra/slurm/run_pipeline.sh 2 insert # insertion (after trials done) +infra/slurm/run_pipeline.sh 2 synth # synthesis (after insertion done) +``` + +Run size comes from each mode's `.sub` (see §5). To understand or customize the stages, +read §2–§4 — they are exactly what the helper runs. + +--- + +## 2. Step 1 — Trials (generate cohort manifests) + +One `sbatch` per mode. Each writes manifest CSV/JSON to +`$ITRIALSPACE_OUTPUT_DIR/manifests/mode_*/`. + +```bash +sbatch infra/slurm/trials/mode1_controlled_prevalence.sub +sbatch infra/slurm/trials/mode2_size_detection_curve.sub +# ... mode3 … mode13 (filenames below) +``` + +| Mode | Script | Produces | +|------|--------|----------| +| 1 | `mode1_controlled_prevalence.sub` | 1 manifest | +| 2 | `mode2_size_detection_curve.sub` | per size bucket | +| 3 | `mode3_location_sensitivity.sub` | per lobe | +| 4 | `mode4_demographic_stratification.sub` | per stratum | +| 5 | `mode5_counterfactual.sub` | per varied value | +| 6 | `mode6_cross_dataset.sub` | per dataset | +| 7 | `mode7_bootstrap_confidence.sub` | per replicate | +| 8 | `mode8_algorithm_comparison.sub` | 1 manifest | +| 9 | `mode9_screening_simulation.sub` | per round | +| 10 | `mode10_multi_nodule_realism.sub` | 2 (single + multi sub-cohorts) | +| 11 | `mode11_digital_twin_isolation.sub` | per dataset | +| 12 | `mode12_digital_twin_complete.sub` | per dataset | +| 13 | `mode13_digital_twin_cross.sub` | per host×donor pair | + +Verify: + +```bash +ls $ITRIALSPACE_OUTPUT_DIR/manifests/mode1_controlled_prevalence/ # NLST_cohort.csv … +``` + +--- + +## 3. Step 2 — Insertion (paste nodule masks) + +Reads a mode's manifests and writes a combined label-23 mask per case plus an +`audit.json` per manifest. Uses the **array** script (one task per manifest): + +```bash +source infra/slurm/env.sh # defines $ITRIALSPACE_OUTPUT_DIR etc. +M=1 # mode number +DIR=$(ls -d $ITRIALSPACE_OUTPUT_DIR/manifests/mode${M}_* | head -1) +ML=$ITRIALSPACE_OUTPUT_DIR/manifest_lists/mode${M}.txt +mkdir -p "$(dirname "$ML")"; ls "$DIR"/*.csv | sort > "$ML" + +sbatch --array=0-$(( $(wc -l < "$ML") - 1 )) \ + --export=ALL,MANIFEST_LIST="$ML" \ + infra/slurm/mask_inserter/mode${M}_insert_masks_array.sub +``` + +Preview without writing files: append `,DRY_RUN=true` to `--export`. + +Verify: + +```bash +find $ITRIALSPACE_OUTPUT_DIR/inserted_masks/mode${M}_*/ -name audit.json +find $ITRIALSPACE_OUTPUT_DIR/inserted_masks/mode${M}_*/ -name '*_mask.nii.gz' | wc -l +``` + +--- + +## 4. Step 3 — Synthesis (generate CTs) — **GPU + model weights** + +Needs `NODMAISI_MODELS_DIR` set and the `synthesis` extra installed. One array job per +manifest's `audit.json`, one task per case. Case IDs must be the **mask-filename stems** +(`infra/slurm/_gen_caselist.py` does this): + +```bash +source infra/slurm/env.sh +M=1 +audit=$(find $ITRIALSPACE_OUTPUT_DIR/inserted_masks/mode${M}_*/ -name audit.json | sort | head -1) +cl=$ITRIALSPACE_OUTPUT_DIR/nodmaisi_case_lists/mode${M}.txt +n=$(python infra/slurm/_gen_caselist.py "$audit" "$cl") # prints N cases + +sbatch --array=0-$((n-1)) \ + --export=ALL,AUDIT_PATH="$audit",CASE_LIST="$cl",OUT_DIR="$ITRIALSPACE_OUTPUT_DIR/generated_cts/mode${M}" \ + infra/slurm/synthesis/mode1_nodmaisi_array.sub +``` + +(`mode1_nodmaisi_array.sub` is generic — driven by the `AUDIT_PATH`/`CASE_LIST`/`OUT_DIR` +env vars, so it works for any mode. For modes with multiple manifests, repeat per +`audit.json`.) Validate inputs without a GPU first by running the bridge with `--dry-run` +(see [walkthrough_mode1.md](walkthrough_mode1.md)). + +Verify, per case directory: + +```bash +ls $ITRIALSPACE_OUTPUT_DIR/generated_cts/mode${M}/*/ +# synthetic_ct.nii.gz input_mask.nii.gz host_ct.nii.gz qc/*.png nodmaisi_audit.json +find $ITRIALSPACE_OUTPUT_DIR/generated_cts/mode${M} -name synthetic_ct.nii.gz | wc -l +``` + +--- + +## 5. Run size — demo vs paper/production run + +**What ships is a quick demo (small numbers), not the paper run.** Run size lives in each +mode's **trials `.sub`** (`infra/slurm/trials/mode_*.sub`). The paper value is commented +right above the active demo value, e.g.: + +```bash +# infra/slurm/trials/mode1_controlled_prevalence.sub +# N_CASES=1000 # paper run (commented for 5-case demo) ← restore this +N_CASES=5 # demo +``` + +### Demo vs paper values, and exactly what to edit + +For modes 1–10, edit the variable in the named file. The "paper run" column is the +original production configuration. + +| Mode | File (`infra/slurm/trials/…`) | Variable(s) | Demo | **Paper run** | +|------|------------------------------|-------------|------|---------------| +| 1 Controlled prevalence | `mode1_controlled_prevalence.sub` | `N_CASES` | 5 | **1000** | +| 2 Size detection curve | `mode2_size_detection_curve.sub` | `N_PER_BUCKET` | 5 | **100** (×6 buckets) | +| 3 Location sensitivity | `mode3_location_sensitivity.sub` | `N_PER_LOBE` | 5 | **100** (×5 lobes) | +| 4 Demographic strat. | `mode4_demographic_stratification.sub` | `N_PER_STRATUM` | 5 | **200** (×~4 strata) | +| 5 Counterfactual | `mode5_counterfactual.sub` | `N_CASES` (per variant) | 5 | **500** | +| 6 Cross-dataset | `mode6_cross_dataset.sub` | `N_CASES` (per dataset) | 5 | **300** | +| 7 Bootstrap confidence | `mode7_bootstrap_confidence.sub` | `N_CASES`, `N_BOOTSTRAP` | 5, 3 | **200, 20** | +| 8 Algorithm comparison | `mode8_algorithm_comparison.sub` | `N_CASES` | 5 | **500** | +| 9 Screening simulation | `mode9_screening_simulation.sub` | `N_CASES_PER_ROUND` (`N_ROUNDS`=3) | 5 | **500** | +| 10 Multi-nodule realism | `mode10_multi_nodule_realism.sub` | `N_CASES` (`MULTI_NODULE_FRACTION`=0.25) | 5 | **500** | + +For the digital-twin modes 11–13, the demo restricts datasets and caps patients/nodules; +the paper run enumerates **all 7 datasets** with no caps: + +| Mode | File | Demo | **Paper run** (restore) | +|------|------|------|--------------------------| +| 11 Isolation | `mode11_digital_twin_isolation.sub` | `DATASETS=("DLCS24")`; `--max-patients 5 --max-nodules-per-patient 1` | `DATASETS=(all 7)`; `--all-patients` (≈13k cases) | +| 12 Complete | `mode12_digital_twin_complete.sub` | `DATASETS=("DLCS24")`; `--max-patients 5` | `DATASETS=(all 7)`; `--all-patients` (≈8k cases) | +| 13 Cross | `mode13_digital_twin_cross.sub` | `HOST=("DLCS24") DONOR=("LUNA25")`; `--max-host-patients 5`; `MAX_DONOR_NODULES=5` | `HOST/DONOR=(all 7)`; `--all-host-patients --all-donor-patients`; `MAX_DONOR_NODULES=250` (≈79k cases) | + +In each `.sub` the paper values are present as commented lines (`# … # paper run`) / +the full `DATASETS=(…)` arrays — uncomment them and comment out the demo lines. + +### Quicker: override without editing files (optional) + +If the count variables are exposed as `${VAR:-default}` (ask the maintainers / see the +`.sub`), you can override per submission instead of editing: + +```bash +N_CASES=1000 infra/slurm/run_pipeline.sh 1 trials +N_PER_BUCKET=100 infra/slurm/run_pipeline.sh 2 trials +MAX_DONOR_NODULES=250 infra/slurm/run_pipeline.sh 13 trials +``` + +> **Heads-up:** the paper run is large (mode 13 alone ≈ 79k cases) and the synthesis stage +> is GPU-bound (~1.5–3 min/case). Scale up deliberately and use the array/chunking in the +> SLURM scripts. + +--- + +## 6. Monitoring + +```bash +squeue -u $USER # queue +sacct -u $USER -S today --format=JobID,JobName%22,State,Elapsed,ExitCode +tail -f logs/_.out # live log +``` +Logs are written to `logs/` in the repo (gitignored; kept via `.gitkeep`). + +--- + +## 7. Verified smoke-test result (reference) + +All 13 modes were run end-to-end at the smoke size in the `itrialspace` env on an A6000: + +| Stage | Modes 1–10 | Modes 11/12/13 | +|-------|-----------|----------------| +| Trials | 10/10 manifests | 5 / 7 / 5 rows | +| Insertion | 35/35 tasks, masks + audits | 5 masks each | +| Synthesis | 50 synthetic CTs (5/mode) | 5 CTs each | + +> **Mode 10 note:** it is the only mode that creates **two sub-cohorts** (75% +> single-nodule + 25% multi-nodule). At 5 cases that's 4 single + 1 multi, so it has two +> `audit.json` files; synthesize **both** to get all 5 CTs (the helper in §1 and the loop +> in §4 do this automatically). + +--- + +## 8. Troubleshooting + +| Symptom | Cause / fix | +|---------|-------------| +| Job "COMPLETED" in 0s but no output | Submitted from outside the repo root, or `logs/` missing → `env.sh` not found. Submit from repo root. | +| `env.sh: No such file or directory` | SLURM copies the script to a spool dir; the scripts locate `env.sh` by walking up from `$SLURM_SUBMIT_DIR` — submit from the repo (or a subdir of it). | +| `ModuleNotFoundError` (torch/pytest/…) | The env is shadowed by `~/.local`. Jobs set `PYTHONNOUSERSITE=1` automatically; for manual runs, prefix `PYTHONNOUSERSITE=1`. | +| `CUDNN_STATUS_NOT_INITIALIZED` / `libcudnn.so.9 not found` | torch's pip CUDA libs not on the loader path → handled by `env.sh`. If you rebuilt the env, ensure only the `*-cu12` nvidia packages are installed (no stray `*-cu13`). | +| Synthesis: "No cases found" | The case list must contain **mask-filename stems**, not the audit's integer `case_id`. Use `infra/slurm/_gen_caselist.py`. | +| Wrong env activated | Set `ITRIALSPACE_CONDA_ENV` in `.env`. | + +See also: [walkthrough_mode1.md](walkthrough_mode1.md) (narrated single-mode walkthrough), +[configuration.md](configuration.md), [installation.md](installation.md), +[infra/slurm/README.md](../infra/slurm/README.md). diff --git a/itrialspace/blinded_doc/trial_modes.md b/itrialspace/blinded_doc/trial_modes.md new file mode 100644 index 0000000000000000000000000000000000000000..0e9076aefc820093114e4f9955c9c04bc6e5436a --- /dev/null +++ b/itrialspace/blinded_doc/trial_modes.md @@ -0,0 +1,31 @@ + + +# Trial modes + +`its-trials --mode ` generates cohort manifests. The 13 modes: + +| # | Mode name | Purpose | +|---|-----------|---------| +| 1 | `controlled_prevalence` | Vary cancer prevalence | +| 2 | `size_detection_curve` | Detection sensitivity by nodule size (FROC) | +| 3 | `location_sensitivity` | Detection by anatomical location (lobe) | +| 4 | `demographic_stratification` | Performance across demographics | +| 5 | `counterfactual` | Same patient ± nodule | +| 6 | `cross_dataset` | Cross-dataset generalization | +| 7 | `bootstrap_confidence` | Statistical confidence intervals | +| 8 | `algorithm_comparison` | Standardized model comparison | +| 9 | `screening_simulation` | Multi-round with prevalence decay | +| 10 | `multi_nodule` | Multi-nodule context impact (companions) | +| 11 | `digital_twin_isolation` | Per-nodule isolation within host anatomy | +| 12 | `digital_twin_complete` | All native nodules per CT scan | +| 13 | `digital_twin_cross` | Cross-patient host anatomy + donor nodules | + +Modes 11–13 (digital twins) match at the **CT-scan level** (`host_ct_path == +donor_ct_path`), enabling task-level fidelity comparison of AI on real vs. synthetic +versions of the same anatomy. + +```bash +its-trials --mode size_detection_curve --n-per-bucket 100 \ + --output-dir "$ITRIALSPACE_OUTPUT_DIR/manifests/mode2" +its-trials --help # all per-mode options +``` diff --git a/itrialspace/blinded_doc/vlm_eval.md b/itrialspace/blinded_doc/vlm_eval.md new file mode 100644 index 0000000000000000000000000000000000000000..c12ebc2a856f83d191f6e2730ba732087544028a --- /dev/null +++ b/itrialspace/blinded_doc/vlm_eval.md @@ -0,0 +1,296 @@ + + +# VLM evaluation — vision-language models on lung-nodule CT + +`itrialspace.evaluation.vlm_eval` evaluates **vision-language models (VLMs)** on lung-nodule +CT slices — zero-shot, on **synthetic** (iTrialSpace-generated) and **real** CTs. + +- **Models (3):** **BiomedCLIP** (contrastive, `open_clip`), **LLaVA-Med** (7B generative), + **MedGemma** (4B generative). BiomedCLIP is light; the two generative models are heavy. +- **Tasks (3):** **presence** (binary), **lobe** (5-class localisation), **size** (4-class bucket). +- **Image conditions (4):** `plain`, `bbox`, `contour`, `bbox_contour` — "spatial-guidance" + overlays that test whether marking the lesion changes VLM accuracy. +- **Optional extra**, GPU-backed. Module-driven (no console script). + +## Pipeline + +``` +manifests + generated CTs ─┐ ┌─ run_biomedclip ─┐ + (synthetic) ├─ build_dataset ─────┤ run_llava_med ├─ metrics ─ cross_model +profiles + raw CTs ────────┘ build_real_dataset └─ run_medgemma ─┘ + plots _comparison + → eval_dataset.csv + + slices/ (+ overlays via --overlays) +``` + +`runners/run_conditions.py` wraps a model across all 4 image conditions; `run_all.py` chains +build → infer → metrics → plots. + +> **Implementation reference.** For the architecture, data model, module responsibilities, and +> extension points of this subsystem, see [vlm_eval_implementation.md](vlm_eval_implementation.md). + +### Ground truth + +`eval_dataset.csv` carries the label for each task: `ground_truth_presence` +(`present`/`absent`), `ground_truth_lobe` (5 classes: `right_lung_{upper,middle,lower}_lobe`, +`left_lung_{upper,lower}_lobe`), and `ground_truth_size_bucket` (`<5mm`, `5-10mm`, `10-20mm`, +`>20mm`). For **synthetic** cases the labels are **known by construction** (insertion lobe + +chosen effective diameter; `absent` for the nodule-free counterfactual cases); for **real** +cases they come from the source-dataset annotations (lobe normalised, diameter binned, all +`present`). Scoring: `correct = (prediction == ground_truth)`, accuracy = mean, per condition. +Full details in the [dataset card](dataset_card.md#vlm-ground-truth). + +--- + +## 1. Prerequisites + +```bash +conda activate itrialspace +pip install -e ".[vlm]" # transformers, open_clip_torch, nibabel, pillow, matplotlib, seaborn +# PyTorch (CUDA build) is separate — see docs/installation.md +cp .env.example .env # ITRIALSPACE_DATA_DIR / _OUTPUT_DIR +``` + +- **GPU** required for LLaVA-Med / MedGemma; BiomedCLIP runs on GPU or (slowly) CPU. +- **Model weights** load from **Hugging Face** by default (`google/medgemma-…`, the BiomedCLIP + open_clip id, the LLaVA-Med id) — no bundled weights dir. Ensure HF access / a warm + `~/.cache/huggingface` (or pass `--cache-dir`); pass a **local checkpoint** via each model's + `model_id` if you have one offline. +- **MedGemma** needs cuDNN 9 on `LD_LIBRARY_PATH` — handled automatically by `infra/slurm/env.sh`. + +--- + +## 2. End-to-end demo (extract slices → run a VLM) + +This demo runs the whole VLM workflow on the **demo pipeline outputs** in +`$ITRIALSPACE_OUTPUT_DIR` (e.g. `/scratch/.../outputs_iTrialSpace/`), which holds the 5-case-per-mode +`generated_cts/`, `manifests/`, and `inserted_masks/` from a demo pipeline run (see +[running_the_pipeline.md](running_the_pipeline.md)). It's a **small smoke run**, not the paper run +(§4 scales it up). + +### SLURM jobs — build → run → analyze + +The whole workflow is three env-driven jobs in +[`infra/slurm/vlm_eval/`](../infra/slurm/vlm_eval/) (full guide: its +[README](../infra/slurm/vlm_eval/README.md)). Defaults = this small demo. + +```bash +# 1) BUILD demo eval sets (synthetic modes 1–3, + a small real set) +sbatch infra/slurm/vlm_eval/build_dataset.sub # synthetic · lung_axial +VLM_SET=real sbatch infra/slurm/vlm_eval/build_dataset.sub # real · lung_axial +# (add PROFILE=lung_axial_medgemma to also build the MedGemma profile) + +# 2) RUN a model across all 4 conditions × 3 tasks +B=$ITRIALSPACE_OUTPUT_DIR/vlm_eval_demo +MODEL=biomedclip EVAL_DIR=$B/lung_axial sbatch infra/slurm/vlm_eval/run_vlm.sub +# MODEL=llava_med | medgemma (MedGemma → EVAL_DIR=$B/lung_axial_medgemma) + +# 3) ANALYZE (tables, figures, stats, report.md) +sbatch infra/slurm/vlm_eval/analyze.sub # → $B/eval_analysis/report.md +``` + +Build/analyze run on CPU (`defq`); `run_vlm` on GPU (`vram48`) — override with `sbatch -p `. +Chain with `--dependency=afterok:` for one-shot submission (see the README). + +### The two steps it runs (do them by hand to learn the flow) + +```bash +conda activate itrialspace +set -a; . ./.env; set +a # ITRIALSPACE_OUTPUT_DIR = outputs_iTrialSpace + +# STEP 1 — EXTRACT VLM SLICES from the demo synthetic CTs +# reads manifests + locates each case's synthetic_ct under --ct-base, extracts a +# lesion-centred axial slice (+ bbox/contour/bbox_contour overlays via --overlays) +python -m itrialspace.evaluation.vlm_eval.build_dataset \ + -m "$ITRIALSPACE_OUTPUT_DIR"/manifests/mode1_*/*.csv \ + "$ITRIALSPACE_OUTPUT_DIR"/manifests/mode2_*/*.csv \ + --ct-base "$ITRIALSPACE_OUTPUT_DIR/generated_cts" \ + --mask-base "$ITRIALSPACE_OUTPUT_DIR/inserted_masks" \ + --output-dir "$ITRIALSPACE_OUTPUT_DIR/vlm_eval_demo/lung_axial" \ + --profile lung_axial --overlays --workers 4 +# → writes eval_dataset.csv + slices/ (+ overlay variants) + +# STEP 2 — RUN A VLM on the extracted slices (BiomedCLIP = lightest) +python -m itrialspace.evaluation.vlm_eval.run_biomedclip \ + --dataset-csv "$ITRIALSPACE_OUTPUT_DIR/vlm_eval_demo/lung_axial/eval_dataset.csv" \ + --output-dir "$ITRIALSPACE_OUTPUT_DIR/vlm_eval_demo/lung_axial/biomedclip" \ + --tasks presence lobe size +# → presence/lobe/size_results.csv per condition + +# (other models: runners.run_llava_med / runners.run_medgemma; all 4 conditions at once: +# python -m itrialspace.evaluation.vlm_eval.runners.run_conditions --model biomedclip ...) +``` + +### Scale it to the larger / full dataset + +The **same three jobs** scale to the full study — only the env vars change. On the released data +the eval sets and frozen splits already ship under `$ITRIALSPACE_DATA_DIR/vlm_dataset/`, so you +usually **skip the build** and score a fixed split: + +```bash +B=$ITRIALSPACE_DATA_DIR/vlm_dataset/synthetic +S=$ITRIALSPACE_DATA_DIR/vlm_dataset/splits/release_v1_full.synthetic.txt +MODEL=biomedclip CASE_IDS=$S EVAL_DIR=$B/lung_axial sbatch infra/slurm/vlm_eval/run_vlm.sub +MODEL=llava_med CASE_IDS=$S EVAL_DIR=$B/lung_axial sbatch infra/slurm/vlm_eval/run_vlm.sub +MODEL=medgemma CASE_IDS=$S EVAL_DIR=$B/lung_axial_medgemma sbatch infra/slurm/vlm_eval/run_vlm.sub +RESULTS=$ITRIALSPACE_DATA_DIR/vlm_dataset SPLIT=release_v1_full sbatch infra/slurm/vlm_eval/analyze.sub +``` + +To **regenerate** the full eval sets from scratch, point `build_dataset.sub` at all 13 modes / +all 7 datasets and both profiles (`VLM_MODES`, `VLM_SET=real VLM_MAX="" VLM_DATASETS=…`, +`PROFILE=lung_axial_medgemma`, `EVAL_DIR=$ITRIALSPACE_DATA_DIR/vlm_dataset//`). The +demo→full mapping is one knob per axis — see the +[SLURM README](../infra/slurm/vlm_eval/README.md#scaling-to-the-full--curated-dataset). + +--- + +## 3. Dataset layout (public release) + +The released VLM dataset lives under `$ITRIALSPACE_DATA_DIR/vlm_dataset/`, split into +**synthetic** (modes 1–13, standard + digital-twin merged) and **real** (7 datasets): + +``` +vlm_dataset/ +├── synthetic/ # 42,858 cases +│ ├── lung_axial/ # BiomedCLIP + LLaVA-Med +│ │ ├── eval_dataset.csv # one row per case: paths + ground-truth columns +│ │ ├── slices//… # lesion-centred slices: center + z±1, × plain/bbox/contour/bbox_contour +│ │ ├── biomedclip/ llava_med/ # per-condition {presence,lobe,size}_results.csv + comparison/ +│ ├── lung_axial_medgemma/ # MedGemma (3-channel windowing) — same structure + medgemma/ +│ └── cross_model_comparison/ # cross-model accuracy/deltas/summary +└── real/ # 13,087 cases (7 datasets, no NLST3D) — same structure +``` + +(The demo in §2 writes to `$ITRIALSPACE_OUTPUT_DIR/vlm_eval_demo[_real]/` instead, to keep it +separate from the released set.) + +Profiles (`--profile`): `lung_axial` (default, BiomedCLIP/LLaVA), **`lung_axial_medgemma`** +(MedGemma's 3-channel windowing), plus `mediastinal_axial`, `bone_axial`, `lung_coronal`, +`lung_sagittal`, `lung_axial_npy`. + +--- + +## 4. Reproduce the full (paper) run + +The demo is intentionally tiny. The published study evaluates **all 3 models** under **all 4 +conditions** on **all 13 synthetic trial modes** and the **real-CT** datasets. To reproduce: + +1. **Generate the full synthetic data first** (production case counts, not the 5-case demo) — + see [running_the_pipeline.md](running_the_pipeline.md) §5; this fills + `$ITRIALSPACE_OUTPUT_DIR/{manifests,generated_cts,inserted_masks}` for all modes. +2. **Build the full eval datasets** — `build_dataset.sub` for each set × profile (all 13 modes / + all 7 datasets), into the public layout `vlm_dataset/{synthetic,real}//`. See the + [SLURM README](../infra/slurm/vlm_eval/README.md#scaling-to-the-full--curated-dataset). +3. **Run every model × condition** — `run_vlm.sub` per model (BiomedCLIP + LLaVA-Med on + `lung_axial`; MedGemma on `lung_axial_medgemma`), optionally on a frozen split via `CASE_IDS`. +4. **Analyse** — one command produces every table, figure, and statistic: + + ```bash + python -m itrialspace.evaluation.vlm_eval.eval_analysis \ + --results $ITRIALSPACE_DATA_DIR/vlm_dataset --split release_v1_full --out analysis/ + ``` + + The **`eval_analysis`** suite auto-discovers whatever models/conditions/tasks are present + (so it works on the full dataset *and* a tiny demo run) and writes `analysis/`: + - `tables/` — accuracy, Δ-vs-plain, per-mode / per-dataset / per-size / per-lobe breakdowns, + confusion matrices, per-class accuracy, bootstrap CIs, McNemar significance (CSV). + - `figures/` — accuracy-by-condition, Δ bars, confusion heatmaps, breakdown bars (PNG + PDF). + - `report.md` — the assembled report. + + (`comparison.py` / `cross_model_comparison.py` remain for quick per-run condition deltas.) + +> **SLURM jobs:** the whole flow is three env-driven jobs — +> [`build_dataset.sub` → `run_vlm.sub` → `analyze.sub`](../infra/slurm/vlm_eval/README.md) — the +> same ones used for the demo (§2), pointed at the full data. (The old per-shard +> `vlm_*_ext`/`postfix`/`overlay_build` scripts for the pre-release split layout have been +> removed in favour of these.) + +> **The released VLM dataset** ships as `vlm_dataset/{synthetic,real}/` (the layout in §3) — +> see the [dataset card](dataset_card.md). Drop it under `$ITRIALSPACE_DATA_DIR/vlm_dataset/` +> and the runners pick it up, or regenerate it from the raw CTs with the steps above. + +--- + +## 4a. Reporting convention — keeping released numbers aligned + +When you aggregate results for a paper/report, **score the same set of cases in every task** so all +reported accuracies share one N. The rule: + +> **Report accuracy on the cases that have a completed prediction in *every* (task × condition × +> model).** Take the intersection of `case_id` across all the result CSVs you are comparing; drop +> any case that is missing from one of them; report that single N everywhere. + +For the **released dataset this is the full case count** (42,858 synthetic / 13,087 real) — every +`eval_dataset.csv` row is complete for presence, lobe, and size. You only get a *smaller* N if some +runs are unfinished (a model/condition still missing predictions), in which case the intersection +keeps the comparison honest instead of silently averaging different case sets per task. + +> **Why the paper says 42,382, not 42,858.** Same rule, earlier snapshot: at paper time 334 mode-13 +> cases (plus a few re-extracted later) had slices on disk but **inference not yet run**, so they +> were excluded to keep N equal across tasks. Reconciliation: **42,382** = inference-complete (paper +> tables) · 42,716 = slices extracted on disk then · **42,858** = the finished release (inference +> complete for all cases). See the [dataset card § Reporting convention](dataset_card.md#reporting-convention-evaluation-n--read-before-comparing-to-the-paper). + +Helper (use it in any aggregation script so the convention is enforced, not assumed): + +```python +import pandas as pd +from itrialspace.evaluation.vlm_eval.metrics import common_case_ids + +# one result frame per (task × condition × model) you want to compare +frames = [pd.read_csv(p) for p in result_csvs] +keep = common_case_ids(frames) # cases scored in *all* of them +frames = [df[df["case_id"].isin(keep)] for df in frames] +print("reported N =", len(keep)) # the single N for every table +``` + +`comparison.py` and `cross_model_comparison.py` print this `reported N` so it lands in the logs and +summary JSON alongside the accuracies. + +### Frozen splits — the exact cases reported on + +The release ships the case sets as immutable, checksummed files under +`vlm_dataset/splits/` (one **canonical uid** per line — `mode/case`, condition-independent — +plus `splits.json` with counts + SHA-256 + provenance + code commit): + +| Split | Synthetic | Real | Scope | +|-------|----------:|-----:|-------| +| `release_v1` | 42,858 | 13,087 | all 3 models × `plain` × 3 tasks (headline numbers) | +| `release_v1_full` | 41,502 | 13,047 | all 3 models × all 4 conditions × 3 tasks (condition tables) | + +**Run on exactly a split** — every runner takes `--case-ids`: + +```bash +python -m itrialspace.evaluation.vlm_eval.runners.run_conditions \ + --model biomedclip --run-all-conditions \ + --dataset-csv $ITRIALSPACE_DATA_DIR/vlm_dataset/synthetic/lung_axial/eval_dataset.csv \ + --output-dir out/biomedclip \ + --case-ids $ITRIALSPACE_DATA_DIR/vlm_dataset/splits/release_v1.synthetic.txt +``` + +**(Re)generate a split** (reproducible — the `sha256` must match): + +```bash +python -m itrialspace.evaluation.vlm_eval.make_split \ + --name release_v1 --set synthetic \ + --out-dir $ITRIALSPACE_DATA_DIR/vlm_dataset/splits \ + --results-glob "$ITRIALSPACE_DATA_DIR/vlm_dataset/synthetic/lung_axial/*/plain/*_results.csv" \ + "$ITRIALSPACE_DATA_DIR/vlm_dataset/synthetic/lung_axial_medgemma/medgemma/plain/*_results.csv" +``` + +Full details and verification: `vlm_dataset/splits/README.md`. + +--- + +## 5. Troubleshooting + +| Symptom | Fix | +|---------|-----| +| `ModuleNotFoundError: open_clip/transformers` | `pip install -e ".[vlm]"`. | +| Model download fails / offline | warm `~/.cache/huggingface` or pass `--cache-dir`; or set each model's `model_id` to a local checkpoint. | +| MedGemma cuDNN / `libcudnn.so.9` errors | run via `infra/slurm/*` (env.sh puts cuDNN on `LD_LIBRARY_PATH`); use the `lung_axial_medgemma` profile. | +| CUDA OOM on generative models | use a 48 GB GPU (`vram48`); reduce batch/cases; BiomedCLIP needs far less. | +| Empty / skipped cases at build | the case's CT/mask isn't under `--ct-base`/`--mask-base` (synthetic) or `$ITRIALSPACE_DATA_DIR` (real). | +| Slow CPU run | BiomedCLIP works on CPU but is slow; generative models effectively require GPU. | + +See also: [running_the_pipeline.md](running_the_pipeline.md), +[evaluation_external_dependencies.md](evaluation_external_dependencies.md). diff --git a/itrialspace/blinded_doc/vlm_eval_implementation.md b/itrialspace/blinded_doc/vlm_eval_implementation.md new file mode 100644 index 0000000000000000000000000000000000000000..0e4b40c45db87b3518b9788030adce5e1bfce25c --- /dev/null +++ b/itrialspace/blinded_doc/vlm_eval_implementation.md @@ -0,0 +1,265 @@ + + +# VLM evaluation — implementation reference + +This is the **engineering/architecture reference** for the vision-language-model (VLM) +evaluation subsystem (`itrialspace.evaluation.vlm_eval`). It documents the design, the +data model, every module's responsibility, and the extension points. + +For task-oriented instructions (how to run a demo, reproduce the study, troubleshoot) +see the user guide [vlm_eval.md](vlm_eval.md); for the released numbers see +[vlm_results.md](vlm_results.md); for the data contract see +[dataset_card.md](dataset_card.md). + +--- + +## 1. Scope and design goals + +The subsystem evaluates three zero-shot VLMs — **BiomedCLIP**, **LLaVA-Med**, and +**MedGemma** — on three clinical tasks (**presence**, **lobe**, **size**) over four image +**conditions** (`plain`, `bbox`, `contour`, `bbox_contour`), on both **synthetic** and +**real** lung-nodule CT. It is built around five principles: + +1. **Single tidy data contract.** Every model run emits the same row schema; every analysis + is a group-by over one long table. No bespoke per-model parsing downstream. +2. **Stable identity.** A case is identified by a **canonical uid** derived from its slice + path — never the non-unique `case_id` index in the CSVs (§4). +3. **Reproducible, fixed reporting sets.** Accuracy is reported on a frozen, checksummed + **split** so reruns and re-reports score the same cases (§7). +4. **Auto-discovery.** Tools infer which models/conditions/tasks are present, so the *same* + code serves the full released dataset and a tiny demo run. +5. **Portable & secret-free.** All paths come from `ITRIALSPACE_DATA_DIR`/`settings`; the + HuggingFace token comes from `.env` (`HF_TOKEN`), never from code (§9). + +--- + +## 2. Architecture at a glance + +``` + ┌──────────────────────── Stage 1: dataset construction ────────────────────────┐ + manifests / profiles ──▶│ build_dataset (synthetic) · build_real_dataset (real) │ + generated_cts / masks │ └─ slice_extractor (centre-slice + z±1) · overlay (bbox/contour) │──▶ eval_dataset.csv + raw_ct / nodule_seg │ └─ preprocess_profiles (lung_axial / lung_axial_medgemma) │ + slices/*.png + └───────────────────────────────────────────────────────────────────────────────┘ + ┌──────────────────────── Stage 2: inference ──────────────────────────────────┐ + eval_dataset.csv ──────▶│ runners/run_conditions ─▶ run_biomedclip · runners/run_llava_med · run_medgemma│──▶ //_results.csv + │ models/{biomedclip,llava_med,medgemma} · prompt_templates · parsers │ + │ inference_cache (resume) │ + └───────────────────────────────────────────────────────────────────────────────┘ + ┌──────────────────────── Stage 3: scoring & reporting ────────────────────────┐ + *_results.csv ─────────▶│ splits / make_split (frozen sets) · metrics · comparison / cross_model │──▶ accuracy / deltas / splits.json + └───────────────────────────────────────────────────────────────────────────────┘ + ┌──────────────────────── Stage 4: analysis suite ─────────────────────────────┐ + *_results.csv + split ─▶│ eval_analysis: load ─▶ tables · stats · plots ─▶ report │──▶ tables/ + figures/ + report.md + └───────────────────────────────────────────────────────────────────────────────┘ +``` + +| Layer | Modules | Responsibility | +|-------|---------|----------------| +| Dataset construction | `build_dataset`, `build_real_dataset`, `build_negative_dataset`, `slice_extractor`, `overlay`, `preprocess_profiles` | Turn 3-D CTs + masks into 2-D eval slices + ground truth | +| Model adapters | `models/biomedclip_model`*, `models/llava_med`, `models/medgemma` | Uniform `predict`/`predict_batch` over each backbone | +| Inference orchestration | `runners/run_conditions`, `run_biomedclip`, `runners/run_llava_med`, `runners/run_medgemma`, `run_all` | Drive a model across conditions/tasks; write result CSVs | +| Prompting & parsing | `prompt_templates`, `parsers` | Task prompts + robust free-text → label parsing | +| Scoring | `metrics`, `comparison`, `cross_model_comparison`, `inference_cache` | Accuracy/F1, condition deltas, resume | +| Reporting sets | `splits`, `make_split` | Canonical uid, frozen checksummed splits, `--case-ids` | +| Analysis suite | `eval_analysis/{load,tables,stats,plots,report}` | Full tables, figures, statistics, markdown report | + +\* `biomedclip_model.py` lives at the package root; the generative adapters live under +`models/`. + +--- + +## 3. The two stages of data, and what "results" mean + +- A **case** is one nodule on one CT. Synthetic cases come from a trial-mode manifest (an + inserted donor nodule on a host CT); real cases come from a dataset's nodule profile. +- Each case yields, per **preprocessing profile**, **3 z-slices** (`z`, `z-1`, `z+1`) × + **4 conditions** = up to 12 PNGs. **Evaluation uses the centre (`z`) slice**; `z±1` are + context that MedGemma may stack (BiomedCLIP/LLaVA-Med use the centre slice only). +- A **run** scores one `(model × condition × task)` and writes one + `//_results.csv`, one row per case, with `prediction`, + `ground_truth`, `correct`, and the slice `image_path`. + +--- + +## 4. Data model + +### 4.1 `eval_dataset.csv` (Stage 1 output) +One row per case (per profile). Key columns: + +| Column | Meaning | +|--------|---------| +| `png_path`, `png_bbox_path`, `png_contour_path`, `png_bbox_contour_path` | centre-slice PNG per condition | +| `slice_z`, `slice_method`, `preprocess_profile` | extraction provenance | +| `ground_truth_presence` | `present` / `absent` | +| `ground_truth_lobe` | 5 classes (`right_lung_upper_lobe` … `left_lung_lower_lobe`) | +| `ground_truth_size_bucket` | `<5mm`, `5-10mm`, `10-20mm`, `>20mm` | +| `mode` / `dataset`, `effective_diam_mm`/`nodule_mean_diam_mm`, `insertion_lobe`, `population_type` | metadata for breakdowns | + +**Ground-truth derivation.** Synthetic labels are **known by construction** (insertion lobe; +`effective_diam_mm` binned to a size bucket; `present` unless a deliberately nodule-free +case). Real labels come from the source dataset's annotations (lobe normalised to the 5 +canonical classes via `prompt_templates.normalise_lobe`; diameter binned via +`diameter_to_size_bucket`; all `present`). + +### 4.2 Canonical uid — the only stable key +The `case_id` column in both `eval_dataset.csv` and the result CSVs is a **non-unique +positional index** (it restarts per shard). The stable identity is the slice path with the +condition sub-dir and extension stripped, computed by +[`splits.canonical_uid`](../src/itrialspace/evaluation/vlm_eval/splits.py): + +``` +…/slices/mode1_controlled_prevalence/NLST_cohort__C0000.png ┐ +…/slices/mode1_controlled_prevalence/bbox/NLST_cohort__C0000.png ┘ → mode1_controlled_prevalence/NLST_cohort__C0000 +``` + +so one case maps to one uid across all four conditions, and results join cleanly to +`eval_dataset.csv`. **All joins, intersections, and de-duplication use the uid, never +`case_id`.** + +--- + +## 5. Stage 1 — dataset construction + +- **`slice_extractor`** locates the nodule centroid (from the inserted/nodule mask), extracts + the axial centre slice and `z±1`, converts to radiological orientation, applies the HU + window, and drops artefact slices. `preprocess_profiles` defines the windows: + `lung_axial` (BiomedCLIP/LLaVA-Med) and `lung_axial_medgemma` (3-channel z-stack). +- **`overlay`** renders the spatial-guidance variants from the mask: `bbox` (bounding box), + `contour` (segmentation outline), `bbox_contour` (both). `VALID_CONDITIONS` is the single + source of truth for the condition set. +- **`build_dataset`** (synthetic) resolves each manifest case's `synthetic_ct` + mask, + extracts slices, draws overlays (`--overlays`), and writes `eval_dataset.csv` + (multiprocessing via `--workers`). **`build_real_dataset`** does the same from real + profiles + `raw_ct/` + `nodule_seg/`. **`build_negative_dataset`** samples nodule-free lung + slices for presence negatives. + +Output: `vlm_dataset/{synthetic,real}//{eval_dataset.csv, slices/…}`. + +--- + +## 6. Stage 2 — inference + +- **Model adapters** (`models/…`) present a uniform interface (lazy weight loading; batched + `predict`). BiomedCLIP is contrastive (open_clip; scores label prompts); LLaVA-Med and + MedGemma are generative (`transformers`), prompted via `prompt_templates.get_generative_prompt`. +- **`parsers`** turns free-text generative answers into a label + a `ParseResult` status + (handles synonyms, negation, partial matches) so scoring is robust. +- **`runners/run_conditions`** is the orchestrator: it remaps `png_path` to the chosen + condition column, optionally restricts to a split (`--case-ids`, §7), and dispatches to the + per-model runner for each condition. `run_all` chains the full matrix. +- **`inference_cache`** lets a run resume by reusing prior rows for unchanged cases + (`--skip-existing`). + +Output: `//_results.csv` (+ per-mode and `aggregate/` copies). + +--- + +## 7. Stage 3 — reporting sets and the reporting-N convention + +> **Convention.** Report accuracy on the cases scored in *every* `(model × condition × +> task)` you compare — the canonical-uid **intersection** — so every number shares one N. + +- **`metrics.common_case_ids`** computes that intersection (keyed on the uid). +- **`splits` / `make_split`** freeze it as a checksummed artifact under `vlm_dataset/splits/`: + a sorted uid list per set plus `splits.json` (count, SHA-256, source globs, git commit). + Two ship with the release: + + | Split | Synthetic | Real | Scope | + |-------|----------:|-----:|-------| + | `release_v1` | 42,858 | 13,087 | all models × `plain` × 3 tasks | + | `release_v1_full` | 41,502 | 13,047 | all models × **4 conditions** × 3 tasks | + +- Every runner accepts **`--case-ids `** to score exactly that set. +- `comparison` / `cross_model_comparison` produce per-condition deltas for a single run. + +This is also the reconciliation point for the paper: the submission's synthetic N = 42,382 +is the *same rule* at a pre-inference snapshot; the release completes inference, so +`release_v1` = 42,858. See [dataset_card.md](dataset_card.md#reporting-convention-evaluation-n--read-before-comparing-to-the-paper). + +--- + +## 8. Stage 4 — the `eval_analysis` suite + +A reusable engine that turns result CSVs into a full report: + +- **`load`** — auto-discovers condition-level `*_results.csv` under any root, joins each row + to its `eval_dataset.csv` metadata, applies a split, and returns **one tidy long + DataFrame** (`set, model, condition, task, uid, prediction, ground_truth, correct, + mode, source_dataset, lobe, size_bucket, diam_mm, population`). +- **`tables`** — accuracy, Δ-vs-baseline, breakdowns (mode / dataset / size / lobe), + confusion, per-class. +- **`stats`** — percentile **bootstrap CIs** and paired **McNemar** significance of each + condition vs the baseline. +- **`plots`** — publication-style figures (top/right spines removed, shared y-axis with + labels on the first panel, blue-shade palette, 300-dpi PNG + vector PDF). +- **`report`** — orchestrates everything into `out/{tables/*.csv, figures/*, report.md}`. + +```bash +python -m itrialspace.evaluation.vlm_eval.eval_analysis \ + --results $ITRIALSPACE_DATA_DIR/vlm_dataset --split release_v1_full --out analysis/ +# demo: --results out/demo (omit --split; auto-discovers what's present) +``` + +--- + +## 9. Configuration, portability, and secrets + +- **Paths** are never hardcoded. `itrialspace.config.settings` resolves everything from + `ITRIALSPACE_DATA_DIR` / `ITRIALSPACE_OUTPUT_DIR` (with `.env` loaded once at import; real + environment variables win). `tools/check_portability.py` gates against stray absolute paths. +- **HuggingFace token.** Gated models (MedGemma; some LLaVA-Med checkpoints) read the token + from the environment via `settings.hf_token()` (`.env` → `HF_TOKEN`, or the legacy + `HUGGING_FACE_HUB_TOKEN`) and pass it to `from_pretrained`. **No token is ever committed**; + `.env` is gitignored. To share, clear the value — each user supplies their own. BiomedCLIP + is public and needs none. +- **Weights** are not bundled; models load from the HuggingFace cache (or a local + `--model-id`). + +--- + +## 10. Extension points + +| To add… | Do this | +|---------|---------| +| **a model** | Add an adapter under `models/` with `predict`/`predict_batch`; register a dispatch branch in `runners/run_conditions._run_model`. | +| **a task** | Add a `TaskDefinition` to `prompt_templates.ALL_TASKS` (+ generative prompt) and a parser in `parsers`. | +| **a condition** | Extend `overlay.VALID_CONDITIONS` + the draw function and the `_CONDITION_COLUMNS` map in `run_conditions`. | +| **a preprocessing profile** | Add a `PreprocessProfile` in `preprocess_profiles`. | +| **an analysis breakdown** | Add the column to `eval_analysis.load` metadata and a `breakdown_table(by=…)` call in `report`. | + +--- + +## 11. Quality gates + +- **Lint/format:** `ruff` + `black` (CI; repo standard). +- **Portability:** `tools/check_portability.py`. +- **Reproducibility:** split SHA-256 in `splits.json` — regenerate with `make_split` and the + hash must match. +- **Tests:** unit tests run under `pytest -m "not full_volume"`; full-volume/model tests are + env-gated (need data/GPU). + +--- + +## 12. Module reference + +| Module | One-line role | +|--------|---------------| +| `build_dataset.py` | Build synthetic eval dataset from trial manifests | +| `build_real_dataset.py` | Build real-CT eval dataset from nodule profiles | +| `build_negative_dataset.py` | Sample nodule-free slices (presence negatives) | +| `slice_extractor.py` | Centroid-centred axial slice extraction + HU windowing | +| `overlay.py` | bbox / contour / bbox_contour spatial-guidance overlays | +| `preprocess_profiles.py` | Named preprocessing profiles (windows, z-stack) | +| `prompt_templates.py` | Task definitions, prompts, lobe/size normalisation | +| `parsers.py` | Free-text answer → label (robust) | +| `biomedclip_model.py`, `models/llava_med.py`, `models/medgemma.py` | Model adapters | +| `run_biomedclip.py`, `runners/run_llava_med.py`, `runners/run_medgemma.py` | Per-model runners | +| `runners/run_conditions.py`, `run_all.py` | Condition/matrix orchestration | +| `inference_cache.py` | Resume support | +| `metrics.py` | Accuracy/F1/confusion + `common_case_ids` | +| `comparison.py`, `cross_model_comparison.py` | Per-condition / cross-model deltas | +| `splits.py`, `make_split.py` | Canonical uid + frozen checksummed splits | +| `report.py` | Quick single-table headline report | +| `eval_analysis/` | Full analysis suite (tables, stats, figures, report) | +``` diff --git a/itrialspace/blinded_doc/walkthrough_mode1.md b/itrialspace/blinded_doc/walkthrough_mode1.md new file mode 100644 index 0000000000000000000000000000000000000000..e90e845c25dbd026943a1716072fc8288f2b57c1 --- /dev/null +++ b/itrialspace/blinded_doc/walkthrough_mode1.md @@ -0,0 +1,170 @@ + + +# Walkthrough: 200 cases through Mode 1 (end-to-end) + +This tutorial takes **Mode 1 (`controlled_prevalence`)** from a cohort specification all +the way to synthetic CT volumes, for **200 cases**: + +``` +its-trials ──▶ manifest CSV ──▶ its-insert ──▶ inserted masks + audit.json ──▶ synthesis ──▶ synthetic CTs + (1) plan (cohort) (2) insert (label-23 combined masks) (3) generate (+ QC) +``` + +## 0. One-time setup + +```bash +cd /path/to/itrialspace +conda activate itrialspace # or your env with the deps installed +pip install -e ".[imaging]" # core + NIfTI/scipy/SimpleITK + +# Tell iTrialSpace where the data lives (the 7 datasets, host CTs, organ segs) +export ITRIALSPACE_DATA_DIR=/scratch/railabs/ft42/VLST_Project/Data/iTrialSpace +# Where outputs go (defaults to ITRIALSPACE_DATA_DIR if unset) +export ITRIALSPACE_OUTPUT_DIR=$ITRIALSPACE_DATA_DIR + +its config # sanity-check the resolved paths +``` + +> Tip: put these in a `.env` (copy `.env.example`); the SLURM scripts and config +> loaders pick it up automatically. + +--- + +## Step 1 — Plan the cohort (itrialspace → manifest) + +`its-trials` runs the trial-mode factory, builds the cohort with `CohortBuilder`, and +writes a manifest (CSV + JSON). + +```bash +its-trials \ + --mode controlled_prevalence \ + --n-cases 200 \ + --prevalence 0.05 \ + --template NLST \ + --seed 42 \ + --output-dir $ITRIALSPACE_OUTPUT_DIR/manifests/mode1_controlled_prevalence +``` + +**Produces** (filename derives from the template, e.g. `NLST_cohort.csv`): + +``` +$ITRIALSPACE_OUTPUT_DIR/manifests/mode1_controlled_prevalence/ +├── NLST_cohort.csv # 200 rows — one per case (host CT + donor nodule + placement) +├── NLST_cohort.json # same content, structured +└── _run_config.json # exact parameters used (reproducibility) +``` + +Each manifest row carries the host CT path, host organ segmentation, the donor nodule, and +the target placement (lobe / percentile / scale). Verify: + +```bash +python -c "import pandas as pd; d=pd.read_csv('$ITRIALSPACE_OUTPUT_DIR/manifests/mode1_controlled_prevalence/NLST_cohort.csv'); print(len(d),'cases'); print(d['host_dataset'].value_counts())" +``` + +Useful options: `--no-verify-paths` (skip on-disk path checks for a quick dry plan), +`--n-cases`, `--prevalence`. See `its-trials --help`. + +--- + +## Step 2 — Insert nodule masks (manifest → inserted masks) + +`its-insert run` reads the manifest, resolves host organ-segmentation volumes, and pastes +each donor nodule mask at **VISTA3D label 23** using the 5-stage placement pipeline (lobe +targeting → percentile→voxel → snap-to-mask → pleural safety → collision avoidance). +**Mask-only — no CT intensities are touched here.** + +```bash +its-insert run \ + --manifest $ITRIALSPACE_OUTPUT_DIR/manifests/mode1_controlled_prevalence/NLST_cohort.csv \ + --output-dir $ITRIALSPACE_OUTPUT_DIR/inserted_masks/mode1_controlled_prevalence \ + --trial-name mode1_controlled_prevalence \ + --seed 42 \ + --n-jobs 8 +``` + +**Produces:** + +``` +$ITRIALSPACE_OUTPUT_DIR/inserted_masks/mode1_controlled_prevalence/ +├── iTS--mode1...--C0000--host-...--src-...--nod-..._mask.nii.gz # combined label map per case +├── ... (200 masks) +└── audit.json # per-case provenance (placement, snap, pleural dist, overlap) — KEY for step 3 +``` + +- **Dry run first** (placement decisions only, nothing written): + `its-insert run --manifest ... --output-dir ... --dry-run` +- Verify a finished run: `its-insert verify --output-dir $ITRIALSPACE_OUTPUT_DIR/inserted_masks/mode1_controlled_prevalence` + +--- + +## Step 3 — Generate CTs (inserted masks → synthetic CT) + +This runs **NodMAISI** (ControlNet-conditioned rectified-flow diffusion). It **needs a +GPU**, the `synthesis` extra, and the model weights. + +```bash +pip install -e ".[synthesis]" +# torch matching your CUDA (example: cu124) — see docs/installation.md +pip install torch --index-url https://download.pytorch.org/whl/cu124 + +# Point at the NodMAISI weights (autoencoder.pt, diffusion_unet.pt, controlnet *.pt) +export NODMAISI_MODELS_DIR=/path/to/nodmaisi/models +``` + +Run the integration bridge. The `audit.json` from Step 2 is the preferred input (it links +each mask back to its host CT for the QC overlay): + +```bash +python -m itrialspace.synthesis.tools.run_itrialspace_to_ct \ + --audit $ITRIALSPACE_OUTPUT_DIR/inserted_masks/mode1_controlled_prevalence/audit.json \ + --config configs/integration.example.yaml \ + --outdir $ITRIALSPACE_OUTPUT_DIR/generated_cts/mode1_controlled_prevalence \ + --jobs 1 +``` + +(If you don't have the audit, use `--mask-root $ITRIALSPACE_OUTPUT_DIR/inserted_masks/mode1_controlled_prevalence` instead.) + +**Produces, per case:** + +``` +$ITRIALSPACE_OUTPUT_DIR/generated_cts/mode1_controlled_prevalence// +├── synthetic_ct.nii.gz # generated CT volume +├── input_mask.nii.gz # mask fed to the model (snapped to a valid grid) +├── host_ct.nii.gz # symlink to host CT (for comparison) +├── qc/qc_slice_*.png # 3-panel QC (host | synthetic+overlay | synthetic) +└── nodmaisi_audit.json # params, geometry, sanity checks, timing +``` + +Validate without a GPU first: add `--dry-run` (checks inputs/geometry, skips inference). + +--- + +## Running it on HPC (recommended for 200 cases) + +Each stage has SLURM scripts under `infra/slurm/`, cluster-portable via `infra/slurm/env.sh` +(set `ITRIALSPACE_DATA_DIR`, `ITRIALSPACE_CONDA_ENV`, partitions in your `.env`): + +```bash +# 1. plan +sbatch infra/slurm/trials/mode1_controlled_prevalence.sub +# 2. insert (CPU array job) +sbatch infra/slurm/mask_inserter/mode1_insert_masks.sub +# 3. synthesize (GPU array job; chunks automatically if >1000 cases) +infra/slurm/synthesis/submit_array_jobs.sh 1 +``` + +> Edit the `#SBATCH --partition/--account` lines for your cluster (see +> [infra/slurm/README.md](../infra/slurm/README.md)). + +--- + +## What "200 cases" means at each stage + +| Stage | Input | Output | Needs | +|-------|-------|--------|-------| +| 1. Plan | dataset index | 200-row manifest CSV/JSON | CPU, profile CSVs | +| 2. Insert | manifest + host organ segs | 200 label-23 masks + `audit.json` | CPU, host CTs/segs | +| 3. Generate | masks (+ audit) | 200 synthetic CTs + QC | **GPU + NodMAISI weights** | + +After Step 3 you can feed the synthetic CTs into evaluation — VLM +(`itrialspace.evaluation.vlm_eval`). diff --git a/itrialspace/configs/datasets.example.yaml b/itrialspace/configs/datasets.example.yaml new file mode 100644 index 0000000000000000000000000000000000000000..37d3d2d2f9eb4f8e9d951f5e863fcc24b956d0b7 --- /dev/null +++ b/itrialspace/configs/datasets.example.yaml @@ -0,0 +1,35 @@ +# iTrialSpace Dataset Registry — maps dataset name → nodule-profile CSV path. +# +# Copy to `configs/datasets.yaml` and adjust if your layout differs. Paths use the +# ${ITRIALSPACE_DATA_DIR} placeholder, which is expanded by itrialspace.config.settings +# (default: ~/.itrialspace/data). You usually only need to set ITRIALSPACE_DATA_DIR in .env. + +datasets: + + DLCS24: + csv_path: ${ITRIALSPACE_DATA_DIR}/profiles/DLCS24_nodule_profiles.csv + notes: "Binary label. Lung-RADS scores, smoking, age/sex. 2,487 nodules." + + LUNA25: + csv_path: ${ITRIALSPACE_DATA_DIR}/profiles/LUNA25_nodule_profiles.csv + notes: "Binary label. Largest dataset (6,163 nodules). Multi-nodule screening." + + LUNA16: + csv_path: ${ITRIALSPACE_DATA_DIR}/profiles/LUNA16_nodule_profiles.csv + notes: "No malignancy label. Use for reinsertion/anatomy analysis only." + + LUNGx: + csv_path: ${ITRIALSPACE_DATA_DIR}/profiles/LUNGx_nodule_profiles.csv + notes: "Benchmark challenge. 49.4% malignant." + + LNDbv4: + csv_path: ${ITRIALSPACE_DATA_DIR}/profiles/LNDbv4_nodule_profiles.csv + notes: "Malignancy is continuous float (radiologist avg 1-5). Threshold 3.0 used." + + NSCLCR: + csv_path: ${ITRIALSPACE_DATA_DIR}/profiles/NSCLCR_nodule_profiles.csv + notes: "All malignant (100%). Large tumours (median 52mm). Has staging/survival." + + IMDCT: + csv_path: ${ITRIALSPACE_DATA_DIR}/profiles/IMDCT_nodule_profiles.csv + notes: "Label is string benign/cancer. Has nodule type, PET, spiculation." diff --git a/itrialspace/configs/features.yaml b/itrialspace/configs/features.yaml new file mode 100644 index 0000000000000000000000000000000000000000..48adfc5a1faed648be9a4374f5fcfdd15455b0e8 --- /dev/null +++ b/itrialspace/configs/features.yaml @@ -0,0 +1,111 @@ +# Feature-set definitions for NoduleMap embeddings. +# Each feature set defines the columns used, their types, and preprocessing. + +feature_sets: + + # ── reinsertion_core ────────────────────────────────────────────────────── + # Safe default: uses only reinsertion_* columns (100% complete, no NaNs). + reinsertion_core: + description: "Reinsertion-only features — no NaNs, 12 columns" + numeric: + - reinsertion_lobe_cc_pct + - reinsertion_lobe_ml_pct + - reinsertion_lobe_ap_pct + - reinsertion_lung_cc_pct + - reinsertion_lung_ml_pct + - reinsertion_lung_ap_pct + - reinsertion_pleural_dist_mm + - reinsertion_airway_dist_mm + - reinsertion_nodule_diam_mm + categorical: + - reinsertion_lobe + - reinsertion_lung_side + - reinsertion_lung_zone + scaler: standard # standard | robust + imputer: none # none | median | mean + + # ── core_53 ─────────────────────────────────────────────────────────────── + # Full 53-column profile: anatomy, distances, inter-nodule, reinsertion. + # May contain NaNs in non-reinsertion columns. + core_53: + description: "All 53 core pipeline features — requires imputation" + numeric: + - nodule_mean_diam_mm + - nodule_vol_mm3 + - cranio_caudal_pct + - mediolateral_pct + - anteroposterior_pct + - lobe_cc_pct + - lobe_ml_pct + - lobe_ap_pct + - dist_to_trachea_mm + - dist_to_aorta_mm + - dist_to_heart_mm + - dist_to_esophagus_mm + - dist_to_pulmonary_vein_mm + - dist_to_superior_vena_cava_mm + - pleural_distance_mm + - airway_distance_mm + - n_nodules_in_patient + - nearest_nodule_dist_mm + - nearest_dx_mm + - nearest_dy_mm + - nearest_dz_mm + - reinsertion_lobe_cc_pct + - reinsertion_lobe_ml_pct + - reinsertion_lobe_ap_pct + - reinsertion_lung_cc_pct + - reinsertion_lung_ml_pct + - reinsertion_lung_ap_pct + - reinsertion_pleural_dist_mm + - reinsertion_airway_dist_mm + - reinsertion_nodule_diam_mm + categorical: + - lobe_name + - lung_side + - lung_zone + - central_peripheral + - reinsertion_lobe + - reinsertion_lung_side + - reinsertion_lung_zone + scaler: robust + imputer: median + +# ── Embedding model presets ──────────────────────────────────────────────── +models: + + PCA_2D: + algorithm: pca + n_components: 2 + + PCA_32: + algorithm: pca + n_components: 32 + + UMAP_2D: + algorithm: umap + n_components: 2 + n_neighbors: 30 + min_dist: 0.3 + metric: euclidean + + UMAP_16: + algorithm: umap + n_components: 16 + n_neighbors: 30 + min_dist: 0.1 + metric: euclidean + + UMAP_32: + algorithm: umap + n_components: 32 + n_neighbors: 30 + min_dist: 0.1 + metric: euclidean + + TSNE_2D: + algorithm: tsne + n_components: 2 + perplexity: 30 + learning_rate: auto + n_iter: 1000 diff --git a/itrialspace/configs/integration.example.yaml b/itrialspace/configs/integration.example.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4613a38f94a484b31b23aa0c1b4cc61d41b1a063 --- /dev/null +++ b/itrialspace/configs/integration.example.yaml @@ -0,0 +1,76 @@ +# ============================================================================ +# iTrialSpace -> NodMAISI Integration Pipeline — Configuration +# ============================================================================ + +# -- Paths to NodMAISI model components ----------------------------------- +# Paths use ${VAR} placeholders expanded by itrialspace.config.settings. +# Model weights are NOT bundled — set NODMAISI_MODELS_DIR to the directory holding +# autoencoder.pt / diffusion_unet.pt / controlnet *.pt (see docs/installation.md). +nodmaisi: + project_dir: ${ITRIALSPACE_ROOT}/src/itrialspace/synthesis + model_config: configs/config_maisi3d-rflow.json + controlnet_config: configs/infr_config_NoMAISI_controlnet.json + env_config: configs/infr_env_NoMAISI_DLCSD24_demo.json + # Model checkpoints (absolute via NODMAISI_MODELS_DIR, or relative to project_dir) + autoencoder_path: ${NODMAISI_MODELS_DIR}/autoencoder.pt + diffusion_unet_path: ${NODMAISI_MODELS_DIR}/diffusion_unet.pt + controlnet_path: ${NODMAISI_MODELS_DIR}/Experiments_NoMAISI_512xy_256z_771p25m_finetune_500epoch_best.pt + +# -- Inference parameters ------------------------------------------------- +inference: + num_inference_steps: 30 + autoencoder_sliding_window_infer_size: [80, 80, 64] + autoencoder_sliding_window_infer_overlap: 0.25 + noise_factor: 1.0 + modality: 1 # 1 = CT + seed: 42 + device: "cuda:0" + +# -- iTrialSpace mask parameters ------------------------------------------ +itrialspace: + nodule_label_value: 23 # Label value used by iTrialSpace for inserted nodules + # Base directory for resolving relative paths in iTrialSpace manifests/audits + base_dir: ${ITRIALSPACE_DATA_DIR} + # Root of iTrialSpace trial manifests (JSON/CSV with host_ct_path per case) + manifest_root: ${ITRIALSPACE_DATA_DIR}/manifests + +# -- Output structure ----------------------------------------------------- +output: + # Root for generated CTs. {trial_name} is substituted at runtime. + root: ${ITRIALSPACE_OUTPUT_DIR}/generated_cts + # Per-case subdirectory template + case_dir_template: "case_{case_id}" + # Filenames inside each case directory + synthetic_ct_name: synthetic_ct.nii.gz + input_mask_name: input_mask.nii.gz + host_ct_link_name: host_ct.nii.gz + qc_dir_name: qc + audit_name: nodmaisi_audit.json + +# -- QC settings ---------------------------------------------------------- +qc: + enabled: true + # Number of axial slices to render (evenly spaced through the nodule region) + num_slices: 3 + # Window level / width for CT display (HU) + window_center: -600 + window_width: 1500 + # PNG DPI + dpi: 150 + +# -- Geometry constraints (from NodMAISI check_input) --------------------- +geometry: + # Valid XY sizes for NodMAISI (first two dims must be equal) + valid_xy_sizes: [256, 384, 512] + # Valid Z sizes + valid_z_sizes: [128, 256, 384, 512, 640, 768] + # Target spacing for resampling if needed (null = use mask's native spacing) + target_spacing: null + # If true, resample mask to nearest valid size; if false, skip cases that don't fit + auto_resize: true + +# -- Conda / environment (for SLURM scripts) ----------------------------- +environment: + conda_module: "" + conda_env: ${ITRIALSPACE_CONDA_ENV} + monai_data_directory: ${ITRIALSPACE_ROOT}/src/itrialspace/synthesis diff --git a/itrialspace/configs/mask_inserter.example.yaml b/itrialspace/configs/mask_inserter.example.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2035657fa4cdbd99f3db7c794fd23b2868fcbdaa --- /dev/null +++ b/itrialspace/configs/mask_inserter.example.yaml @@ -0,0 +1,113 @@ +# iTrialSpace Mask Insertion Engine — defaults +# Override per-site via --config flag or INSERTER_CONFIG env var. + +# ── Lobe label mapping (VISTA3D integer labels) ───────────────────────────── +lobe_labels: + left_lung_upper_lobe: 28 + left_lung_lower_lobe: 29 + right_lung_upper_lobe: 30 + right_lung_middle_lobe: 31 + right_lung_lower_lobe: 32 + +# String ↔ integer aliases accepted in manifest ``insertion_lobe`` column. +# Keys are normalised lowercased names; values map to the canonical key above. +lobe_aliases: + lul: left_lung_upper_lobe + lll: left_lung_lower_lobe + rul: right_lung_upper_lobe + rml: right_lung_middle_lobe + rll: right_lung_lower_lobe + left_upper: left_lung_upper_lobe + left_lower: left_lung_lower_lobe + right_upper: right_lung_upper_lobe + right_middle: right_lung_middle_lobe + right_lower: right_lung_lower_lobe + +# Labels treated as "whole lung" for fallback placement. +lung_labels: [28, 29, 30, 31, 32] + +# ── Nodule output label ───────────────────────────────────────────────────── +# Integer value written into the host output mask for inserted nodule voxels. +# The intermediate binary mask (0/1) is converted to this label before writing. +# Default 23; change without code edits by overriding this value. +nodule_label_value: 23 + +# Future extension: per-nodule-type label mapping (unused for now). +# When populated, keys are nodule type strings and values are integer labels. +# Example: {"malignant": 23, "benign": 24} +nodule_type_to_label: {} + +# ── Placement parameters ──────────────────────────────────────────────────── +placement: + # Maximum search radius (voxels) when snapping an out-of-mask candidate to + # the nearest valid voxel inside the target mask. + max_snap_radius_vox: 25 + + # Minimum distance (mm) from the lung boundary that an insertion centre must + # satisfy. Set to 0 to disable. + min_pleural_dist_mm: 2.0 + + # If True, check for overlap with existing nodules in the combined mask and + # attempt to shift the placement to avoid it. + check_overlap: true + + # Maximum fraction of donor mask voxels allowed to overlap with an existing + # nodule mask before the placement is declared infeasible. + max_overlap_fraction: 0.05 + + # Maximum additional shift (voxels) attempted to resolve overlap collisions. + max_collision_shift_vox: 15 + +# ── Resampling parameters ─────────────────────────────────────────────────── +resample: + # Interpolation for binary masks: "nearest" (default) or "linear" then + # threshold. + interpolation: nearest + + # After resampling, voxels with value >= this threshold are set to 1. + binary_threshold: 0.5 + + # Remove connected components smaller than this (voxels) after resampling. + min_component_size_vox: 3 + + # Fill holes in the binary mask after resampling. + fill_holes: true + +# ── Output naming ─────────────────────────────────────────────────────────── +output: + # Flat directory — all combined masks in one folder, no subdirectories. + use_case_subdirs: false + + # Combined mask template. + # Delimiter convention: '--' separates fields, '-' separates key from value. + # Parsing: dict(f.split('-', 1) for f in stem.split('--')[1:] if '-' in f) + # Available placeholders: {trial_name}, {case_id}, {host_id}, {host_dataset}, {donor_id}. + # case_id is zero-padded to 4 digits. host_id is SHA-256[:8] when >20 chars. + combined_mask_template: "iTS--{trial_name}--C{case_id}--host-{host_id}--src-{host_dataset}--nod-{donor_id}_mask.nii.gz" + + # Whether to save individual per-nodule binary masks (in addition to the combined mask). + save_per_nodule_mask: false + + # Per-nodule mask template (only used when save_per_nodule_mask is true). + nodule_mask_template: "case_{case_id}_nodule_{nodule_idx}_mask.nii.gz" + + # Audit log filename. + audit_name: audit.json + + # Compress NIfTI outputs. + compress: true + +# ── Optional CT intensity insertion (experimental, off by default) ────────── +ct_insertion: + enabled: false + blending_mode: poisson # poisson | direct | alpha + boundary_width_mm: 2.0 + +# ── Parallelism ───────────────────────────────────────────────────────────── +parallel: + backend: loky # loky | threading | sequential + n_jobs: 1 + verbose: 10 + +# ── Reproducibility ───────────────────────────────────────────────────────── +seed: 42 diff --git a/itrialspace/configs/paths.example.yaml b/itrialspace/configs/paths.example.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2403d5cf4b3aa23e4dc43291f759f0527d87ce28 --- /dev/null +++ b/itrialspace/configs/paths.example.yaml @@ -0,0 +1,61 @@ +# iTrialSpace path layout — unified data directory. +# +# Copy to `configs/paths.yaml` and adjust if your layout differs. ${ITRIALSPACE_DATA_DIR} +# is expanded by itrialspace.config.settings (default: ~/.itrialspace/data). +# +# ${ITRIALSPACE_DATA_DIR}/ +# ├── raw_ct/{DATASET}/ CT scans (resampled NIfTI) +# ├── masks/{DATASET}/ +# │ ├── nodule_seg/ Individual nodule masks +# │ ├── combined_seg/ Combined patient masks +# │ ├── organ_seg/ VISTA3D organ segmentations (raw, deprecated) +# │ └── refined_seg/ Refined organ + body segmentations (used by default) +# ├── profiles/ Nodule profile CSVs +# └── meta/ Original dataset metadata CSVs +# +# ct_path values in profile CSVs are relative to raw_ct/, e.g. +# "DLCS24/DLCS_0001.nii.gz" → ${ITRIALSPACE_DATA_DIR}/raw_ct/DLCS24/DLCS_0001.nii.gz + +# ── Global base directory ────────────────────────────────────────────────── +base_dir: ${ITRIALSPACE_DATA_DIR} + +# ── Per-dataset configuration ────────────────────────────────────────────── +# Only override patterns/flags when they differ from the defaults: +# organ_seg_pattern: "{ct_id}_seg.nii.gz" +# nodule_seg_pattern: "{annotation_id}.nii.gz" +# combined_mask_pattern: "{ct_id}_mask.nii.gz" + +datasets: + + DLCS24: + profile_csv: DLCS24_nodule_profiles.csv + meta_csv: DLCS24_BMdataset_FEB192026_FIT_v1.csv + + LUNA25: + profile_csv: LUNA25_nodule_profiles.csv + meta_csv: LUNA25_dataset_FEB192026_FIT_v1.csv + + LUNA16: + profile_csv: LUNA16_nodule_profiles.csv + meta_csv: LUNA16_dataset_FEB192026_FIT_v1.csv + + LUNGx: + profile_csv: LUNGx_nodule_profiles.csv + meta_csv: LUNGx_dataset_FEB192026_FIT_v1.csv + + LNDbv4: + profile_csv: LNDbv4_nodule_profiles.csv + meta_csv: LNDBv4_dataset_FEB192026_FIT_v1.csv + + NSCLCR: + profile_csv: NSCLCR_nodule_profiles.csv + meta_csv: NSCLCR_dataset_FEB192026_FIT_v1.csv + nodule_seg_pattern: "{annotation_id}.nii.gz" + combined_mask_pattern: "{ct_id}.nii.gz" + + IMDCT: + profile_csv: IMDCT_nodule_profiles.csv + meta_csv: IMDCT_dataset_FEB192026_FIT_v1.csv + nodule_seg_use_ct_id: true + nodule_seg_pattern: "{ct_id}_seg.nii.gz" + combined_mask_pattern: "{ct_id}_seg.nii.gz" diff --git a/itrialspace/configs/trials.yaml b/itrialspace/configs/trials.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f1059ea91828b3a631423a6407986df9ae46f1d7 --- /dev/null +++ b/itrialspace/configs/trials.yaml @@ -0,0 +1,157 @@ +# Published lung cancer screening trial parameters. +# Used by TrialKnowledgeBase to instantiate TrialSpec objects. +# +# Sources: +# NLST: Aberle et al. NEJM 2011; 365:395-409 +# NELSON: de Koning et al. NEJM 2020; 382:503-513 +# UKLS: Field et al. Lancet Respir Med 2016; 4:699-709 +# DANTE: Infante et al. AJRCCM 2009; 180:445-453 +# MILD: Pastorino et al. ERJ 2012; 39:1354-1362 + +trials: + + NLST: + full_name: "National Lung Screening Trial" + publication: "Aberle et al. NEJM 2011" + population: screening + n_participants: 26722 + demographics: + age_range: [55, 74] + age_mean: 61.4 + age_std: 5.0 + sex_ratio_male: 0.59 + smoking_status: ["Current", "Former"] + pack_years_min: 30 + nodule_prevalence: + any_nodule: 0.245 + malignancy_rate: 0.04 + size_distribution: + bucket_weights: + "<5mm": 0.42 + "5-10mm": 0.38 + "10-15mm": 0.11 + "15-20mm": 0.05 + "20-30mm": 0.03 + ">30mm": 0.01 + malignancy_rate_by_size: + "<5mm": 0.01 + "5-10mm": 0.024 + "10-15mm": 0.094 + "15-20mm": 0.178 + "20-30mm": 0.222 + ">30mm": 0.362 + lobe_distribution: + right_lung_upper_lobe: 0.30 + right_lung_middle_lobe: 0.08 + right_lung_lower_lobe: 0.18 + left_lung_upper_lobe: 0.28 + left_lung_lower_lobe: 0.16 + applicable_source_datasets: ["DLCS24", "LUNA25", "LUNA16", "LNDbv4"] + + NELSON: + full_name: "Nederlands-Leuvens Longkanker Screenings Onderzoek" + publication: "de Koning et al. NEJM 2020" + population: screening + n_participants: 7557 + demographics: + age_range: [50, 75] + age_mean: 58.0 + age_std: 5.5 + sex_ratio_male: 0.84 + smoking_status: ["Current", "Former"] + pack_years_min: 15 + nodule_prevalence: + any_nodule: 0.50 + malignancy_rate: 0.022 + size_distribution: + bucket_weights: + "<5mm": 0.55 + "5-10mm": 0.30 + "10-15mm": 0.09 + "15-20mm": 0.04 + ">20mm": 0.02 + malignancy_rate_by_size: + "<5mm": 0.005 + "5-10mm": 0.014 + "10-15mm": 0.063 + "15-20mm": 0.156 + ">20mm": 0.308 + lobe_distribution: + right_lung_upper_lobe: 0.30 + right_lung_middle_lobe: 0.08 + right_lung_lower_lobe: 0.18 + left_lung_upper_lobe: 0.28 + left_lung_lower_lobe: 0.16 + applicable_source_datasets: ["DLCS24", "LUNA25", "LUNA16", "LNDbv4"] + + UKLS: + full_name: "UK Lung Cancer Screening Trial" + publication: "Field et al. Lancet Respir Med 2016" + population: screening + n_participants: 1994 + demographics: + age_range: [50, 75] + sex_ratio_male: 0.52 + smoking_status: ["Current", "Former"] + pack_years_min: 20 + nodule_prevalence: + any_nodule: 0.34 + malignancy_rate: 0.017 + size_distribution: + bucket_weights: + "<5mm": 0.48 + "5-10mm": 0.35 + "10-15mm": 0.10 + "15-20mm": 0.04 + ">20mm": 0.03 + lobe_distribution: + right_lung_upper_lobe: 0.30 + right_lung_middle_lobe: 0.08 + right_lung_lower_lobe: 0.18 + left_lung_upper_lobe: 0.28 + left_lung_lower_lobe: 0.16 + applicable_source_datasets: ["DLCS24", "LUNA25", "LUNA16"] + + DANTE: + full_name: "Detection And screening of early lung Neoplasm with LDCT" + publication: "Infante et al. AJRCCM 2009" + population: screening + n_participants: 1276 + demographics: + age_range: [60, 75] + sex_ratio_male: 1.0 + smoking_status: ["Current", "Former"] + pack_years_min: 20 + nodule_prevalence: + any_nodule: 0.31 + malignancy_rate: 0.028 + size_distribution: + bucket_weights: + "<5mm": 0.40 + "5-10mm": 0.37 + "10-15mm": 0.13 + "15-20mm": 0.06 + ">20mm": 0.04 + applicable_source_datasets: ["DLCS24", "LUNA25"] + + MILD: + full_name: "Multicentric Italian Lung Detection Trial" + publication: "Pastorino et al. ERJ 2012" + population: screening + n_participants: 2376 + demographics: + age_range: [49, 75] + sex_ratio_male: 0.66 + smoking_status: ["Current", "Former"] + pack_years_min: 20 + nodule_prevalence: + any_nodule: 0.28 + malignancy_rate: 0.012 + size_distribution: + bucket_weights: + "<5mm": 0.52 + "5-10mm": 0.33 + "10-15mm": 0.09 + "15-20mm": 0.04 + ">20mm": 0.02 + applicable_source_datasets: ["DLCS24", "LUNA25", "LUNA16"] diff --git a/itrialspace/docker/Dockerfile b/itrialspace/docker/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d4eba00ae82e16a2a819adfea95081afbe77e337 --- /dev/null +++ b/itrialspace/docker/Dockerfile @@ -0,0 +1,35 @@ +# iTrialSpace — lightweight image for the core pipeline + web tools. +# +# docker build -t itrialspace -f docker/Dockerfile . +# docker run --rm -e ITRIALSPACE_DATA_DIR=/data -v /host/data:/data itrialspace its config +# +# GPU stages (synthesis, VLM) need a CUDA base image + torch; this image covers the +# core/imaging/web extras. See docs/installation.md for the GPU setup. +FROM python:3.11-slim + +ENV PYTHONUNBUFFERED=1 \ + PIP_NO_CACHE_DIR=1 \ + ITRIALSPACE_DATA_DIR=/data + +# System libs needed by nibabel/SimpleITK/matplotlib/faiss +RUN apt-get update && apt-get install -y --no-install-recommends \ + build-essential libgl1 libglib2.0-0 git \ + && rm -rf /var/lib/apt/lists/* + +WORKDIR /app + +# Install dependencies first (better layer caching), then the package. +COPY pyproject.toml README.md ./ +COPY src ./src +COPY configs ./configs +RUN pip install --upgrade pip && pip install ".[imaging,web]" + +# Bring in the rest (docs, tests, infra, sample data) +COPY . . + +# Non-root user +RUN useradd -m -u 1000 its && mkdir -p /data && chown -R its:its /app /data +USER its + +ENTRYPOINT ["its"] +CMD ["config"] diff --git a/itrialspace/docker/Dockerfile.gpu b/itrialspace/docker/Dockerfile.gpu new file mode 100644 index 0000000000000000000000000000000000000000..5c1b02c55782d2f140cdce0a276439e69f6bcc9c --- /dev/null +++ b/itrialspace/docker/Dockerfile.gpu @@ -0,0 +1,51 @@ +# iTrialSpace — GPU image for synthesis (NodMAISI) and VLM evaluation. +# Pinned to the development environment: CUDA 12.1, torch 2.4.1, git-pinned MONAI. +# +# docker build -t itrialspace-gpu -f docker/Dockerfile.gpu . +# +# # Step 3 synthesis (mount data, outputs, and the NodMAISI weights): +# docker run --rm --gpus all \ +# -e ITRIALSPACE_DATA_DIR=/data -e ITRIALSPACE_OUTPUT_DIR=/out \ +# -e NODMAISI_MODELS_DIR=/models \ +# -v /host/iTrialSpace:/data -v /host/outputs:/out -v /host/nodmaisi/models:/models \ +# --entrypoint python itrialspace-gpu \ +# -m itrialspace.synthesis.tools.run_itrialspace_to_ct \ +# --audit /out/inserted_masks/mode1_controlled_prevalence/audit.json \ +# --config src/itrialspace/synthesis/tools/integration_config.yaml \ +# --outdir /out/generated_cts/mode1_controlled_prevalence +# +# For a byte-for-byte clone of the dev env instead, build from requirements.lock.txt +# (see docs/installation.md). Base matches torch 2.4.1+cu121. +FROM nvidia/cuda:12.1.1-cudnn8-runtime-ubuntu22.04 + +ENV DEBIAN_FRONTEND=noninteractive \ + PYTHONUNBUFFERED=1 \ + PIP_NO_CACHE_DIR=1 \ + ITRIALSPACE_DATA_DIR=/data \ + ITRIALSPACE_OUTPUT_DIR=/out \ + NODMAISI_MODELS_DIR=/models + +# System Python (3.10 on 22.04; package requires >=3.10) + libs for nibabel/SimpleITK/matplotlib +RUN apt-get update && apt-get install -y --no-install-recommends \ + python3 python3-pip python3-dev build-essential git \ + libgl1 libglib2.0-0 \ + && ln -sf /usr/bin/python3 /usr/bin/python \ + && rm -rf /var/lib/apt/lists/* + +WORKDIR /app +COPY . . + +# Match the dev env: torch 2.4.1 (cu121) and the git-pinned MONAI build, then the +# package (editable so the synthesis subprocess path model resolves like dev). +RUN pip install --upgrade pip \ + && pip install torch==2.4.1 --index-url https://download.pytorch.org/whl/cu121 \ + && pip install "monai @ git+https://github.com/Project-MONAI/MONAI.git@c3a317d2bcb486199f40bda0d722a41e3869712a" \ + && pip install -e ".[imaging,synthesis,vlm]" + +# Non-root user; create the runtime mount points +RUN useradd -m -u 1000 its && mkdir -p /data /out /models && chown -R its:its /app /data /out /models +USER its + +# Default to the umbrella CLI; override --entrypoint for synthesis/VLM module runs. +ENTRYPOINT ["its"] +CMD ["config"] diff --git a/itrialspace/docker/itrialspace.def b/itrialspace/docker/itrialspace.def new file mode 100644 index 0000000000000000000000000000000000000000..57c2d95b23c93518956b525dd4d698f659fd1ca4 --- /dev/null +++ b/itrialspace/docker/itrialspace.def @@ -0,0 +1,68 @@ +# Apptainer/Singularity recipe for iTrialSpace (GPU) — for HPC clusters that use +# Apptainer instead of Docker. Builds rootless, no Docker daemon required. +# +# # Build the image (.sif) — run from the repo root: +# apptainer build itrialspace.sif docker/itrialspace.def +# +# # Or convert the already-built Docker image: +# apptainer build itrialspace.sif docker-daemon://itrialspace-gpu:latest +# +# # Run the umbrella CLI (Apptainer bind-mounts $HOME and $PWD by default; add others): +# apptainer run --nv \ +# --env ITRIALSPACE_DATA_DIR=/data,ITRIALSPACE_OUTPUT_DIR=/out,NODMAISI_MODELS_DIR=/models \ +# -B /scratch/.../iTrialSpace:/data,/scratch/.../outputs:/out,/path/nodmaisi/models:/models \ +# itrialspace.sif config +# +# # Step 3 synthesis: +# apptainer exec --nv \ +# --env ITRIALSPACE_DATA_DIR=/data,ITRIALSPACE_OUTPUT_DIR=/out,NODMAISI_MODELS_DIR=/models \ +# -B /host/iTrialSpace:/data,/host/outputs:/out,/host/nodmaisi/models:/models \ +# itrialspace.sif \ +# python -m itrialspace.synthesis.tools.run_itrialspace_to_ct \ +# --audit /out/inserted_masks/mode1_controlled_prevalence/audit.json \ +# --config /opt/itrialspace/src/itrialspace/synthesis/tools/integration_config.yaml \ +# --outdir /out/generated_cts/mode1_controlled_prevalence +# +# NOTE: build from the repo root so %files can copy the source tree. + +Bootstrap: docker +From: nvidia/cuda:12.1.1-cudnn8-runtime-ubuntu22.04 + +%files + . /opt/itrialspace + +%post + export DEBIAN_FRONTEND=noninteractive + apt-get update && apt-get install -y --no-install-recommends \ + python3 python3-pip python3-dev build-essential git \ + libgl1 libglib2.0-0 + ln -sf /usr/bin/python3 /usr/bin/python + rm -rf /var/lib/apt/lists/* + + cd /opt/itrialspace + # Drop any host-local state copied in via %files + rm -rf .git .env logs/* **/__pycache__ 2>/dev/null || true + pip install --upgrade pip + pip install torch==2.4.1 --index-url https://download.pytorch.org/whl/cu121 + pip install "monai @ git+https://github.com/Project-MONAI/MONAI.git@c3a317d2bcb486199f40bda0d722a41e3869712a" + pip install -e ".[imaging,synthesis,vlm]" + +%environment + export ITRIALSPACE_ROOT=/opt/itrialspace + export ITRIALSPACE_DATA_DIR=${ITRIALSPACE_DATA_DIR:-/data} + export ITRIALSPACE_OUTPUT_DIR=${ITRIALSPACE_OUTPUT_DIR:-/out} + export NODMAISI_MODELS_DIR=${NODMAISI_MODELS_DIR:-/models} + export PYTHONUNBUFFERED=1 + +%runscript + exec its "$@" + +%labels + Name iTrialSpace + Description Synthetic Imaging Clinical Trial Engine (GPU) + +%help + iTrialSpace container. Bind your data/outputs/weights and set the matching + ITRIALSPACE_DATA_DIR / ITRIALSPACE_OUTPUT_DIR / NODMAISI_MODELS_DIR env vars. + Use `apptainer run` for the `its` CLI, or `apptainer exec ... python -m ...` + for synthesis/VLM module runs. See docs/installation.md. diff --git a/itrialspace/environment.lock.yml b/itrialspace/environment.lock.yml new file mode 100644 index 0000000000000000000000000000000000000000..a9f299d0bdb607280159cc5a0397563acac066c8 --- /dev/null +++ b/itrialspace/environment.lock.yml @@ -0,0 +1,18 @@ +# Exact clone of the original development environment. +# Reproduces Python 3.10.13 + the full pinned package set (linux-64, CUDA 12.1), +# including torch 2.4.1+cu121 and the git-pinned MONAI build. +# +# conda env create -f environment.lock.yml +# conda activate itrialspace +# +# This is the "give me exactly what worked" option. For a lighter, less pinned +# setup use environment.yml instead. See docs/installation.md. +name: itrialspace +channels: + - conda-forge +dependencies: + - python=3.10.13 + - pip + - pip: + - -r requirements.lock.txt + - -e . diff --git a/itrialspace/environment.yml b/itrialspace/environment.yml new file mode 100644 index 0000000000000000000000000000000000000000..5cb9c5816323fe45994faee367618f4718ab756b --- /dev/null +++ b/itrialspace/environment.yml @@ -0,0 +1,30 @@ +# Conda environment for iTrialSpace — matches the development environment versions. +# +# conda env create -f environment.yml +# conda activate itrialspace +# +# IMPORTANT: install everything in ONE pip resolution (this file does). Do NOT follow +# up with extra unpinned `pip install`s — the `>=` extras would drift to latest and +# bump torch/transformers/monai. For an exact freeze, see requirements.lock.txt. +# +# Verified versions: Python 3.10, torch 2.4.1+cu121, torchvision 0.19.1+cu121, +# transformers 4.51.3, open_clip 2.32.0, MONAI (git dev commit), numpy 1.26.4. +# CUDA 12.1 build of torch — adjust the index URL to match your driver if needed. +name: itrialspace +channels: + - conda-forge +dependencies: + - python=3.10 + - pip>=23 + - pip: + - --extra-index-url https://download.pytorch.org/whl/cu121 + # Behavior-critical pins (match the dev env exactly) + - numpy==1.26.4 + - torch==2.4.1 + - torchvision==0.19.1 + - transformers==4.51.3 + - open_clip_torch==2.32.0 + - seaborn>=0.12 + - monai @ git+https://github.com/Project-MONAI/MONAI.git@c3a317d2bcb486199f40bda0d722a41e3869712a + # The package with all in-repo extras (deps resolve around the pins above) + - -e .[imaging,apps,synthesis,vlm,dev] diff --git a/itrialspace/infra/slurm/README.md b/itrialspace/infra/slurm/README.md new file mode 100644 index 0000000000000000000000000000000000000000..baaafce4c447d8b0e6dfcf04b1364f1d56824d96 --- /dev/null +++ b/itrialspace/infra/slurm/README.md @@ -0,0 +1,47 @@ +# SLURM job scripts + +HPC submission scripts for every stage of the iTrialSpace pipeline. They are +**cluster-portable**: paths, the conda environment, and partitions come from +environment variables (with sane defaults) rather than being hardcoded. + +## How portability works + +Every script sources [`env.sh`](env.sh) near the top: + +```bash +source "$(dirname "$0")/../env.sh" # sets PROJ_DIR, ITRIALSPACE_DATA_DIR, CONDA_ENV, ... +itrialspace_activate_conda # activates the conda env portably +``` + +`env.sh` resolves (overridable via your shell or a repo-root `.env`): + +| Variable | Default | Meaning | +|----------|---------|---------| +| `PROJ_DIR` | auto (repo root) | iTrialSpace checkout | +| `ITRIALSPACE_DATA_DIR` | `~/.itrialspace/data` | unified data layout | +| `ITRIALSPACE_OUTPUT_DIR` | `=DATA_DIR` | generated artifacts | +| `ITRIALSPACE_CONDA_ENV` | `itrialspace` | conda env name | +| `CONDA_PROFILE` | auto-detected | path to `conda.sh` | +| `SLURM_PARTITION_GPU` / `SLURM_PARTITION_CPU` | `gpu` / `cpu` | partitions | + +## Adapting to a new cluster + +1. Set the variables above in your `.env` (copy `.env.example`) or shell profile. +2. **Edit the `#SBATCH` directives** in the scripts you use — partition names + (`--partition`), account (`--account`), GPU type, walltime, and memory are + cluster-specific and cannot be set from environment variables (SLURM parses + `#SBATCH` lines before the shell runs). Search-and-replace the partition names + for your site. +3. Submit from the repo root, e.g. `sbatch infra/slurm/nodulemap/nodulemap.sub`. + +## Layout + +| Directory | Stage | +|-----------|-------| +| `trials/` | Generate cohort manifests (13 modes) | +| `mask_inserter/` | Insert nodule masks into host CTs | +| `synthesis/` | NodMAISI CT synthesis (needs model weights — see docs) | +| `nodulemap/` · `retriever/` | Launch interactive web tools | +| `vlm_eval/` | Vision-language model evaluation | + +> Logs are written to `logs/` (gitignored). Create it first or let the scripts `mkdir -p logs`. diff --git a/itrialspace/infra/slurm/_gen_caselist.py b/itrialspace/infra/slurm/_gen_caselist.py new file mode 100644 index 0000000000000000000000000000000000000000..7c9ea2d1301d96b4f246b5efde0057ee7b5c3e32 --- /dev/null +++ b/itrialspace/infra/slurm/_gen_caselist.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python3 +"""Write a synthesis case list (mask-filename stems) from an insertion audit.json. + +The synthesis runner matches --case-ids against the mask-filename stem (NOT the +audit's integer case_id), so the case list must contain those stems. + +Usage: python _gen_caselist.py # prints N cases +""" +import json +import os +import sys + + +def stem(path: str) -> str: + name = os.path.basename(path) + for suffix in ("_mask.nii.gz", ".nii.gz"): + if name.endswith(suffix): + return name[: -len(suffix)] + return name + + +def main() -> None: + audit, out = sys.argv[1], sys.argv[2] + data = json.load(open(audit)) + recs = data.get("records", data.get("cases", [])) + cases = sorted( + {stem(r["output_combined_path"]) for r in recs + if r.get("status") == "success" and r.get("output_combined_path")} + ) + os.makedirs(os.path.dirname(out) or ".", exist_ok=True) + with open(out, "w") as f: + f.write("\n".join(cases) + "\n") + print(len(cases)) + + +if __name__ == "__main__": + main() diff --git a/itrialspace/infra/slurm/env.sh b/itrialspace/infra/slurm/env.sh new file mode 100644 index 0000000000000000000000000000000000000000..536dc61899f7893808aec6664344d8e46b29ac6e --- /dev/null +++ b/itrialspace/infra/slurm/env.sh @@ -0,0 +1,88 @@ +#!/usr/bin/env bash +# Shared environment for all iTrialSpace SLURM scripts. +# +# Every .sub script sources this file instead of hardcoding paths or the conda env: +# +# source "$(dirname "${BASH_SOURCE[0]}")/../env.sh" +# +# Override any value by exporting it before submitting, or by editing this file / +# a local copy. Nothing here is host-specific by default — set the variables for +# your cluster in your shell profile or a `.env` next to the repo. + +# ── Repo root (auto-detected: this file lives at /infra/slurm/env.sh) ── +_ENV_SH_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +export PROJ_DIR="${PROJ_DIR:-$(cd "${_ENV_SH_DIR}/../.." && pwd)}" + +# Load a repo-local .env for defaults. Precedence: variables already set in the +# environment (shell export, or `VAR=x sbatch ...`) WIN over .env, which in turn +# wins over the built-in defaults below. So a per-job override works: +# ITRIALSPACE_OUTPUT_DIR=/somewhere sbatch infra/slurm/trials/mode1_*.sub +if [[ -f "${PROJ_DIR}/.env" ]]; then + while IFS= read -r _line || [[ -n "${_line}" ]]; do + case "${_line}" in ''|\#*) continue ;; esac # skip blanks/comments + _key="${_line%%=*}" + [[ "${_key}" =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]] || continue + if [[ -z "${!_key+x}" ]]; then # only if not already set + export "${_key}=$(eval "printf '%s' \"${_line#*=}\"")" + fi + done < "${PROJ_DIR}/.env" + unset _line _key +fi + +# ── Data root (unified layout: raw_ct/ masks/ profiles/ ...) ──────────────── +export ITRIALSPACE_DATA_DIR="${ITRIALSPACE_DATA_DIR:-${HOME}/.itrialspace/data}" +export DATA_BASE="${DATA_BASE:-${ITRIALSPACE_DATA_DIR}}" +# Output root defaults to the data root — computed AFTER .env so it follows it. +export ITRIALSPACE_OUTPUT_DIR="${ITRIALSPACE_OUTPUT_DIR:-${ITRIALSPACE_DATA_DIR}}" + +# ── Conda environment ─────────────────────────────────────────────────────── +export ITRIALSPACE_CONDA_ENV="${ITRIALSPACE_CONDA_ENV:-itrialspace}" +# Isolate from ~/.local user-site packages so the conda env is authoritative +# (avoids shadowing the env's torch/pytest/etc. with stale user-site copies). +export PYTHONNOUSERSITE="${PYTHONNOUSERSITE:-1}" +# Path to your conda profile script (cluster-specific). Common locations tried below. +export CONDA_PROFILE="${CONDA_PROFILE:-}" + +# ── SLURM partitions / account (override per cluster) ─────────────────────── +export SLURM_PARTITION_GPU="${SLURM_PARTITION_GPU:-gpu}" +export SLURM_PARTITION_CPU="${SLURM_PARTITION_CPU:-cpu}" +export SLURM_ACCOUNT="${SLURM_ACCOUNT:-}" + +# ── Make the package importable ───────────────────────────────────────────── +export PYTHONPATH="${PROJ_DIR}/src:${PYTHONPATH:-}" + +# ── Helper: activate the conda env portably ───────────────────────────────── +itrialspace_activate_conda() { + local profile="${CONDA_PROFILE}" + if [[ -z "${profile}" ]]; then + for cand in \ + "/cm/shared/apps/miniconda/etc/profile.d/conda.sh" \ + "${HOME}/miniconda3/etc/profile.d/conda.sh" \ + "${HOME}/anaconda3/etc/profile.d/conda.sh" \ + "/opt/conda/etc/profile.d/conda.sh"; do + [[ -f "${cand}" ]] && profile="${cand}" && break + done + fi + if [[ -n "${profile}" && -f "${profile}" ]]; then + # shellcheck disable=SC1090 + source "${profile}" + conda activate "${ITRIALSPACE_CONDA_ENV}" + else + echo "WARNING: conda profile not found; set CONDA_PROFILE. Continuing without activation." >&2 + fi + # torch's pip-installed CUDA libs (cuDNN etc.) aren't auto-found in a clean env → + # put every nvidia/*/lib on LD_LIBRARY_PATH (otherwise: "libcudnn.so.9 not found" / + # CUDNN_STATUS_NOT_INITIALIZED). + if [[ -n "${CONDA_PREFIX:-}" ]]; then + local _d + for _d in "${CONDA_PREFIX}"/lib/python*/site-packages/nvidia/*/lib; do + [[ -d "${_d}" ]] && export LD_LIBRARY_PATH="${_d}:${LD_LIBRARY_PATH:-}" + done + fi +} + +# Run from the repo root and ensure the log directory exists. (The `#SBATCH +# --output=logs/...` path is opened by SLURM *before* this runs, so also keep a +# committed logs/ dir and submit from the repo root — see infra/slurm/README.md.) +cd "${PROJ_DIR}" 2>/dev/null || true +mkdir -p "${PROJ_DIR}/logs" diff --git a/itrialspace/infra/slurm/mask_inserter/mode10_insert_masks.sub b/itrialspace/infra/slurm/mask_inserter/mode10_insert_masks.sub new file mode 100644 index 0000000000000000000000000000000000000000..8571e131eba2e021fc6c090299c100af6be4aea0 --- /dev/null +++ b/itrialspace/infra/slurm/mask_inserter/mode10_insert_masks.sub @@ -0,0 +1,84 @@ +#!/bin/bash +# ────────────────────────────────────────────────────────────────────────────── +# Mode 10: Multi-Nodule Realism Study — Mask Insertion +# +# Inserts donor nodule masks for multi-nodule realism study manifests. +# Mode 10 produces 2 manifests (single-nodule and multi-nodule sub-cohorts). +# Consider the array variant for batch processing across sub-cohorts. +# +# Usage: +# MANIFEST_PATH=.../multi_nodule_study_single.csv sbatch mode10_insert_masks.sub +# ────────────────────────────────────────────────────────────────────────────── + +#SBATCH --job-name=ins_M10_MultiNod +#SBATCH --partition=defq +#SBATCH --ntasks=1 +#SBATCH --gpus=0 +#SBATCH --cpus-per-task=8 +#SBATCH --mem=32G +#SBATCH --time=2-00:00:00 +#SBATCH --output=logs/insert_mode10_multi_nodule_realism_%j.out +#SBATCH --error=logs/insert_mode10_multi_nodule_realism_%j.err + +# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" +itrialspace_activate_conda + + +set -euo pipefail + +BASE_DIR="${ITRIALSPACE_DATA_DIR}" +MANIFEST_ROOT="${ITRIALSPACE_OUTPUT_DIR}/manifests" +OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks" +PROJECT_DIR="${PROJ_DIR}" + +TRIAL_MODE="mode10_multi_nodule_realism" +MANIFEST_PATH="${MANIFEST_PATH:-${MANIFEST_ROOT}/${TRIAL_MODE}/multi_nodule_study_single.csv}" +OUT_DIR="${OUT_DIR:-${OUTPUT_ROOT}/${TRIAL_MODE}}" +CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}" +N_JOBS="${N_JOBS:-8}" +DRY_RUN="${DRY_RUN:-false}" +SEED="${SEED:-42}" + +echo "==================================================================" +echo " iTrialSpace Mask Insertion — Mode 10: Multi-Nodule Realism Study" +echo " Job ID: ${SLURM_JOB_ID:-local} Node: $(hostname) Date: $(date)" +echo "==================================================================" +echo " MANIFEST_PATH : ${MANIFEST_PATH}" +echo " OUT_DIR : ${OUT_DIR}" +echo " N_JOBS : ${N_JOBS}" +echo "" + +cd "${PROJECT_DIR}" + +if [ ! -f "${MANIFEST_PATH}" ]; then + echo "FATAL: Manifest not found: ${MANIFEST_PATH}" + exit 1 +fi +mkdir -p "${OUT_DIR}" + +CFG_ARG="" +if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then + CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}" +elif [ -f "${CONFIG_PATH}" ]; then + CFG_ARG="--config ${CONFIG_PATH}" +fi + +EXTRA_ARGS="" +[ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run" + +echo "Running: python3 -m itrialspace.mask_inserter run ..." +echo " manifest: ${MANIFEST_PATH}" +echo " output: ${OUT_DIR}" + +python3 -m itrialspace.mask_inserter run \ + --manifest "${MANIFEST_PATH}" \ + --output-dir "${OUT_DIR}" \ + ${CFG_ARG} \ + --trial-name "${TRIAL_MODE}" \ + --seed ${SEED} \ + --n-jobs ${N_JOBS} \ + ${EXTRA_ARGS} +EXIT_CODE=$? +echo "Finished: $(date) Exit: ${EXIT_CODE}" +exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/mask_inserter/mode10_insert_masks_array.sub b/itrialspace/infra/slurm/mask_inserter/mode10_insert_masks_array.sub new file mode 100644 index 0000000000000000000000000000000000000000..0ecb9947dc532db9827953e55b137bb9c486add5 --- /dev/null +++ b/itrialspace/infra/slurm/mask_inserter/mode10_insert_masks_array.sub @@ -0,0 +1,101 @@ +#!/bin/bash +# ────────────────────────────────────────────────────────────────────────────── +# Mode 10: Multi-Nodule Realism Study — Array Job (one per sub-cohort) +# +# Mode 10 produces 2 manifests (single-nodule and multi-nodule sub-cohorts). +# +# Usage: +# python itrialspace_mask_inserter/tools/list_manifests.py \ +# --dir /scratch/.../manifests/mode10_multi_nodule_realism \ +# --output manifests_mode10.txt +# sbatch --array=0-$(( $(wc -l < manifests_mode10.txt) - 1 )) \ +# mode10_insert_masks_array.sub +# ────────────────────────────────────────────────────────────────────────────── + +#SBATCH --job-name=ins_M10_arr +#SBATCH --partition=defq +#SBATCH --ntasks=1 +#SBATCH --gpus=0 +#SBATCH --cpus-per-task=8 +#SBATCH --mem=32G +#SBATCH --time=2-00:00:00 +#SBATCH --output=logs/insert_mode10_multi_nodule_realism_%A_%a.out +#SBATCH --error=logs/insert_mode10_multi_nodule_realism_%A_%a.err + +# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" +itrialspace_activate_conda + + +set -euo pipefail + +BASE_DIR="${ITRIALSPACE_DATA_DIR}" +OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks" +PROJECT_DIR="${PROJ_DIR}" + +TRIAL_MODE="mode10_multi_nodule_realism" +MANIFEST_LIST="${MANIFEST_LIST:-${PROJECT_DIR}/itrialspace_mask_inserter/slurm_trials/manifests_mode10.txt}" +CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}" +N_JOBS="${N_JOBS:-8}" +DRY_RUN="${DRY_RUN:-false}" +SEED="${SEED:-42}" + +if [ ! -f "${MANIFEST_LIST}" ]; then + echo "FATAL: Manifest list not found: ${MANIFEST_LIST}" + exit 1 +fi + +TASK_ID="${SLURM_ARRAY_TASK_ID:-0}" +MANIFEST_PATH=$(sed -n "$((TASK_ID + 1))p" "${MANIFEST_LIST}") + +if [ -z "${MANIFEST_PATH}" ]; then + echo "FATAL: No manifest at index ${TASK_ID} in ${MANIFEST_LIST}" + exit 1 +fi + +MANIFEST_BASENAME="$(basename "${MANIFEST_PATH}" .csv)" +MANIFEST_BASENAME="$(basename "${MANIFEST_BASENAME}" .json)" +OUT_DIR="${OUTPUT_ROOT}/${TRIAL_MODE}/${MANIFEST_BASENAME}" + +echo "==================================================================" +echo " iTrialSpace Mask Insertion — Mode 10: Multi-Nodule Realism (Array)" +echo " Job ID: ${SLURM_JOB_ID:-local} Array Task: ${TASK_ID}" +echo " Node: $(hostname) Date: $(date)" +echo "==================================================================" +echo " MANIFEST_PATH : ${MANIFEST_PATH}" +echo " OUT_DIR : ${OUT_DIR}" +echo "" + +cd "${PROJECT_DIR}" + +if [ ! -f "${MANIFEST_PATH}" ]; then + echo "FATAL: Manifest not found: ${MANIFEST_PATH}" + exit 1 +fi +mkdir -p "${OUT_DIR}" + +CFG_ARG="" +if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then + CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}" +elif [ -f "${CONFIG_PATH}" ]; then + CFG_ARG="--config ${CONFIG_PATH}" +fi + +EXTRA_ARGS="" +[ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run" + +echo "Running: python3 -m itrialspace.mask_inserter run ..." +echo " manifest: ${MANIFEST_PATH}" +echo " output: ${OUT_DIR}" + +python3 -m itrialspace.mask_inserter run \ + --manifest "${MANIFEST_PATH}" \ + --output-dir "${OUT_DIR}" \ + ${CFG_ARG} \ + --trial-name "${TRIAL_MODE}_${MANIFEST_BASENAME}" \ + --seed ${SEED} \ + --n-jobs ${N_JOBS} \ + ${EXTRA_ARGS} +EXIT_CODE=$? +echo "Finished: $(date) Exit: ${EXIT_CODE}" +exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/mask_inserter/mode11_insert_masks.sub b/itrialspace/infra/slurm/mask_inserter/mode11_insert_masks.sub new file mode 100644 index 0000000000000000000000000000000000000000..34785a6f34052fb43556ec99fc8ac80cd1cf2681 --- /dev/null +++ b/itrialspace/infra/slurm/mask_inserter/mode11_insert_masks.sub @@ -0,0 +1,85 @@ +#!/bin/bash +# ────────────────────────────────────────────────────────────────────────────── +# Mode 11: Digital Twin Isolation — Mask Insertion +# +# Inserts one native nodule mask per isolation case. Each row in the manifest +# represents a single nodule placed into the host patient's own anatomy. +# Because each case is a single nodule insertion the per-row cost is low, +# but the total number of rows can be large (one per nodule per patient). +# +# Usage: +# MANIFEST_PATH=.../digital_twin_isolation_DLCS24.csv sbatch mode11_insert_masks.sub +# ────────────────────────────────────────────────────────────────────────────── + +#SBATCH --job-name=ins_M11_DTiso +#SBATCH --partition=defq +#SBATCH --ntasks=1 +#SBATCH --gpus=0 +#SBATCH --cpus-per-task=8 +#SBATCH --mem=32G +#SBATCH --time=2-00:00:00 +#SBATCH --output=logs/insert_mode11_digital_twin_isolation_%j.out +#SBATCH --error=logs/insert_mode11_digital_twin_isolation_%j.err + +# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" +itrialspace_activate_conda + + +set -euo pipefail + +BASE_DIR="${ITRIALSPACE_DATA_DIR}" +MANIFEST_ROOT="${ITRIALSPACE_OUTPUT_DIR}/manifests" +OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks" +PROJECT_DIR="${PROJ_DIR}" + +TRIAL_MODE="mode11_digital_twin_isolation" +MANIFEST_PATH="${MANIFEST_PATH:-${MANIFEST_ROOT}/${TRIAL_MODE}/digital_twin_isolation_DLCS24.csv}" +OUT_DIR="${OUT_DIR:-${OUTPUT_ROOT}/${TRIAL_MODE}}" +CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}" +N_JOBS="${N_JOBS:-8}" +DRY_RUN="${DRY_RUN:-false}" +SEED="${SEED:-42}" + +echo "==================================================================" +echo " iTrialSpace Mask Insertion — Mode 11: Digital Twin Isolation" +echo " Job ID: ${SLURM_JOB_ID:-local} Node: $(hostname) Date: $(date)" +echo "==================================================================" +echo " MANIFEST_PATH : ${MANIFEST_PATH}" +echo " OUT_DIR : ${OUT_DIR}" +echo " N_JOBS : ${N_JOBS}" +echo "" + +cd "${PROJECT_DIR}" + +if [ ! -f "${MANIFEST_PATH}" ]; then + echo "FATAL: Manifest not found: ${MANIFEST_PATH}" + exit 1 +fi +mkdir -p "${OUT_DIR}" + +CFG_ARG="" +if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then + CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}" +elif [ -f "${CONFIG_PATH}" ]; then + CFG_ARG="--config ${CONFIG_PATH}" +fi + +EXTRA_ARGS="" +[ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run" + +echo "Running: python3 -m itrialspace.mask_inserter run ..." +echo " manifest: ${MANIFEST_PATH}" +echo " output: ${OUT_DIR}" + +python3 -m itrialspace.mask_inserter run \ + --manifest "${MANIFEST_PATH}" \ + --output-dir "${OUT_DIR}" \ + ${CFG_ARG} \ + --trial-name "${TRIAL_MODE}" \ + --seed ${SEED} \ + --n-jobs ${N_JOBS} \ + ${EXTRA_ARGS} +EXIT_CODE=$? +echo "Finished: $(date) Exit: ${EXIT_CODE}" +exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/mask_inserter/mode11_insert_masks_array.sub b/itrialspace/infra/slurm/mask_inserter/mode11_insert_masks_array.sub new file mode 100644 index 0000000000000000000000000000000000000000..c61350ede463769460e061a68d1ca0e509616bc1 --- /dev/null +++ b/itrialspace/infra/slurm/mask_inserter/mode11_insert_masks_array.sub @@ -0,0 +1,103 @@ +#!/bin/bash +# ────────────────────────────────────────────────────────────────────────────── +# Mode 11: Digital Twin Isolation — Array Job (one per manifest chunk) +# +# When all_patients=True the isolation manifest can be large (one row per +# nodule per patient). Use the list_manifests tool to split into chunks, +# then submit an array job so each chunk runs on a separate SLURM task. +# +# Usage: +# python itrialspace_mask_inserter/tools/list_manifests.py \ +# --dir /scratch/.../manifests/mode11_digital_twin_isolation \ +# --output manifests_mode11.txt +# sbatch --array=0-$(( $(wc -l < manifests_mode11.txt) - 1 )) \ +# mode11_insert_masks_array.sub +# ────────────────────────────────────────────────────────────────────────────── + +#SBATCH --job-name=ins_M11_arr +#SBATCH --partition=defq +#SBATCH --ntasks=1 +#SBATCH --gpus=0 +#SBATCH --cpus-per-task=8 +#SBATCH --mem=32G +#SBATCH --time=2-00:00:00 +#SBATCH --output=logs/insert_mode11_digital_twin_isolation_%A_%a.out +#SBATCH --error=logs/insert_mode11_digital_twin_isolation_%A_%a.err + +# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" +itrialspace_activate_conda + + +set -euo pipefail + +BASE_DIR="${ITRIALSPACE_DATA_DIR}" +OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks" +PROJECT_DIR="${PROJ_DIR}" + +TRIAL_MODE="mode11_digital_twin_isolation" +MANIFEST_LIST="${MANIFEST_LIST:-${PROJECT_DIR}/itrialspace_mask_inserter/slurm_trials/manifests_mode11.txt}" +CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}" +N_JOBS="${N_JOBS:-8}" +DRY_RUN="${DRY_RUN:-false}" +SEED="${SEED:-42}" + +if [ ! -f "${MANIFEST_LIST}" ]; then + echo "FATAL: Manifest list not found: ${MANIFEST_LIST}" + exit 1 +fi + +TASK_ID="${SLURM_ARRAY_TASK_ID:-0}" +MANIFEST_PATH=$(sed -n "$((TASK_ID + 1))p" "${MANIFEST_LIST}") + +if [ -z "${MANIFEST_PATH}" ]; then + echo "FATAL: No manifest at index ${TASK_ID} in ${MANIFEST_LIST}" + exit 1 +fi + +MANIFEST_BASENAME="$(basename "${MANIFEST_PATH}" .csv)" +MANIFEST_BASENAME="$(basename "${MANIFEST_BASENAME}" .json)" +OUT_DIR="${OUTPUT_ROOT}/${TRIAL_MODE}/${MANIFEST_BASENAME}" + +echo "==================================================================" +echo " iTrialSpace Mask Insertion — Mode 11: Digital Twin Isolation (Array)" +echo " Job ID: ${SLURM_JOB_ID:-local} Array Task: ${TASK_ID}" +echo " Node: $(hostname) Date: $(date)" +echo "==================================================================" +echo " MANIFEST_PATH : ${MANIFEST_PATH}" +echo " OUT_DIR : ${OUT_DIR}" +echo "" + +cd "${PROJECT_DIR}" + +if [ ! -f "${MANIFEST_PATH}" ]; then + echo "FATAL: Manifest not found: ${MANIFEST_PATH}" + exit 1 +fi +mkdir -p "${OUT_DIR}" + +CFG_ARG="" +if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then + CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}" +elif [ -f "${CONFIG_PATH}" ]; then + CFG_ARG="--config ${CONFIG_PATH}" +fi + +EXTRA_ARGS="" +[ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run" + +echo "Running: python3 -m itrialspace.mask_inserter run ..." +echo " manifest: ${MANIFEST_PATH}" +echo " output: ${OUT_DIR}" + +python3 -m itrialspace.mask_inserter run \ + --manifest "${MANIFEST_PATH}" \ + --output-dir "${OUT_DIR}" \ + ${CFG_ARG} \ + --trial-name "${TRIAL_MODE}_${MANIFEST_BASENAME}" \ + --seed ${SEED} \ + --n-jobs ${N_JOBS} \ + ${EXTRA_ARGS} +EXIT_CODE=$? +echo "Finished: $(date) Exit: ${EXIT_CODE}" +exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/mask_inserter/mode12_insert_masks.sub b/itrialspace/infra/slurm/mask_inserter/mode12_insert_masks.sub new file mode 100644 index 0000000000000000000000000000000000000000..b32c8f735cc5b177626f62deeaaf5490f4dd8b07 --- /dev/null +++ b/itrialspace/infra/slurm/mask_inserter/mode12_insert_masks.sub @@ -0,0 +1,84 @@ +#!/bin/bash +# ────────────────────────────────────────────────────────────────────────────── +# Mode 12: Digital Twin Complete — Mask Insertion +# +# Inserts ALL native nodule masks per patient into one combined conditioning +# mask. Each case has multiple manifest rows sharing a case_id; the inserter +# processes them sequentially and merges with label value 23. +# +# Usage: +# MANIFEST_PATH=.../digital_twin_complete_DLCS24.csv sbatch mode12_insert_masks.sub +# ────────────────────────────────────────────────────────────────────────────── + +#SBATCH --job-name=ins_M12_DTcomp +#SBATCH --partition=defq +#SBATCH --ntasks=1 +#SBATCH --gpus=0 +#SBATCH --cpus-per-task=8 +#SBATCH --mem=32G +#SBATCH --time=2-00:00:00 +#SBATCH --output=logs/insert_mode12_digital_twin_complete_%j.out +#SBATCH --error=logs/insert_mode12_digital_twin_complete_%j.err + +# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" +itrialspace_activate_conda + + +set -euo pipefail + +BASE_DIR="${ITRIALSPACE_DATA_DIR}" +MANIFEST_ROOT="${ITRIALSPACE_OUTPUT_DIR}/manifests" +OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks" +PROJECT_DIR="${PROJ_DIR}" + +TRIAL_MODE="mode12_digital_twin_complete" +MANIFEST_PATH="${MANIFEST_PATH:-${MANIFEST_ROOT}/${TRIAL_MODE}/digital_twin_complete_DLCS24.csv}" +OUT_DIR="${OUT_DIR:-${OUTPUT_ROOT}/${TRIAL_MODE}}" +CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}" +N_JOBS="${N_JOBS:-8}" +DRY_RUN="${DRY_RUN:-false}" +SEED="${SEED:-42}" + +echo "==================================================================" +echo " iTrialSpace Mask Insertion — Mode 12: Digital Twin Complete" +echo " Job ID: ${SLURM_JOB_ID:-local} Node: $(hostname) Date: $(date)" +echo "==================================================================" +echo " MANIFEST_PATH : ${MANIFEST_PATH}" +echo " OUT_DIR : ${OUT_DIR}" +echo " N_JOBS : ${N_JOBS}" +echo "" + +cd "${PROJECT_DIR}" + +if [ ! -f "${MANIFEST_PATH}" ]; then + echo "FATAL: Manifest not found: ${MANIFEST_PATH}" + exit 1 +fi +mkdir -p "${OUT_DIR}" + +CFG_ARG="" +if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then + CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}" +elif [ -f "${CONFIG_PATH}" ]; then + CFG_ARG="--config ${CONFIG_PATH}" +fi + +EXTRA_ARGS="" +[ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run" + +echo "Running: python3 -m itrialspace.mask_inserter run ..." +echo " manifest: ${MANIFEST_PATH}" +echo " output: ${OUT_DIR}" + +python3 -m itrialspace.mask_inserter run \ + --manifest "${MANIFEST_PATH}" \ + --output-dir "${OUT_DIR}" \ + ${CFG_ARG} \ + --trial-name "${TRIAL_MODE}" \ + --seed ${SEED} \ + --n-jobs ${N_JOBS} \ + ${EXTRA_ARGS} +EXIT_CODE=$? +echo "Finished: $(date) Exit: ${EXIT_CODE}" +exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/mask_inserter/mode12_insert_masks_array.sub b/itrialspace/infra/slurm/mask_inserter/mode12_insert_masks_array.sub new file mode 100644 index 0000000000000000000000000000000000000000..8d42abce9c08ebb815a4f718b9cc8706fe4b5abc --- /dev/null +++ b/itrialspace/infra/slurm/mask_inserter/mode12_insert_masks_array.sub @@ -0,0 +1,102 @@ +#!/bin/bash +# ────────────────────────────────────────────────────────────────────────────── +# Mode 12: Digital Twin Complete — Array Job (one per manifest chunk) +# +# When all_patients=True the complete manifest can be large. +# Use the list_manifests tool to split into chunks, then submit an array job. +# +# Usage: +# python itrialspace_mask_inserter/tools/list_manifests.py \ +# --dir /scratch/.../manifests/mode12_digital_twin_complete \ +# --output manifests_mode12.txt +# sbatch --array=0-$(( $(wc -l < manifests_mode12.txt) - 1 )) \ +# mode12_insert_masks_array.sub +# ────────────────────────────────────────────────────────────────────────────── + +#SBATCH --job-name=ins_M12_arr +#SBATCH --partition=defq +#SBATCH --ntasks=1 +#SBATCH --gpus=0 +#SBATCH --cpus-per-task=8 +#SBATCH --mem=32G +#SBATCH --time=2-00:00:00 +#SBATCH --output=logs/insert_mode12_digital_twin_complete_%A_%a.out +#SBATCH --error=logs/insert_mode12_digital_twin_complete_%A_%a.err + +# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" +itrialspace_activate_conda + + +set -euo pipefail + +BASE_DIR="${ITRIALSPACE_DATA_DIR}" +OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks" +PROJECT_DIR="${PROJ_DIR}" + +TRIAL_MODE="mode12_digital_twin_complete" +MANIFEST_LIST="${MANIFEST_LIST:-${PROJECT_DIR}/itrialspace_mask_inserter/slurm_trials/manifests_mode12.txt}" +CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}" +N_JOBS="${N_JOBS:-8}" +DRY_RUN="${DRY_RUN:-false}" +SEED="${SEED:-42}" + +if [ ! -f "${MANIFEST_LIST}" ]; then + echo "FATAL: Manifest list not found: ${MANIFEST_LIST}" + exit 1 +fi + +TASK_ID="${SLURM_ARRAY_TASK_ID:-0}" +MANIFEST_PATH=$(sed -n "$((TASK_ID + 1))p" "${MANIFEST_LIST}") + +if [ -z "${MANIFEST_PATH}" ]; then + echo "FATAL: No manifest at index ${TASK_ID} in ${MANIFEST_LIST}" + exit 1 +fi + +MANIFEST_BASENAME="$(basename "${MANIFEST_PATH}" .csv)" +MANIFEST_BASENAME="$(basename "${MANIFEST_BASENAME}" .json)" +OUT_DIR="${OUTPUT_ROOT}/${TRIAL_MODE}/${MANIFEST_BASENAME}" + +echo "==================================================================" +echo " iTrialSpace Mask Insertion — Mode 12: Digital Twin Complete (Array)" +echo " Job ID: ${SLURM_JOB_ID:-local} Array Task: ${TASK_ID}" +echo " Node: $(hostname) Date: $(date)" +echo "==================================================================" +echo " MANIFEST_PATH : ${MANIFEST_PATH}" +echo " OUT_DIR : ${OUT_DIR}" +echo "" + +cd "${PROJECT_DIR}" + +if [ ! -f "${MANIFEST_PATH}" ]; then + echo "FATAL: Manifest not found: ${MANIFEST_PATH}" + exit 1 +fi +mkdir -p "${OUT_DIR}" + +CFG_ARG="" +if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then + CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}" +elif [ -f "${CONFIG_PATH}" ]; then + CFG_ARG="--config ${CONFIG_PATH}" +fi + +EXTRA_ARGS="" +[ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run" + +echo "Running: python3 -m itrialspace.mask_inserter run ..." +echo " manifest: ${MANIFEST_PATH}" +echo " output: ${OUT_DIR}" + +python3 -m itrialspace.mask_inserter run \ + --manifest "${MANIFEST_PATH}" \ + --output-dir "${OUT_DIR}" \ + ${CFG_ARG} \ + --trial-name "${TRIAL_MODE}_${MANIFEST_BASENAME}" \ + --seed ${SEED} \ + --n-jobs ${N_JOBS} \ + ${EXTRA_ARGS} +EXIT_CODE=$? +echo "Finished: $(date) Exit: ${EXIT_CODE}" +exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/mask_inserter/mode13_insert_masks.sub b/itrialspace/infra/slurm/mask_inserter/mode13_insert_masks.sub new file mode 100644 index 0000000000000000000000000000000000000000..fb8e317b1c9303808b486c310d5f8bf97cb81e05 --- /dev/null +++ b/itrialspace/infra/slurm/mask_inserter/mode13_insert_masks.sub @@ -0,0 +1,84 @@ +#!/bin/bash +# ────────────────────────────────────────────────────────────────────────────── +# Mode 13: Digital Twin Cross — Mask Insertion +# +# Inserts donor nodule masks from a DIFFERENT patient (possibly a different +# dataset) into the host patient anatomy. The manifest contains separate +# host and donor paths; the inserter reads them directly. +# +# Usage: +# MANIFEST_PATH=.../digital_twin_cross_DLCS24_x_LUNA25.csv sbatch mode13_insert_masks.sub +# ────────────────────────────────────────────────────────────────────────────── + +#SBATCH --job-name=ins_M13_DTcross +#SBATCH --partition=defq +#SBATCH --ntasks=1 +#SBATCH --gpus=0 +#SBATCH --cpus-per-task=8 +#SBATCH --mem=32G +#SBATCH --time=2-00:00:00 +#SBATCH --output=logs/insert_mode13_digital_twin_cross_%j.out +#SBATCH --error=logs/insert_mode13_digital_twin_cross_%j.err + +# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" +itrialspace_activate_conda + + +set -euo pipefail + +BASE_DIR="${ITRIALSPACE_DATA_DIR}" +MANIFEST_ROOT="${ITRIALSPACE_OUTPUT_DIR}/manifests" +OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks" +PROJECT_DIR="${PROJ_DIR}" + +TRIAL_MODE="mode13_digital_twin_cross" +MANIFEST_PATH="${MANIFEST_PATH:-${MANIFEST_ROOT}/${TRIAL_MODE}/digital_twin_cross_DLCS24_x_LUNA25.csv}" +OUT_DIR="${OUT_DIR:-${OUTPUT_ROOT}/${TRIAL_MODE}}" +CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}" +N_JOBS="${N_JOBS:-8}" +DRY_RUN="${DRY_RUN:-false}" +SEED="${SEED:-42}" + +echo "==================================================================" +echo " iTrialSpace Mask Insertion — Mode 13: Digital Twin Cross" +echo " Job ID: ${SLURM_JOB_ID:-local} Node: $(hostname) Date: $(date)" +echo "==================================================================" +echo " MANIFEST_PATH : ${MANIFEST_PATH}" +echo " OUT_DIR : ${OUT_DIR}" +echo " N_JOBS : ${N_JOBS}" +echo "" + +cd "${PROJECT_DIR}" + +if [ ! -f "${MANIFEST_PATH}" ]; then + echo "FATAL: Manifest not found: ${MANIFEST_PATH}" + exit 1 +fi +mkdir -p "${OUT_DIR}" + +CFG_ARG="" +if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then + CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}" +elif [ -f "${CONFIG_PATH}" ]; then + CFG_ARG="--config ${CONFIG_PATH}" +fi + +EXTRA_ARGS="" +[ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run" + +echo "Running: python3 -m itrialspace.mask_inserter run ..." +echo " manifest: ${MANIFEST_PATH}" +echo " output: ${OUT_DIR}" + +python3 -m itrialspace.mask_inserter run \ + --manifest "${MANIFEST_PATH}" \ + --output-dir "${OUT_DIR}" \ + ${CFG_ARG} \ + --trial-name "${TRIAL_MODE}" \ + --seed ${SEED} \ + --n-jobs ${N_JOBS} \ + ${EXTRA_ARGS} +EXIT_CODE=$? +echo "Finished: $(date) Exit: ${EXIT_CODE}" +exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/mask_inserter/mode13_insert_masks_array.sub b/itrialspace/infra/slurm/mask_inserter/mode13_insert_masks_array.sub new file mode 100644 index 0000000000000000000000000000000000000000..c0497691f487eb9e717a7fbb2cd7e3184c78534a --- /dev/null +++ b/itrialspace/infra/slurm/mask_inserter/mode13_insert_masks_array.sub @@ -0,0 +1,103 @@ +#!/bin/bash +# ────────────────────────────────────────────────────────────────────────────── +# Mode 13: Digital Twin Cross — Array Job (one per manifest chunk) +# +# Cross-patient insertion may produce many manifests (one per host×donor +# dataset combination). Use the list_manifests tool to split into chunks, +# then submit an array job. +# +# Usage: +# python itrialspace_mask_inserter/tools/list_manifests.py \ +# --dir /scratch/.../manifests/mode13_digital_twin_cross \ +# --output manifests_mode13.txt +# sbatch --array=0-$(( $(wc -l < manifests_mode13.txt) - 1 )) \ +# mode13_insert_masks_array.sub +# ────────────────────────────────────────────────────────────────────────────── + +#SBATCH --job-name=ins_M13_arr +#SBATCH --partition=defq +#SBATCH --ntasks=1 +#SBATCH --gpus=0 +#SBATCH --cpus-per-task=8 +#SBATCH --mem=32G +#SBATCH --time=2-00:00:00 +#SBATCH --output=logs/insert_mode13_digital_twin_cross_%A_%a.out +#SBATCH --error=logs/insert_mode13_digital_twin_cross_%A_%a.err + +# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" +itrialspace_activate_conda + + +set -euo pipefail + +BASE_DIR="${ITRIALSPACE_DATA_DIR}" +OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks" +PROJECT_DIR="${PROJ_DIR}" + +TRIAL_MODE="mode13_digital_twin_cross" +MANIFEST_LIST="${MANIFEST_LIST:-${PROJECT_DIR}/itrialspace_mask_inserter/slurm_trials/manifests_mode13.txt}" +CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}" +N_JOBS="${N_JOBS:-8}" +DRY_RUN="${DRY_RUN:-false}" +SEED="${SEED:-42}" + +if [ ! -f "${MANIFEST_LIST}" ]; then + echo "FATAL: Manifest list not found: ${MANIFEST_LIST}" + exit 1 +fi + +TASK_ID="${SLURM_ARRAY_TASK_ID:-0}" +MANIFEST_PATH=$(sed -n "$((TASK_ID + 1))p" "${MANIFEST_LIST}") + +if [ -z "${MANIFEST_PATH}" ]; then + echo "FATAL: No manifest at index ${TASK_ID} in ${MANIFEST_LIST}" + exit 1 +fi + +MANIFEST_BASENAME="$(basename "${MANIFEST_PATH}" .csv)" +MANIFEST_BASENAME="$(basename "${MANIFEST_BASENAME}" .json)" +OUT_DIR="${OUTPUT_ROOT}/${TRIAL_MODE}/${MANIFEST_BASENAME}" + +echo "==================================================================" +echo " iTrialSpace Mask Insertion — Mode 13: Digital Twin Cross (Array)" +echo " Job ID: ${SLURM_JOB_ID:-local} Array Task: ${TASK_ID}" +echo " Node: $(hostname) Date: $(date)" +echo "==================================================================" +echo " MANIFEST_PATH : ${MANIFEST_PATH}" +echo " OUT_DIR : ${OUT_DIR}" +echo "" + +cd "${PROJECT_DIR}" + +if [ ! -f "${MANIFEST_PATH}" ]; then + echo "FATAL: Manifest not found: ${MANIFEST_PATH}" + exit 1 +fi +mkdir -p "${OUT_DIR}" + +CFG_ARG="" +if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then + CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}" +elif [ -f "${CONFIG_PATH}" ]; then + CFG_ARG="--config ${CONFIG_PATH}" +fi + +EXTRA_ARGS="" +[ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run" + +echo "Running: python3 -m itrialspace.mask_inserter run ..." +echo " manifest: ${MANIFEST_PATH}" +echo " output: ${OUT_DIR}" + +python3 -m itrialspace.mask_inserter run \ + --manifest "${MANIFEST_PATH}" \ + --output-dir "${OUT_DIR}" \ + ${CFG_ARG} \ + --trial-name "${TRIAL_MODE}_${MANIFEST_BASENAME}" \ + --seed ${SEED} \ + --n-jobs ${N_JOBS} \ + ${EXTRA_ARGS} +EXIT_CODE=$? +echo "Finished: $(date) Exit: ${EXIT_CODE}" +exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/mask_inserter/mode1_insert_masks.sub b/itrialspace/infra/slurm/mask_inserter/mode1_insert_masks.sub new file mode 100644 index 0000000000000000000000000000000000000000..2dffd2e8bc29d728898309dee77fb417d784ba2d --- /dev/null +++ b/itrialspace/infra/slurm/mask_inserter/mode1_insert_masks.sub @@ -0,0 +1,95 @@ +#!/bin/bash +# ────────────────────────────────────────────────────────────────────────────── +# Mode 1: Controlled Prevalence — Mask Insertion +# +# Inserts donor nodule masks into host CTs for the controlled-prevalence +# cohort manifest (single manifest with fixed malignancy prevalence). +# +# Usage: +# sbatch mode1_insert_masks.sub +# sbatch --mem=64G --time=08:00:00 mode1_insert_masks.sub # override +# ────────────────────────────────────────────────────────────────────────────── + +#SBATCH --job-name=ins_M1_Prev +#SBATCH --partition=defq +#SBATCH --ntasks=1 +#SBATCH --gpus=0 +#SBATCH --cpus-per-task=8 +#SBATCH --mem=32G +#SBATCH --time=08:00:00 +#SBATCH --output=logs/insert_mode1_controlled_prevalence_%j.out +#SBATCH --error=logs/insert_mode1_controlled_prevalence_%j.err + +# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" +itrialspace_activate_conda + + +set -euo pipefail + +# ── Site-specific paths (edit these) ───────────────────────────────────────── +BASE_DIR="${ITRIALSPACE_DATA_DIR}" +MANIFEST_ROOT="${ITRIALSPACE_OUTPUT_DIR}/manifests" +OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks" +PROJECT_DIR="${PROJ_DIR}" + +# ── Mode configuration ─────────────────────────────────────────────────────── +TRIAL_MODE="mode1_controlled_prevalence" +MANIFEST_PATH="${MANIFEST_PATH:-${MANIFEST_ROOT}/${TRIAL_MODE}/NLST_cohort.csv}" +OUT_DIR="${OUT_DIR:-${OUTPUT_ROOT}/${TRIAL_MODE}}" +CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}" +N_JOBS="${N_JOBS:-8}" +DRY_RUN="${DRY_RUN:-false}" +SEED="${SEED:-42}" + +# ── Banner ──────────────────────────────────────────────────────────────────── +echo "==================================================================" +echo " iTrialSpace Mask Insertion — Mode 1: Controlled Prevalence" +echo " Job ID: ${SLURM_JOB_ID:-local} Node: $(hostname) Date: $(date)" +echo "==================================================================" +echo " MANIFEST_PATH : ${MANIFEST_PATH}" +echo " OUT_DIR : ${OUT_DIR}" +echo " CONFIG_PATH : ${CONFIG_PATH}" +echo " N_JOBS : ${N_JOBS}" +echo " DRY_RUN : ${DRY_RUN}" +echo "" + +# ── Environment ────────────────────────────────────────────────────────────── +cd "${PROJECT_DIR}" + +# ── Validate ───────────────────────────────────────────────────────────────── +if [ ! -f "${MANIFEST_PATH}" ]; then + echo "FATAL: Manifest not found: ${MANIFEST_PATH}" + exit 1 +fi +mkdir -p "${OUT_DIR}" + +# Resolve config path (falls back to the package's bundled defaults.yaml if unset) +CFG_ARG="" +if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then + CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}" +elif [ -f "${CONFIG_PATH}" ]; then + CFG_ARG="--config ${CONFIG_PATH}" +fi + +# ── Run ────────────────────────────────────────────────────────────────────── +EXTRA_ARGS="" +[ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run" + +echo "Running: python3 -m itrialspace.mask_inserter run ..." +echo " manifest: ${MANIFEST_PATH}" +echo " output: ${OUT_DIR}" + +python3 -m itrialspace.mask_inserter run \ + --manifest "${MANIFEST_PATH}" \ + --output-dir "${OUT_DIR}" \ + ${CFG_ARG} \ + --trial-name "${TRIAL_MODE}" \ + --seed ${SEED} \ + --n-jobs ${N_JOBS} \ + ${EXTRA_ARGS} +EXIT_CODE=$? + +echo "" +echo "Finished: $(date) Exit: ${EXIT_CODE}" +exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/mask_inserter/mode1_insert_masks_array.sub b/itrialspace/infra/slurm/mask_inserter/mode1_insert_masks_array.sub new file mode 100644 index 0000000000000000000000000000000000000000..9b60c0a65230c3e4dd79e792d59616478c185203 --- /dev/null +++ b/itrialspace/infra/slurm/mask_inserter/mode1_insert_masks_array.sub @@ -0,0 +1,108 @@ +#!/bin/bash +# ────────────────────────────────────────────────────────────────────────────── +# Mode 1: Controlled Prevalence — Array Job (multiple manifests) +# +# Reads a manifest list file and processes one manifest per array task. +# +# Usage: +# # 1. Generate the manifest list: +# python itrialspace_mask_inserter/tools/list_manifests.py \ +# --dir /scratch/.../manifests/mode1_controlled_prevalence \ +# --output manifests_mode1.txt +# +# # 2. Submit array job (N = number of manifests - 1): +# sbatch --array=0-$(( $(wc -l < manifests_mode1.txt) - 1 )) \ +# mode1_insert_masks_array.sub +# ────────────────────────────────────────────────────────────────────────────── + +#SBATCH --job-name=ins_M1_arr +#SBATCH --partition=defq +#SBATCH --ntasks=1 +#SBATCH --gpus=0 +#SBATCH --cpus-per-task=8 +#SBATCH --mem=32G +#SBATCH --time=04:00:00 +#SBATCH --output=logs/insert_mode1_controlled_prevalence_%A_%a.out +#SBATCH --error=logs/insert_mode1_controlled_prevalence_%A_%a.err + +# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" +itrialspace_activate_conda + + +set -euo pipefail + +# ── Site-specific paths ────────────────────────────────────────────────────── +BASE_DIR="${ITRIALSPACE_DATA_DIR}" +OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks" +PROJECT_DIR="${PROJ_DIR}" + +TRIAL_MODE="mode1_controlled_prevalence" +MANIFEST_LIST="${MANIFEST_LIST:-${PROJECT_DIR}/itrialspace_mask_inserter/slurm_trials/manifests_mode1.txt}" +CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}" +N_JOBS="${N_JOBS:-8}" +DRY_RUN="${DRY_RUN:-false}" +SEED="${SEED:-42}" + +# ── Resolve manifest for this array task ───────────────────────────────────── +if [ ! -f "${MANIFEST_LIST}" ]; then + echo "FATAL: Manifest list not found: ${MANIFEST_LIST}" + exit 1 +fi + +TASK_ID="${SLURM_ARRAY_TASK_ID:-0}" +MANIFEST_PATH=$(sed -n "$((TASK_ID + 1))p" "${MANIFEST_LIST}") + +if [ -z "${MANIFEST_PATH}" ]; then + echo "FATAL: No manifest at index ${TASK_ID} in ${MANIFEST_LIST}" + exit 1 +fi + +# Derive a unique output subdirectory from the manifest filename +MANIFEST_BASENAME="$(basename "${MANIFEST_PATH}" .csv)" +MANIFEST_BASENAME="$(basename "${MANIFEST_BASENAME}" .json)" +OUT_DIR="${OUTPUT_ROOT}/${TRIAL_MODE}/${MANIFEST_BASENAME}" + +echo "==================================================================" +echo " iTrialSpace Mask Insertion — Mode 1: Controlled Prevalence (Array)" +echo " Job ID: ${SLURM_JOB_ID:-local} Array Task: ${TASK_ID}" +echo " Node: $(hostname) Date: $(date)" +echo "==================================================================" +echo " MANIFEST_PATH : ${MANIFEST_PATH}" +echo " OUT_DIR : ${OUT_DIR}" +echo " N_JOBS : ${N_JOBS}" +echo "" + +cd "${PROJECT_DIR}" + +if [ ! -f "${MANIFEST_PATH}" ]; then + echo "FATAL: Manifest not found: ${MANIFEST_PATH}" + exit 1 +fi +mkdir -p "${OUT_DIR}" + +CFG_ARG="" +if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then + CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}" +elif [ -f "${CONFIG_PATH}" ]; then + CFG_ARG="--config ${CONFIG_PATH}" +fi + +EXTRA_ARGS="" +[ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run" + +echo "Running: python3 -m itrialspace.mask_inserter run ..." +echo " manifest: ${MANIFEST_PATH}" +echo " output: ${OUT_DIR}" + +python3 -m itrialspace.mask_inserter run \ + --manifest "${MANIFEST_PATH}" \ + --output-dir "${OUT_DIR}" \ + ${CFG_ARG} \ + --trial-name "${TRIAL_MODE}_${MANIFEST_BASENAME}" \ + --seed ${SEED} \ + --n-jobs ${N_JOBS} \ + ${EXTRA_ARGS} +EXIT_CODE=$? +echo "Finished: $(date) Exit: ${EXIT_CODE}" +exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/mask_inserter/mode2_insert_masks.sub b/itrialspace/infra/slurm/mask_inserter/mode2_insert_masks.sub new file mode 100644 index 0000000000000000000000000000000000000000..bf586aeeeb074b4a6bf1929844a8e6d02e6c8a5e --- /dev/null +++ b/itrialspace/infra/slurm/mask_inserter/mode2_insert_masks.sub @@ -0,0 +1,87 @@ +#!/bin/bash +# ────────────────────────────────────────────────────────────────────────────── +# Mode 2: Size Detection Curve — Mask Insertion +# +# Inserts donor nodule masks for the size-stratified FROC cohorts. +# Mode 2 produces multiple manifests (one per size bucket), so consider +# using the array job variant (mode2_insert_masks_array.sub) instead. +# +# This script processes a single manifest. Override MANIFEST_PATH to select +# the specific size bucket manifest. +# +# Usage: +# MANIFEST_PATH=.../size_5_10mm.csv sbatch mode2_insert_masks.sub +# ────────────────────────────────────────────────────────────────────────────── + +#SBATCH --job-name=ins_M2_Size +#SBATCH --partition=defq +#SBATCH --ntasks=1 +#SBATCH --gpus=0 +#SBATCH --cpus-per-task=8 +#SBATCH --mem=32G +#SBATCH --time=1-00:00:00 +#SBATCH --output=logs/insert_mode2_size_detection_curve_%j.out +#SBATCH --error=logs/insert_mode2_size_detection_curve_%j.err + +# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" +itrialspace_activate_conda + + +set -euo pipefail + +BASE_DIR="${ITRIALSPACE_DATA_DIR}" +MANIFEST_ROOT="${ITRIALSPACE_OUTPUT_DIR}/manifests" +OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks" +PROJECT_DIR="${PROJ_DIR}" + +TRIAL_MODE="mode2_size_detection_curve" +MANIFEST_PATH="${MANIFEST_PATH:-${MANIFEST_ROOT}/${TRIAL_MODE}/size_curve_5-10mm.csv}" +OUT_DIR="${OUT_DIR:-${OUTPUT_ROOT}/${TRIAL_MODE}}" +CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}" +N_JOBS="${N_JOBS:-8}" +DRY_RUN="${DRY_RUN:-false}" +SEED="${SEED:-42}" + +echo "==================================================================" +echo " iTrialSpace Mask Insertion — Mode 2: Size Detection Curve" +echo " Job ID: ${SLURM_JOB_ID:-local} Node: $(hostname) Date: $(date)" +echo "==================================================================" +echo " MANIFEST_PATH : ${MANIFEST_PATH}" +echo " OUT_DIR : ${OUT_DIR}" +echo " N_JOBS : ${N_JOBS}" +echo "" + +cd "${PROJECT_DIR}" + +if [ ! -f "${MANIFEST_PATH}" ]; then + echo "FATAL: Manifest not found: ${MANIFEST_PATH}" + exit 1 +fi +mkdir -p "${OUT_DIR}" + +CFG_ARG="" +if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then + CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}" +elif [ -f "${CONFIG_PATH}" ]; then + CFG_ARG="--config ${CONFIG_PATH}" +fi + +EXTRA_ARGS="" +[ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run" + +echo "Running: python3 -m itrialspace.mask_inserter run ..." +echo " manifest: ${MANIFEST_PATH}" +echo " output: ${OUT_DIR}" + +python3 -m itrialspace.mask_inserter run \ + --manifest "${MANIFEST_PATH}" \ + --output-dir "${OUT_DIR}" \ + ${CFG_ARG} \ + --trial-name "${TRIAL_MODE}" \ + --seed ${SEED} \ + --n-jobs ${N_JOBS} \ + ${EXTRA_ARGS} +EXIT_CODE=$? +echo "Finished: $(date) Exit: ${EXIT_CODE}" +exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/mask_inserter/mode2_insert_masks_array.sub b/itrialspace/infra/slurm/mask_inserter/mode2_insert_masks_array.sub new file mode 100644 index 0000000000000000000000000000000000000000..b4c9f8162b276472306a6a4e90e861298c67fc3b --- /dev/null +++ b/itrialspace/infra/slurm/mask_inserter/mode2_insert_masks_array.sub @@ -0,0 +1,102 @@ +#!/bin/bash +# ────────────────────────────────────────────────────────────────────────────── +# Mode 2: Size Detection Curve — Array Job (one manifest per size bucket) +# +# Reads a manifest list file and processes one manifest per array task. +# Ideal for Mode 2 which produces ~6 size-bucket manifests. +# +# Usage: +# python itrialspace_mask_inserter/tools/list_manifests.py \ +# --dir /scratch/.../manifests/mode2_size_detection_curve \ +# --output manifests_mode2.txt +# sbatch --array=0-$(( $(wc -l < manifests_mode2.txt) - 1 )) \ +# mode2_insert_masks_array.sub +# ────────────────────────────────────────────────────────────────────────────── + +#SBATCH --job-name=ins_M2_arr +#SBATCH --partition=defq +#SBATCH --ntasks=1 +#SBATCH --gpus=0 +#SBATCH --cpus-per-task=8 +#SBATCH --mem=32G +#SBATCH --time=1-00:00:00 +#SBATCH --output=logs/insert_mode2_size_detection_curve_%A_%a.out +#SBATCH --error=logs/insert_mode2_size_detection_curve_%A_%a.err + +# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" +itrialspace_activate_conda + + +set -euo pipefail + +BASE_DIR="${ITRIALSPACE_DATA_DIR}" +OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks" +PROJECT_DIR="${PROJ_DIR}" + +TRIAL_MODE="mode2_size_detection_curve" +MANIFEST_LIST="${MANIFEST_LIST:-${PROJECT_DIR}/itrialspace_mask_inserter/slurm_trials/manifests_mode2.txt}" +CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}" +N_JOBS="${N_JOBS:-8}" +DRY_RUN="${DRY_RUN:-false}" +SEED="${SEED:-42}" + +if [ ! -f "${MANIFEST_LIST}" ]; then + echo "FATAL: Manifest list not found: ${MANIFEST_LIST}" + exit 1 +fi + +TASK_ID="${SLURM_ARRAY_TASK_ID:-0}" +MANIFEST_PATH=$(sed -n "$((TASK_ID + 1))p" "${MANIFEST_LIST}") + +if [ -z "${MANIFEST_PATH}" ]; then + echo "FATAL: No manifest at index ${TASK_ID} in ${MANIFEST_LIST}" + exit 1 +fi + +MANIFEST_BASENAME="$(basename "${MANIFEST_PATH}" .csv)" +MANIFEST_BASENAME="$(basename "${MANIFEST_BASENAME}" .json)" +OUT_DIR="${OUTPUT_ROOT}/${TRIAL_MODE}/${MANIFEST_BASENAME}" + +echo "==================================================================" +echo " iTrialSpace Mask Insertion — Mode 2: Size Detection Curve (Array)" +echo " Job ID: ${SLURM_JOB_ID:-local} Array Task: ${TASK_ID}" +echo " Node: $(hostname) Date: $(date)" +echo "==================================================================" +echo " MANIFEST_PATH : ${MANIFEST_PATH}" +echo " OUT_DIR : ${OUT_DIR}" +echo "" + +cd "${PROJECT_DIR}" + +if [ ! -f "${MANIFEST_PATH}" ]; then + echo "FATAL: Manifest not found: ${MANIFEST_PATH}" + exit 1 +fi +mkdir -p "${OUT_DIR}" + +CFG_ARG="" +if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then + CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}" +elif [ -f "${CONFIG_PATH}" ]; then + CFG_ARG="--config ${CONFIG_PATH}" +fi + +EXTRA_ARGS="" +[ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run" + +echo "Running: python3 -m itrialspace.mask_inserter run ..." +echo " manifest: ${MANIFEST_PATH}" +echo " output: ${OUT_DIR}" + +python3 -m itrialspace.mask_inserter run \ + --manifest "${MANIFEST_PATH}" \ + --output-dir "${OUT_DIR}" \ + ${CFG_ARG} \ + --trial-name "${TRIAL_MODE}_${MANIFEST_BASENAME}" \ + --seed ${SEED} \ + --n-jobs ${N_JOBS} \ + ${EXTRA_ARGS} +EXIT_CODE=$? +echo "Finished: $(date) Exit: ${EXIT_CODE}" +exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/mask_inserter/mode3_insert_masks.sub b/itrialspace/infra/slurm/mask_inserter/mode3_insert_masks.sub new file mode 100644 index 0000000000000000000000000000000000000000..763944e56760a9d738f82b17d2b258ece8fcbb90 --- /dev/null +++ b/itrialspace/infra/slurm/mask_inserter/mode3_insert_masks.sub @@ -0,0 +1,84 @@ +#!/bin/bash +# ────────────────────────────────────────────────────────────────────────────── +# Mode 3: Location Sensitivity — Mask Insertion +# +# Inserts donor nodule masks for lobe-stratified cohorts. +# Mode 3 produces one manifest per lobe (5 lobes), so consider the +# array job variant (mode3_insert_masks_array.sub) for batch processing. +# +# Usage: +# MANIFEST_PATH=.../lobe_RUL.csv sbatch mode3_insert_masks.sub +# ────────────────────────────────────────────────────────────────────────────── + +#SBATCH --job-name=ins_M3_Loc +#SBATCH --partition=defq +#SBATCH --ntasks=1 +#SBATCH --gpus=0 +#SBATCH --cpus-per-task=8 +#SBATCH --mem=32G +#SBATCH --time=1-00:00:00 +#SBATCH --output=logs/insert_mode3_location_sensitivity_%j.out +#SBATCH --error=logs/insert_mode3_location_sensitivity_%j.err + +# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" +itrialspace_activate_conda + + +set -euo pipefail + +BASE_DIR="${ITRIALSPACE_DATA_DIR}" +MANIFEST_ROOT="${ITRIALSPACE_OUTPUT_DIR}/manifests" +OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks" +PROJECT_DIR="${PROJ_DIR}" + +TRIAL_MODE="mode3_location_sensitivity" +MANIFEST_PATH="${MANIFEST_PATH:-${MANIFEST_ROOT}/${TRIAL_MODE}/lobe_right_lung_upper_lobe.csv}" +OUT_DIR="${OUT_DIR:-${OUTPUT_ROOT}/${TRIAL_MODE}}" +CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}" +N_JOBS="${N_JOBS:-8}" +DRY_RUN="${DRY_RUN:-false}" +SEED="${SEED:-42}" + +echo "==================================================================" +echo " iTrialSpace Mask Insertion — Mode 3: Location Sensitivity" +echo " Job ID: ${SLURM_JOB_ID:-local} Node: $(hostname) Date: $(date)" +echo "==================================================================" +echo " MANIFEST_PATH : ${MANIFEST_PATH}" +echo " OUT_DIR : ${OUT_DIR}" +echo " N_JOBS : ${N_JOBS}" +echo "" + +cd "${PROJECT_DIR}" + +if [ ! -f "${MANIFEST_PATH}" ]; then + echo "FATAL: Manifest not found: ${MANIFEST_PATH}" + exit 1 +fi +mkdir -p "${OUT_DIR}" + +CFG_ARG="" +if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then + CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}" +elif [ -f "${CONFIG_PATH}" ]; then + CFG_ARG="--config ${CONFIG_PATH}" +fi + +EXTRA_ARGS="" +[ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run" + +echo "Running: python3 -m itrialspace.mask_inserter run ..." +echo " manifest: ${MANIFEST_PATH}" +echo " output: ${OUT_DIR}" + +python3 -m itrialspace.mask_inserter run \ + --manifest "${MANIFEST_PATH}" \ + --output-dir "${OUT_DIR}" \ + ${CFG_ARG} \ + --trial-name "${TRIAL_MODE}" \ + --seed ${SEED} \ + --n-jobs ${N_JOBS} \ + ${EXTRA_ARGS} +EXIT_CODE=$? +echo "Finished: $(date) Exit: ${EXIT_CODE}" +exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/mask_inserter/mode3_insert_masks_array.sub b/itrialspace/infra/slurm/mask_inserter/mode3_insert_masks_array.sub new file mode 100644 index 0000000000000000000000000000000000000000..2169dccc8819d56fc895a2cc4560d37db72cb449 --- /dev/null +++ b/itrialspace/infra/slurm/mask_inserter/mode3_insert_masks_array.sub @@ -0,0 +1,101 @@ +#!/bin/bash +# ────────────────────────────────────────────────────────────────────────────── +# Mode 3: Location Sensitivity — Array Job (one manifest per lobe) +# +# Ideal for Mode 3 which produces ~5 lobe-stratified manifests. +# +# Usage: +# python itrialspace_mask_inserter/tools/list_manifests.py \ +# --dir /scratch/.../manifests/mode3_location_sensitivity \ +# --output manifests_mode3.txt +# sbatch --array=0-$(( $(wc -l < manifests_mode3.txt) - 1 )) \ +# mode3_insert_masks_array.sub +# ────────────────────────────────────────────────────────────────────────────── + +#SBATCH --job-name=ins_M3_arr +#SBATCH --partition=defq +#SBATCH --ntasks=1 +#SBATCH --gpus=0 +#SBATCH --cpus-per-task=8 +#SBATCH --mem=32G +#SBATCH --time=1-00:00:00 +#SBATCH --output=logs/insert_mode3_location_sensitivity_%A_%a.out +#SBATCH --error=logs/insert_mode3_location_sensitivity_%A_%a.err + +# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" +itrialspace_activate_conda + + +set -euo pipefail + +BASE_DIR="${ITRIALSPACE_DATA_DIR}" +OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks" +PROJECT_DIR="${PROJ_DIR}" + +TRIAL_MODE="mode3_location_sensitivity" +MANIFEST_LIST="${MANIFEST_LIST:-${PROJECT_DIR}/itrialspace_mask_inserter/slurm_trials/manifests_mode3.txt}" +CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}" +N_JOBS="${N_JOBS:-8}" +DRY_RUN="${DRY_RUN:-false}" +SEED="${SEED:-42}" + +if [ ! -f "${MANIFEST_LIST}" ]; then + echo "FATAL: Manifest list not found: ${MANIFEST_LIST}" + exit 1 +fi + +TASK_ID="${SLURM_ARRAY_TASK_ID:-0}" +MANIFEST_PATH=$(sed -n "$((TASK_ID + 1))p" "${MANIFEST_LIST}") + +if [ -z "${MANIFEST_PATH}" ]; then + echo "FATAL: No manifest at index ${TASK_ID} in ${MANIFEST_LIST}" + exit 1 +fi + +MANIFEST_BASENAME="$(basename "${MANIFEST_PATH}" .csv)" +MANIFEST_BASENAME="$(basename "${MANIFEST_BASENAME}" .json)" +OUT_DIR="${OUTPUT_ROOT}/${TRIAL_MODE}/${MANIFEST_BASENAME}" + +echo "==================================================================" +echo " iTrialSpace Mask Insertion — Mode 3: Location Sensitivity (Array)" +echo " Job ID: ${SLURM_JOB_ID:-local} Array Task: ${TASK_ID}" +echo " Node: $(hostname) Date: $(date)" +echo "==================================================================" +echo " MANIFEST_PATH : ${MANIFEST_PATH}" +echo " OUT_DIR : ${OUT_DIR}" +echo "" + +cd "${PROJECT_DIR}" + +if [ ! -f "${MANIFEST_PATH}" ]; then + echo "FATAL: Manifest not found: ${MANIFEST_PATH}" + exit 1 +fi +mkdir -p "${OUT_DIR}" + +CFG_ARG="" +if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then + CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}" +elif [ -f "${CONFIG_PATH}" ]; then + CFG_ARG="--config ${CONFIG_PATH}" +fi + +EXTRA_ARGS="" +[ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run" + +echo "Running: python3 -m itrialspace.mask_inserter run ..." +echo " manifest: ${MANIFEST_PATH}" +echo " output: ${OUT_DIR}" + +python3 -m itrialspace.mask_inserter run \ + --manifest "${MANIFEST_PATH}" \ + --output-dir "${OUT_DIR}" \ + ${CFG_ARG} \ + --trial-name "${TRIAL_MODE}_${MANIFEST_BASENAME}" \ + --seed ${SEED} \ + --n-jobs ${N_JOBS} \ + ${EXTRA_ARGS} +EXIT_CODE=$? +echo "Finished: $(date) Exit: ${EXIT_CODE}" +exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/mask_inserter/mode4_insert_masks.sub b/itrialspace/infra/slurm/mask_inserter/mode4_insert_masks.sub new file mode 100644 index 0000000000000000000000000000000000000000..15a9bdd059c74e8023919b4f0b0cd93c49bcac82 --- /dev/null +++ b/itrialspace/infra/slurm/mask_inserter/mode4_insert_masks.sub @@ -0,0 +1,84 @@ +#!/bin/bash +# ────────────────────────────────────────────────────────────────────────────── +# Mode 4: Demographic Stratification — Mask Insertion +# +# Inserts donor nodule masks for demographic-stratified cohorts. +# Mode 4 may produce multiple manifests (one per demographic stratum). +# Consider the array variant for batch processing. +# +# Usage: +# sbatch mode4_insert_masks.sub +# ────────────────────────────────────────────────────────────────────────────── + +#SBATCH --job-name=ins_M4_Demo +#SBATCH --partition=defq +#SBATCH --ntasks=1 +#SBATCH --gpus=0 +#SBATCH --cpus-per-task=8 +#SBATCH --mem=32G +#SBATCH --time=04:00:00 +#SBATCH --output=logs/insert_mode4_demographic_stratification_%j.out +#SBATCH --error=logs/insert_mode4_demographic_stratification_%j.err + +# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" +itrialspace_activate_conda + + +set -euo pipefail + +BASE_DIR="${ITRIALSPACE_DATA_DIR}" +MANIFEST_ROOT="${ITRIALSPACE_OUTPUT_DIR}/manifests" +OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks" +PROJECT_DIR="${PROJ_DIR}" + +TRIAL_MODE="mode4_demographic_stratification" +MANIFEST_PATH="${MANIFEST_PATH:-${MANIFEST_ROOT}/${TRIAL_MODE}/demo_stratum_0.csv}" +OUT_DIR="${OUT_DIR:-${OUTPUT_ROOT}/${TRIAL_MODE}}" +CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}" +N_JOBS="${N_JOBS:-8}" +DRY_RUN="${DRY_RUN:-false}" +SEED="${SEED:-42}" + +echo "==================================================================" +echo " iTrialSpace Mask Insertion — Mode 4: Demographic Stratification" +echo " Job ID: ${SLURM_JOB_ID:-local} Node: $(hostname) Date: $(date)" +echo "==================================================================" +echo " MANIFEST_PATH : ${MANIFEST_PATH}" +echo " OUT_DIR : ${OUT_DIR}" +echo " N_JOBS : ${N_JOBS}" +echo "" + +cd "${PROJECT_DIR}" + +if [ ! -f "${MANIFEST_PATH}" ]; then + echo "FATAL: Manifest not found: ${MANIFEST_PATH}" + exit 1 +fi +mkdir -p "${OUT_DIR}" + +CFG_ARG="" +if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then + CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}" +elif [ -f "${CONFIG_PATH}" ]; then + CFG_ARG="--config ${CONFIG_PATH}" +fi + +EXTRA_ARGS="" +[ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run" + +echo "Running: python3 -m itrialspace.mask_inserter run ..." +echo " manifest: ${MANIFEST_PATH}" +echo " output: ${OUT_DIR}" + +python3 -m itrialspace.mask_inserter run \ + --manifest "${MANIFEST_PATH}" \ + --output-dir "${OUT_DIR}" \ + ${CFG_ARG} \ + --trial-name "${TRIAL_MODE}" \ + --seed ${SEED} \ + --n-jobs ${N_JOBS} \ + ${EXTRA_ARGS} +EXIT_CODE=$? +echo "Finished: $(date) Exit: ${EXIT_CODE}" +exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/mask_inserter/mode4_insert_masks_array.sub b/itrialspace/infra/slurm/mask_inserter/mode4_insert_masks_array.sub new file mode 100644 index 0000000000000000000000000000000000000000..74ed0c10894ca3d2d55a47e147d739f4459f4e28 --- /dev/null +++ b/itrialspace/infra/slurm/mask_inserter/mode4_insert_masks_array.sub @@ -0,0 +1,99 @@ +#!/bin/bash +# ────────────────────────────────────────────────────────────────────────────── +# Mode 4: Demographic Stratification — Array Job (one per stratum) +# +# Usage: +# python itrialspace_mask_inserter/tools/list_manifests.py \ +# --dir /scratch/.../manifests/mode4_demographic_stratification \ +# --output manifests_mode4.txt +# sbatch --array=0-$(( $(wc -l < manifests_mode4.txt) - 1 )) \ +# mode4_insert_masks_array.sub +# ────────────────────────────────────────────────────────────────────────────── + +#SBATCH --job-name=ins_M4_arr +#SBATCH --partition=defq +#SBATCH --ntasks=1 +#SBATCH --gpus=0 +#SBATCH --cpus-per-task=8 +#SBATCH --mem=32G +#SBATCH --time=04:00:00 +#SBATCH --output=logs/insert_mode4_demographic_stratification_%A_%a.out +#SBATCH --error=logs/insert_mode4_demographic_stratification_%A_%a.err + +# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" +itrialspace_activate_conda + + +set -euo pipefail + +BASE_DIR="${ITRIALSPACE_DATA_DIR}" +OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks" +PROJECT_DIR="${PROJ_DIR}" + +TRIAL_MODE="mode4_demographic_stratification" +MANIFEST_LIST="${MANIFEST_LIST:-${PROJECT_DIR}/itrialspace_mask_inserter/slurm_trials/manifests_mode4.txt}" +CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}" +N_JOBS="${N_JOBS:-8}" +DRY_RUN="${DRY_RUN:-false}" +SEED="${SEED:-42}" + +if [ ! -f "${MANIFEST_LIST}" ]; then + echo "FATAL: Manifest list not found: ${MANIFEST_LIST}" + exit 1 +fi + +TASK_ID="${SLURM_ARRAY_TASK_ID:-0}" +MANIFEST_PATH=$(sed -n "$((TASK_ID + 1))p" "${MANIFEST_LIST}") + +if [ -z "${MANIFEST_PATH}" ]; then + echo "FATAL: No manifest at index ${TASK_ID} in ${MANIFEST_LIST}" + exit 1 +fi + +MANIFEST_BASENAME="$(basename "${MANIFEST_PATH}" .csv)" +MANIFEST_BASENAME="$(basename "${MANIFEST_BASENAME}" .json)" +OUT_DIR="${OUTPUT_ROOT}/${TRIAL_MODE}/${MANIFEST_BASENAME}" + +echo "==================================================================" +echo " iTrialSpace Mask Insertion — Mode 4: Demographic Strat (Array)" +echo " Job ID: ${SLURM_JOB_ID:-local} Array Task: ${TASK_ID}" +echo " Node: $(hostname) Date: $(date)" +echo "==================================================================" +echo " MANIFEST_PATH : ${MANIFEST_PATH}" +echo " OUT_DIR : ${OUT_DIR}" +echo "" + +cd "${PROJECT_DIR}" + +if [ ! -f "${MANIFEST_PATH}" ]; then + echo "FATAL: Manifest not found: ${MANIFEST_PATH}" + exit 1 +fi +mkdir -p "${OUT_DIR}" + +CFG_ARG="" +if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then + CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}" +elif [ -f "${CONFIG_PATH}" ]; then + CFG_ARG="--config ${CONFIG_PATH}" +fi + +EXTRA_ARGS="" +[ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run" + +echo "Running: python3 -m itrialspace.mask_inserter run ..." +echo " manifest: ${MANIFEST_PATH}" +echo " output: ${OUT_DIR}" + +python3 -m itrialspace.mask_inserter run \ + --manifest "${MANIFEST_PATH}" \ + --output-dir "${OUT_DIR}" \ + ${CFG_ARG} \ + --trial-name "${TRIAL_MODE}_${MANIFEST_BASENAME}" \ + --seed ${SEED} \ + --n-jobs ${N_JOBS} \ + ${EXTRA_ARGS} +EXIT_CODE=$? +echo "Finished: $(date) Exit: ${EXIT_CODE}" +exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/mask_inserter/mode5_insert_masks.sub b/itrialspace/infra/slurm/mask_inserter/mode5_insert_masks.sub new file mode 100644 index 0000000000000000000000000000000000000000..34e3555b0e79e815cd090400a5d8d65157b49998 --- /dev/null +++ b/itrialspace/infra/slurm/mask_inserter/mode5_insert_masks.sub @@ -0,0 +1,84 @@ +#!/bin/bash +# ────────────────────────────────────────────────────────────────────────────── +# Mode 5: Counterfactual — Mask Insertion +# +# Inserts donor nodule masks for counterfactual cohorts (same cohort, +# one parameter varied). Multiple manifests may exist (one per +# counterfactual condition). Consider the array variant for batch. +# +# Usage: +# sbatch mode5_insert_masks.sub +# ────────────────────────────────────────────────────────────────────────────── + +#SBATCH --job-name=ins_M5_CF +#SBATCH --partition=defq +#SBATCH --ntasks=1 +#SBATCH --gpus=0 +#SBATCH --cpus-per-task=8 +#SBATCH --mem=32G +#SBATCH --time=08:00:00 +#SBATCH --output=logs/insert_mode5_counterfactual_%j.out +#SBATCH --error=logs/insert_mode5_counterfactual_%j.err + +# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" +itrialspace_activate_conda + + +set -euo pipefail + +BASE_DIR="${ITRIALSPACE_DATA_DIR}" +MANIFEST_ROOT="${ITRIALSPACE_OUTPUT_DIR}/manifests" +OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks" +PROJECT_DIR="${PROJ_DIR}" + +TRIAL_MODE="mode5_counterfactual" +MANIFEST_PATH="${MANIFEST_PATH:-${MANIFEST_ROOT}/${TRIAL_MODE}/counterfactual_malignancy_prevalence=0.05.csv}" +OUT_DIR="${OUT_DIR:-${OUTPUT_ROOT}/${TRIAL_MODE}}" +CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}" +N_JOBS="${N_JOBS:-8}" +DRY_RUN="${DRY_RUN:-false}" +SEED="${SEED:-42}" + +echo "==================================================================" +echo " iTrialSpace Mask Insertion — Mode 5: Counterfactual" +echo " Job ID: ${SLURM_JOB_ID:-local} Node: $(hostname) Date: $(date)" +echo "==================================================================" +echo " MANIFEST_PATH : ${MANIFEST_PATH}" +echo " OUT_DIR : ${OUT_DIR}" +echo " N_JOBS : ${N_JOBS}" +echo "" + +cd "${PROJECT_DIR}" + +if [ ! -f "${MANIFEST_PATH}" ]; then + echo "FATAL: Manifest not found: ${MANIFEST_PATH}" + exit 1 +fi +mkdir -p "${OUT_DIR}" + +CFG_ARG="" +if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then + CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}" +elif [ -f "${CONFIG_PATH}" ]; then + CFG_ARG="--config ${CONFIG_PATH}" +fi + +EXTRA_ARGS="" +[ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run" + +echo "Running: python3 -m itrialspace.mask_inserter run ..." +echo " manifest: ${MANIFEST_PATH}" +echo " output: ${OUT_DIR}" + +python3 -m itrialspace.mask_inserter run \ + --manifest "${MANIFEST_PATH}" \ + --output-dir "${OUT_DIR}" \ + ${CFG_ARG} \ + --trial-name "${TRIAL_MODE}" \ + --seed ${SEED} \ + --n-jobs ${N_JOBS} \ + ${EXTRA_ARGS} +EXIT_CODE=$? +echo "Finished: $(date) Exit: ${EXIT_CODE}" +exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/mask_inserter/mode5_insert_masks_array.sub b/itrialspace/infra/slurm/mask_inserter/mode5_insert_masks_array.sub new file mode 100644 index 0000000000000000000000000000000000000000..a0e073e521b481d4baa87c9238784eb63461705d --- /dev/null +++ b/itrialspace/infra/slurm/mask_inserter/mode5_insert_masks_array.sub @@ -0,0 +1,99 @@ +#!/bin/bash +# ────────────────────────────────────────────────────────────────────────────── +# Mode 5: Counterfactual — Array Job (one per counterfactual condition) +# +# Usage: +# python itrialspace_mask_inserter/tools/list_manifests.py \ +# --dir /scratch/.../manifests/mode5_counterfactual \ +# --output manifests_mode5.txt +# sbatch --array=0-$(( $(wc -l < manifests_mode5.txt) - 1 )) \ +# mode5_insert_masks_array.sub +# ────────────────────────────────────────────────────────────────────────────── + +#SBATCH --job-name=ins_M5_arr +#SBATCH --partition=defq +#SBATCH --ntasks=1 +#SBATCH --gpus=0 +#SBATCH --cpus-per-task=8 +#SBATCH --mem=32G +#SBATCH --time=04:00:00 +#SBATCH --output=logs/insert_mode5_counterfactual_%A_%a.out +#SBATCH --error=logs/insert_mode5_counterfactual_%A_%a.err + +# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" +itrialspace_activate_conda + + +set -euo pipefail + +BASE_DIR="${ITRIALSPACE_DATA_DIR}" +OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks" +PROJECT_DIR="${PROJ_DIR}" + +TRIAL_MODE="mode5_counterfactual" +MANIFEST_LIST="${MANIFEST_LIST:-${PROJECT_DIR}/itrialspace_mask_inserter/slurm_trials/manifests_mode5.txt}" +CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}" +N_JOBS="${N_JOBS:-8}" +DRY_RUN="${DRY_RUN:-false}" +SEED="${SEED:-42}" + +if [ ! -f "${MANIFEST_LIST}" ]; then + echo "FATAL: Manifest list not found: ${MANIFEST_LIST}" + exit 1 +fi + +TASK_ID="${SLURM_ARRAY_TASK_ID:-0}" +MANIFEST_PATH=$(sed -n "$((TASK_ID + 1))p" "${MANIFEST_LIST}") + +if [ -z "${MANIFEST_PATH}" ]; then + echo "FATAL: No manifest at index ${TASK_ID} in ${MANIFEST_LIST}" + exit 1 +fi + +MANIFEST_BASENAME="$(basename "${MANIFEST_PATH}" .csv)" +MANIFEST_BASENAME="$(basename "${MANIFEST_BASENAME}" .json)" +OUT_DIR="${OUTPUT_ROOT}/${TRIAL_MODE}/${MANIFEST_BASENAME}" + +echo "==================================================================" +echo " iTrialSpace Mask Insertion — Mode 5: Counterfactual (Array)" +echo " Job ID: ${SLURM_JOB_ID:-local} Array Task: ${TASK_ID}" +echo " Node: $(hostname) Date: $(date)" +echo "==================================================================" +echo " MANIFEST_PATH : ${MANIFEST_PATH}" +echo " OUT_DIR : ${OUT_DIR}" +echo "" + +cd "${PROJECT_DIR}" + +if [ ! -f "${MANIFEST_PATH}" ]; then + echo "FATAL: Manifest not found: ${MANIFEST_PATH}" + exit 1 +fi +mkdir -p "${OUT_DIR}" + +CFG_ARG="" +if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then + CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}" +elif [ -f "${CONFIG_PATH}" ]; then + CFG_ARG="--config ${CONFIG_PATH}" +fi + +EXTRA_ARGS="" +[ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run" + +echo "Running: python3 -m itrialspace.mask_inserter run ..." +echo " manifest: ${MANIFEST_PATH}" +echo " output: ${OUT_DIR}" + +python3 -m itrialspace.mask_inserter run \ + --manifest "${MANIFEST_PATH}" \ + --output-dir "${OUT_DIR}" \ + ${CFG_ARG} \ + --trial-name "${TRIAL_MODE}_${MANIFEST_BASENAME}" \ + --seed ${SEED} \ + --n-jobs ${N_JOBS} \ + ${EXTRA_ARGS} +EXIT_CODE=$? +echo "Finished: $(date) Exit: ${EXIT_CODE}" +exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/mask_inserter/mode6_insert_masks.sub b/itrialspace/infra/slurm/mask_inserter/mode6_insert_masks.sub new file mode 100644 index 0000000000000000000000000000000000000000..114642641ef8fd109a51c5c3e254132f78a10828 --- /dev/null +++ b/itrialspace/infra/slurm/mask_inserter/mode6_insert_masks.sub @@ -0,0 +1,84 @@ +#!/bin/bash +# ────────────────────────────────────────────────────────────────────────────── +# Mode 6: Cross-Dataset — Mask Insertion +# +# Inserts donor nodule masks for cross-dataset cohorts (one cohort per +# dataset as sole donor source). Multiple manifests — consider the array +# variant for batch processing. +# +# Usage: +# sbatch mode6_insert_masks.sub +# ────────────────────────────────────────────────────────────────────────────── + +#SBATCH --job-name=ins_M6_XDS +#SBATCH --partition=defq +#SBATCH --ntasks=1 +#SBATCH --gpus=0 +#SBATCH --cpus-per-task=8 +#SBATCH --mem=32G +#SBATCH --time=08:00:00 +#SBATCH --output=logs/insert_mode6_cross_dataset_%j.out +#SBATCH --error=logs/insert_mode6_cross_dataset_%j.err + +# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" +itrialspace_activate_conda + + +set -euo pipefail + +BASE_DIR="${ITRIALSPACE_DATA_DIR}" +MANIFEST_ROOT="${ITRIALSPACE_OUTPUT_DIR}/manifests" +OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks" +PROJECT_DIR="${PROJ_DIR}" + +TRIAL_MODE="mode6_cross_dataset" +MANIFEST_PATH="${MANIFEST_PATH:-${MANIFEST_ROOT}/${TRIAL_MODE}/cross_ds_LUNA25.csv}" +OUT_DIR="${OUT_DIR:-${OUTPUT_ROOT}/${TRIAL_MODE}}" +CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}" +N_JOBS="${N_JOBS:-8}" +DRY_RUN="${DRY_RUN:-false}" +SEED="${SEED:-42}" + +echo "==================================================================" +echo " iTrialSpace Mask Insertion — Mode 6: Cross-Dataset" +echo " Job ID: ${SLURM_JOB_ID:-local} Node: $(hostname) Date: $(date)" +echo "==================================================================" +echo " MANIFEST_PATH : ${MANIFEST_PATH}" +echo " OUT_DIR : ${OUT_DIR}" +echo " N_JOBS : ${N_JOBS}" +echo "" + +cd "${PROJECT_DIR}" + +if [ ! -f "${MANIFEST_PATH}" ]; then + echo "FATAL: Manifest not found: ${MANIFEST_PATH}" + exit 1 +fi +mkdir -p "${OUT_DIR}" + +CFG_ARG="" +if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then + CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}" +elif [ -f "${CONFIG_PATH}" ]; then + CFG_ARG="--config ${CONFIG_PATH}" +fi + +EXTRA_ARGS="" +[ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run" + +echo "Running: python3 -m itrialspace.mask_inserter run ..." +echo " manifest: ${MANIFEST_PATH}" +echo " output: ${OUT_DIR}" + +python3 -m itrialspace.mask_inserter run \ + --manifest "${MANIFEST_PATH}" \ + --output-dir "${OUT_DIR}" \ + ${CFG_ARG} \ + --trial-name "${TRIAL_MODE}" \ + --seed ${SEED} \ + --n-jobs ${N_JOBS} \ + ${EXTRA_ARGS} +EXIT_CODE=$? +echo "Finished: $(date) Exit: ${EXIT_CODE}" +exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/mask_inserter/mode6_insert_masks_array.sub b/itrialspace/infra/slurm/mask_inserter/mode6_insert_masks_array.sub new file mode 100644 index 0000000000000000000000000000000000000000..7298bfbc05c83fba494f532a888abf5a04396329 --- /dev/null +++ b/itrialspace/infra/slurm/mask_inserter/mode6_insert_masks_array.sub @@ -0,0 +1,99 @@ +#!/bin/bash +# ────────────────────────────────────────────────────────────────────────────── +# Mode 6: Cross-Dataset — Array Job (one manifest per donor dataset) +# +# Usage: +# python itrialspace_mask_inserter/tools/list_manifests.py \ +# --dir /scratch/.../manifests/mode6_cross_dataset \ +# --output manifests_mode6.txt +# sbatch --array=0-$(( $(wc -l < manifests_mode6.txt) - 1 )) \ +# mode6_insert_masks_array.sub +# ────────────────────────────────────────────────────────────────────────────── + +#SBATCH --job-name=ins_M6_arr +#SBATCH --partition=defq +#SBATCH --ntasks=1 +#SBATCH --gpus=0 +#SBATCH --cpus-per-task=8 +#SBATCH --mem=32G +#SBATCH --time=04:00:00 +#SBATCH --output=logs/insert_mode6_cross_dataset_%A_%a.out +#SBATCH --error=logs/insert_mode6_cross_dataset_%A_%a.err + +# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" +itrialspace_activate_conda + + +set -euo pipefail + +BASE_DIR="${ITRIALSPACE_DATA_DIR}" +OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks" +PROJECT_DIR="${PROJ_DIR}" + +TRIAL_MODE="mode6_cross_dataset" +MANIFEST_LIST="${MANIFEST_LIST:-${PROJECT_DIR}/itrialspace_mask_inserter/slurm_trials/manifests_mode6.txt}" +CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}" +N_JOBS="${N_JOBS:-8}" +DRY_RUN="${DRY_RUN:-false}" +SEED="${SEED:-42}" + +if [ ! -f "${MANIFEST_LIST}" ]; then + echo "FATAL: Manifest list not found: ${MANIFEST_LIST}" + exit 1 +fi + +TASK_ID="${SLURM_ARRAY_TASK_ID:-0}" +MANIFEST_PATH=$(sed -n "$((TASK_ID + 1))p" "${MANIFEST_LIST}") + +if [ -z "${MANIFEST_PATH}" ]; then + echo "FATAL: No manifest at index ${TASK_ID} in ${MANIFEST_LIST}" + exit 1 +fi + +MANIFEST_BASENAME="$(basename "${MANIFEST_PATH}" .csv)" +MANIFEST_BASENAME="$(basename "${MANIFEST_BASENAME}" .json)" +OUT_DIR="${OUTPUT_ROOT}/${TRIAL_MODE}/${MANIFEST_BASENAME}" + +echo "==================================================================" +echo " iTrialSpace Mask Insertion — Mode 6: Cross-Dataset (Array)" +echo " Job ID: ${SLURM_JOB_ID:-local} Array Task: ${TASK_ID}" +echo " Node: $(hostname) Date: $(date)" +echo "==================================================================" +echo " MANIFEST_PATH : ${MANIFEST_PATH}" +echo " OUT_DIR : ${OUT_DIR}" +echo "" + +cd "${PROJECT_DIR}" + +if [ ! -f "${MANIFEST_PATH}" ]; then + echo "FATAL: Manifest not found: ${MANIFEST_PATH}" + exit 1 +fi +mkdir -p "${OUT_DIR}" + +CFG_ARG="" +if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then + CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}" +elif [ -f "${CONFIG_PATH}" ]; then + CFG_ARG="--config ${CONFIG_PATH}" +fi + +EXTRA_ARGS="" +[ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run" + +echo "Running: python3 -m itrialspace.mask_inserter run ..." +echo " manifest: ${MANIFEST_PATH}" +echo " output: ${OUT_DIR}" + +python3 -m itrialspace.mask_inserter run \ + --manifest "${MANIFEST_PATH}" \ + --output-dir "${OUT_DIR}" \ + ${CFG_ARG} \ + --trial-name "${TRIAL_MODE}_${MANIFEST_BASENAME}" \ + --seed ${SEED} \ + --n-jobs ${N_JOBS} \ + ${EXTRA_ARGS} +EXIT_CODE=$? +echo "Finished: $(date) Exit: ${EXIT_CODE}" +exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/mask_inserter/mode7_insert_masks.sub b/itrialspace/infra/slurm/mask_inserter/mode7_insert_masks.sub new file mode 100644 index 0000000000000000000000000000000000000000..08594832d93b8fe1e69821f6847b50424d9baaa4 --- /dev/null +++ b/itrialspace/infra/slurm/mask_inserter/mode7_insert_masks.sub @@ -0,0 +1,86 @@ +#!/bin/bash +# ────────────────────────────────────────────────────────────────────────────── +# Mode 7: Bootstrap Confidence — Mask Insertion +# +# Inserts donor nodule masks for bootstrap replicates. Mode 7 produces +# N manifests (e.g., 100 bootstrap replicates). The array job variant +# (mode7_insert_masks_array.sub) is STRONGLY recommended for this mode. +# +# This script processes a single manifest. +# +# Usage: +# MANIFEST_PATH=.../bootstrap_boot042.csv sbatch mode7_insert_masks.sub +# ────────────────────────────────────────────────────────────────────────────── + +#SBATCH --job-name=ins_M7_Boot +#SBATCH --partition=defq +#SBATCH --ntasks=1 +#SBATCH --gpus=0 +#SBATCH --cpus-per-task=8 +#SBATCH --mem=32G +#SBATCH --time=08:00:00 +#SBATCH --output=logs/insert_mode7_bootstrap_confidence_%j.out +#SBATCH --error=logs/insert_mode7_bootstrap_confidence_%j.err + +# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" +itrialspace_activate_conda + + +set -euo pipefail + +BASE_DIR="${ITRIALSPACE_DATA_DIR}" +MANIFEST_ROOT="${ITRIALSPACE_OUTPUT_DIR}/manifests" +OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks" +PROJECT_DIR="${PROJ_DIR}" + +TRIAL_MODE="mode7_bootstrap_confidence" +MANIFEST_PATH="${MANIFEST_PATH:-${MANIFEST_ROOT}/${TRIAL_MODE}/NLST_cohort_boot000.csv}" +OUT_DIR="${OUT_DIR:-${OUTPUT_ROOT}/${TRIAL_MODE}}" +CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}" +N_JOBS="${N_JOBS:-8}" +DRY_RUN="${DRY_RUN:-false}" +SEED="${SEED:-42}" + +echo "==================================================================" +echo " iTrialSpace Mask Insertion — Mode 7: Bootstrap Confidence" +echo " Job ID: ${SLURM_JOB_ID:-local} Node: $(hostname) Date: $(date)" +echo "==================================================================" +echo " MANIFEST_PATH : ${MANIFEST_PATH}" +echo " OUT_DIR : ${OUT_DIR}" +echo " N_JOBS : ${N_JOBS}" +echo "" + +cd "${PROJECT_DIR}" + +if [ ! -f "${MANIFEST_PATH}" ]; then + echo "FATAL: Manifest not found: ${MANIFEST_PATH}" + exit 1 +fi +mkdir -p "${OUT_DIR}" + +CFG_ARG="" +if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then + CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}" +elif [ -f "${CONFIG_PATH}" ]; then + CFG_ARG="--config ${CONFIG_PATH}" +fi + +EXTRA_ARGS="" +[ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run" + +echo "Running: python3 -m itrialspace.mask_inserter run ..." +echo " manifest: ${MANIFEST_PATH}" +echo " output: ${OUT_DIR}" + +python3 -m itrialspace.mask_inserter run \ + --manifest "${MANIFEST_PATH}" \ + --output-dir "${OUT_DIR}" \ + ${CFG_ARG} \ + --trial-name "${TRIAL_MODE}" \ + --seed ${SEED} \ + --n-jobs ${N_JOBS} \ + ${EXTRA_ARGS} +EXIT_CODE=$? +echo "Finished: $(date) Exit: ${EXIT_CODE}" +exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/mask_inserter/mode7_insert_masks_array.sub b/itrialspace/infra/slurm/mask_inserter/mode7_insert_masks_array.sub new file mode 100644 index 0000000000000000000000000000000000000000..93e564c1f4adac7e439f617f97710f0322f2ba52 --- /dev/null +++ b/itrialspace/infra/slurm/mask_inserter/mode7_insert_masks_array.sub @@ -0,0 +1,100 @@ +#!/bin/bash +# ────────────────────────────────────────────────────────────────────────────── +# Mode 7: Bootstrap Confidence — Array Job (one per bootstrap replicate) +# +# STRONGLY recommended for Mode 7 which typically produces 100+ replicates. +# +# Usage: +# python itrialspace_mask_inserter/tools/list_manifests.py \ +# --dir /scratch/.../manifests/mode7_bootstrap_confidence \ +# --output manifests_mode7.txt +# sbatch --array=0-99 mode7_insert_masks_array.sub # for 100 bootstraps +# ────────────────────────────────────────────────────────────────────────────── + +#SBATCH --job-name=ins_M7_arr +#SBATCH --partition=defq +#SBATCH --ntasks=1 +#SBATCH --gpus=0 +#SBATCH --cpus-per-task=8 +#SBATCH --mem=32G +#SBATCH --time=04:00:00 +#SBATCH --output=logs/insert_mode7_bootstrap_confidence_%A_%a.out +#SBATCH --error=logs/insert_mode7_bootstrap_confidence_%A_%a.err + +# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" +itrialspace_activate_conda + + +set -euo pipefail + +BASE_DIR="${ITRIALSPACE_DATA_DIR}" +OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks" +PROJECT_DIR="${PROJ_DIR}" + +TRIAL_MODE="mode7_bootstrap_confidence" +MANIFEST_LIST="${MANIFEST_LIST:-${PROJECT_DIR}/itrialspace_mask_inserter/slurm_trials/manifests_mode7.txt}" +CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}" +N_JOBS="${N_JOBS:-8}" +DRY_RUN="${DRY_RUN:-false}" +SEED="${SEED:-42}" + +if [ ! -f "${MANIFEST_LIST}" ]; then + echo "FATAL: Manifest list not found: ${MANIFEST_LIST}" + exit 1 +fi + +TASK_ID="${SLURM_ARRAY_TASK_ID:-0}" +MANIFEST_PATH=$(sed -n "$((TASK_ID + 1))p" "${MANIFEST_LIST}") + +if [ -z "${MANIFEST_PATH}" ]; then + echo "FATAL: No manifest at index ${TASK_ID} in ${MANIFEST_LIST}" + exit 1 +fi + +MANIFEST_BASENAME="$(basename "${MANIFEST_PATH}" .csv)" +MANIFEST_BASENAME="$(basename "${MANIFEST_BASENAME}" .json)" +OUT_DIR="${OUTPUT_ROOT}/${TRIAL_MODE}/${MANIFEST_BASENAME}" + +echo "==================================================================" +echo " iTrialSpace Mask Insertion — Mode 7: Bootstrap Confidence (Array)" +echo " Job ID: ${SLURM_JOB_ID:-local} Array Task: ${TASK_ID}" +echo " Node: $(hostname) Date: $(date)" +echo "==================================================================" +echo " MANIFEST_PATH : ${MANIFEST_PATH}" +echo " OUT_DIR : ${OUT_DIR}" +echo "" + +cd "${PROJECT_DIR}" + +if [ ! -f "${MANIFEST_PATH}" ]; then + echo "FATAL: Manifest not found: ${MANIFEST_PATH}" + exit 1 +fi +mkdir -p "${OUT_DIR}" + +CFG_ARG="" +if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then + CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}" +elif [ -f "${CONFIG_PATH}" ]; then + CFG_ARG="--config ${CONFIG_PATH}" +fi + +EXTRA_ARGS="" +[ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run" + +echo "Running: python3 -m itrialspace.mask_inserter run ..." +echo " manifest: ${MANIFEST_PATH}" +echo " output: ${OUT_DIR}" + +python3 -m itrialspace.mask_inserter run \ + --manifest "${MANIFEST_PATH}" \ + --output-dir "${OUT_DIR}" \ + ${CFG_ARG} \ + --trial-name "${TRIAL_MODE}_${MANIFEST_BASENAME}" \ + --seed ${SEED} \ + --n-jobs ${N_JOBS} \ + ${EXTRA_ARGS} +EXIT_CODE=$? +echo "Finished: $(date) Exit: ${EXIT_CODE}" +exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/mask_inserter/mode8_insert_masks.sub b/itrialspace/infra/slurm/mask_inserter/mode8_insert_masks.sub new file mode 100644 index 0000000000000000000000000000000000000000..06995572fa21c94194a31c5f650ccca90ff11413 --- /dev/null +++ b/itrialspace/infra/slurm/mask_inserter/mode8_insert_masks.sub @@ -0,0 +1,83 @@ +#!/bin/bash +# ────────────────────────────────────────────────────────────────────────────── +# Mode 8: Algorithm Comparison — Mask Insertion +# +# Inserts donor nodule masks for the standardised algorithm comparison cohort. +# Typically a single large manifest shared across multiple detection algorithms. +# +# Usage: +# sbatch mode8_insert_masks.sub +# ────────────────────────────────────────────────────────────────────────────── + +#SBATCH --job-name=ins_M8_Algo +#SBATCH --partition=defq +#SBATCH --ntasks=1 +#SBATCH --gpus=0 +#SBATCH --cpus-per-task=8 +#SBATCH --mem=32G +#SBATCH --time=06:00:00 +#SBATCH --output=logs/insert_mode8_algorithm_comparison_%j.out +#SBATCH --error=logs/insert_mode8_algorithm_comparison_%j.err + +# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" +itrialspace_activate_conda + + +set -euo pipefail + +BASE_DIR="${ITRIALSPACE_DATA_DIR}" +MANIFEST_ROOT="${ITRIALSPACE_OUTPUT_DIR}/manifests" +OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks" +PROJECT_DIR="${PROJ_DIR}" + +TRIAL_MODE="mode8_algorithm_comparison" +MANIFEST_PATH="${MANIFEST_PATH:-${MANIFEST_ROOT}/${TRIAL_MODE}/algo_comparison_NLST_500.csv}" +OUT_DIR="${OUT_DIR:-${OUTPUT_ROOT}/${TRIAL_MODE}}" +CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}" +N_JOBS="${N_JOBS:-16}" # More workers for the large standardised cohort +DRY_RUN="${DRY_RUN:-false}" +SEED="${SEED:-42}" + +echo "==================================================================" +echo " iTrialSpace Mask Insertion — Mode 8: Algorithm Comparison" +echo " Job ID: ${SLURM_JOB_ID:-local} Node: $(hostname) Date: $(date)" +echo "==================================================================" +echo " MANIFEST_PATH : ${MANIFEST_PATH}" +echo " OUT_DIR : ${OUT_DIR}" +echo " N_JOBS : ${N_JOBS}" +echo "" + +cd "${PROJECT_DIR}" + +if [ ! -f "${MANIFEST_PATH}" ]; then + echo "FATAL: Manifest not found: ${MANIFEST_PATH}" + exit 1 +fi +mkdir -p "${OUT_DIR}" + +CFG_ARG="" +if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then + CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}" +elif [ -f "${CONFIG_PATH}" ]; then + CFG_ARG="--config ${CONFIG_PATH}" +fi + +EXTRA_ARGS="" +[ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run" + +echo "Running: python3 -m itrialspace.mask_inserter run ..." +echo " manifest: ${MANIFEST_PATH}" +echo " output: ${OUT_DIR}" + +python3 -m itrialspace.mask_inserter run \ + --manifest "${MANIFEST_PATH}" \ + --output-dir "${OUT_DIR}" \ + ${CFG_ARG} \ + --trial-name "${TRIAL_MODE}" \ + --seed ${SEED} \ + --n-jobs ${N_JOBS} \ + ${EXTRA_ARGS} +EXIT_CODE=$? +echo "Finished: $(date) Exit: ${EXIT_CODE}" +exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/mask_inserter/mode8_insert_masks_array.sub b/itrialspace/infra/slurm/mask_inserter/mode8_insert_masks_array.sub new file mode 100644 index 0000000000000000000000000000000000000000..aa59beace1201d4ddc75dd46772182be7ef1f0dc --- /dev/null +++ b/itrialspace/infra/slurm/mask_inserter/mode8_insert_masks_array.sub @@ -0,0 +1,99 @@ +#!/bin/bash +# ────────────────────────────────────────────────────────────────────────────── +# Mode 8: Algorithm Comparison — Array Job (multiple manifests) +# +# Usage: +# python itrialspace_mask_inserter/tools/list_manifests.py \ +# --dir /scratch/.../manifests/mode8_algorithm_comparison \ +# --output manifests_mode8.txt +# sbatch --array=0-$(( $(wc -l < manifests_mode8.txt) - 1 )) \ +# mode8_insert_masks_array.sub +# ────────────────────────────────────────────────────────────────────────────── + +#SBATCH --job-name=ins_M8_arr +#SBATCH --partition=defq +#SBATCH --ntasks=1 +#SBATCH --gpus=0 +#SBATCH --cpus-per-task=16 +#SBATCH --mem=48G +#SBATCH --time=06:00:00 +#SBATCH --output=logs/insert_mode8_algorithm_comparison_%A_%a.out +#SBATCH --error=logs/insert_mode8_algorithm_comparison_%A_%a.err + +# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" +itrialspace_activate_conda + + +set -euo pipefail + +BASE_DIR="${ITRIALSPACE_DATA_DIR}" +OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks" +PROJECT_DIR="${PROJ_DIR}" + +TRIAL_MODE="mode8_algorithm_comparison" +MANIFEST_LIST="${MANIFEST_LIST:-${PROJECT_DIR}/itrialspace_mask_inserter/slurm_trials/manifests_mode8.txt}" +CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}" +N_JOBS="${N_JOBS:-16}" +DRY_RUN="${DRY_RUN:-false}" +SEED="${SEED:-42}" + +if [ ! -f "${MANIFEST_LIST}" ]; then + echo "FATAL: Manifest list not found: ${MANIFEST_LIST}" + exit 1 +fi + +TASK_ID="${SLURM_ARRAY_TASK_ID:-0}" +MANIFEST_PATH=$(sed -n "$((TASK_ID + 1))p" "${MANIFEST_LIST}") + +if [ -z "${MANIFEST_PATH}" ]; then + echo "FATAL: No manifest at index ${TASK_ID} in ${MANIFEST_LIST}" + exit 1 +fi + +MANIFEST_BASENAME="$(basename "${MANIFEST_PATH}" .csv)" +MANIFEST_BASENAME="$(basename "${MANIFEST_BASENAME}" .json)" +OUT_DIR="${OUTPUT_ROOT}/${TRIAL_MODE}/${MANIFEST_BASENAME}" + +echo "==================================================================" +echo " iTrialSpace Mask Insertion — Mode 8: Algorithm Comparison (Array)" +echo " Job ID: ${SLURM_JOB_ID:-local} Array Task: ${TASK_ID}" +echo " Node: $(hostname) Date: $(date)" +echo "==================================================================" +echo " MANIFEST_PATH : ${MANIFEST_PATH}" +echo " OUT_DIR : ${OUT_DIR}" +echo "" + +cd "${PROJECT_DIR}" + +if [ ! -f "${MANIFEST_PATH}" ]; then + echo "FATAL: Manifest not found: ${MANIFEST_PATH}" + exit 1 +fi +mkdir -p "${OUT_DIR}" + +CFG_ARG="" +if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then + CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}" +elif [ -f "${CONFIG_PATH}" ]; then + CFG_ARG="--config ${CONFIG_PATH}" +fi + +EXTRA_ARGS="" +[ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run" + +echo "Running: python3 -m itrialspace.mask_inserter run ..." +echo " manifest: ${MANIFEST_PATH}" +echo " output: ${OUT_DIR}" + +python3 -m itrialspace.mask_inserter run \ + --manifest "${MANIFEST_PATH}" \ + --output-dir "${OUT_DIR}" \ + ${CFG_ARG} \ + --trial-name "${TRIAL_MODE}_${MANIFEST_BASENAME}" \ + --seed ${SEED} \ + --n-jobs ${N_JOBS} \ + ${EXTRA_ARGS} +EXIT_CODE=$? +echo "Finished: $(date) Exit: ${EXIT_CODE}" +exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/mask_inserter/mode9_insert_masks.sub b/itrialspace/infra/slurm/mask_inserter/mode9_insert_masks.sub new file mode 100644 index 0000000000000000000000000000000000000000..b5b73b63a1c06d86b4febf80abe3ec8120fa0508 --- /dev/null +++ b/itrialspace/infra/slurm/mask_inserter/mode9_insert_masks.sub @@ -0,0 +1,84 @@ +#!/bin/bash +# ────────────────────────────────────────────────────────────────────────────── +# Mode 9: Screening Simulation — Mask Insertion +# +# Inserts donor nodule masks for multi-round screening protocol manifests. +# Mode 9 produces one manifest per screening round (e.g., 3 rounds). +# Consider the array variant for batch processing across rounds. +# +# Usage: +# MANIFEST_PATH=.../round_1.csv sbatch mode9_insert_masks.sub +# ────────────────────────────────────────────────────────────────────────────── + +#SBATCH --job-name=ins_M9_Screen +#SBATCH --partition=defq +#SBATCH --ntasks=1 +#SBATCH --gpus=0 +#SBATCH --cpus-per-task=8 +#SBATCH --mem=32G +#SBATCH --time=08:00:00 +#SBATCH --output=logs/insert_mode9_screening_simulation_%j.out +#SBATCH --error=logs/insert_mode9_screening_simulation_%j.err + +# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" +itrialspace_activate_conda + + +set -euo pipefail + +BASE_DIR="${ITRIALSPACE_DATA_DIR}" +MANIFEST_ROOT="${ITRIALSPACE_OUTPUT_DIR}/manifests" +OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks" +PROJECT_DIR="${PROJ_DIR}" + +TRIAL_MODE="mode9_screening_simulation" +MANIFEST_PATH="${MANIFEST_PATH:-${MANIFEST_ROOT}/${TRIAL_MODE}/screening_round_1_prev=0.040.csv}" +OUT_DIR="${OUT_DIR:-${OUTPUT_ROOT}/${TRIAL_MODE}}" +CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}" +N_JOBS="${N_JOBS:-8}" +DRY_RUN="${DRY_RUN:-false}" +SEED="${SEED:-42}" + +echo "==================================================================" +echo " iTrialSpace Mask Insertion — Mode 9: Screening Simulation" +echo " Job ID: ${SLURM_JOB_ID:-local} Node: $(hostname) Date: $(date)" +echo "==================================================================" +echo " MANIFEST_PATH : ${MANIFEST_PATH}" +echo " OUT_DIR : ${OUT_DIR}" +echo " N_JOBS : ${N_JOBS}" +echo "" + +cd "${PROJECT_DIR}" + +if [ ! -f "${MANIFEST_PATH}" ]; then + echo "FATAL: Manifest not found: ${MANIFEST_PATH}" + exit 1 +fi +mkdir -p "${OUT_DIR}" + +CFG_ARG="" +if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then + CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}" +elif [ -f "${CONFIG_PATH}" ]; then + CFG_ARG="--config ${CONFIG_PATH}" +fi + +EXTRA_ARGS="" +[ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run" + +echo "Running: python3 -m itrialspace.mask_inserter run ..." +echo " manifest: ${MANIFEST_PATH}" +echo " output: ${OUT_DIR}" + +python3 -m itrialspace.mask_inserter run \ + --manifest "${MANIFEST_PATH}" \ + --output-dir "${OUT_DIR}" \ + ${CFG_ARG} \ + --trial-name "${TRIAL_MODE}" \ + --seed ${SEED} \ + --n-jobs ${N_JOBS} \ + ${EXTRA_ARGS} +EXIT_CODE=$? +echo "Finished: $(date) Exit: ${EXIT_CODE}" +exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/mask_inserter/mode9_insert_masks_array.sub b/itrialspace/infra/slurm/mask_inserter/mode9_insert_masks_array.sub new file mode 100644 index 0000000000000000000000000000000000000000..5eb2702c57d4a7fff46e01403a1781fb672dad9b --- /dev/null +++ b/itrialspace/infra/slurm/mask_inserter/mode9_insert_masks_array.sub @@ -0,0 +1,101 @@ +#!/bin/bash +# ────────────────────────────────────────────────────────────────────────────── +# Mode 9: Screening Simulation — Array Job (one per screening round) +# +# Mode 9 produces one manifest per screening round (e.g., 3 rounds). +# +# Usage: +# python itrialspace_mask_inserter/tools/list_manifests.py \ +# --dir /scratch/.../manifests/mode9_screening_simulation \ +# --output manifests_mode9.txt +# sbatch --array=0-$(( $(wc -l < manifests_mode9.txt) - 1 )) \ +# mode9_insert_masks_array.sub +# ────────────────────────────────────────────────────────────────────────────── + +#SBATCH --job-name=ins_M9_arr +#SBATCH --partition=defq +#SBATCH --ntasks=1 +#SBATCH --gpus=0 +#SBATCH --cpus-per-task=8 +#SBATCH --mem=32G +#SBATCH --time=04:00:00 +#SBATCH --output=logs/insert_mode9_screening_simulation_%A_%a.out +#SBATCH --error=logs/insert_mode9_screening_simulation_%A_%a.err + +# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" +itrialspace_activate_conda + + +set -euo pipefail + +BASE_DIR="${ITRIALSPACE_DATA_DIR}" +OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks" +PROJECT_DIR="${PROJ_DIR}" + +TRIAL_MODE="mode9_screening_simulation" +MANIFEST_LIST="${MANIFEST_LIST:-${PROJECT_DIR}/itrialspace_mask_inserter/slurm_trials/manifests_mode9.txt}" +CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}" +N_JOBS="${N_JOBS:-8}" +DRY_RUN="${DRY_RUN:-false}" +SEED="${SEED:-42}" + +if [ ! -f "${MANIFEST_LIST}" ]; then + echo "FATAL: Manifest list not found: ${MANIFEST_LIST}" + exit 1 +fi + +TASK_ID="${SLURM_ARRAY_TASK_ID:-0}" +MANIFEST_PATH=$(sed -n "$((TASK_ID + 1))p" "${MANIFEST_LIST}") + +if [ -z "${MANIFEST_PATH}" ]; then + echo "FATAL: No manifest at index ${TASK_ID} in ${MANIFEST_LIST}" + exit 1 +fi + +MANIFEST_BASENAME="$(basename "${MANIFEST_PATH}" .csv)" +MANIFEST_BASENAME="$(basename "${MANIFEST_BASENAME}" .json)" +OUT_DIR="${OUTPUT_ROOT}/${TRIAL_MODE}/${MANIFEST_BASENAME}" + +echo "==================================================================" +echo " iTrialSpace Mask Insertion — Mode 9: Screening Simulation (Array)" +echo " Job ID: ${SLURM_JOB_ID:-local} Array Task: ${TASK_ID}" +echo " Node: $(hostname) Date: $(date)" +echo "==================================================================" +echo " MANIFEST_PATH : ${MANIFEST_PATH}" +echo " OUT_DIR : ${OUT_DIR}" +echo "" + +cd "${PROJECT_DIR}" + +if [ ! -f "${MANIFEST_PATH}" ]; then + echo "FATAL: Manifest not found: ${MANIFEST_PATH}" + exit 1 +fi +mkdir -p "${OUT_DIR}" + +CFG_ARG="" +if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then + CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}" +elif [ -f "${CONFIG_PATH}" ]; then + CFG_ARG="--config ${CONFIG_PATH}" +fi + +EXTRA_ARGS="" +[ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run" + +echo "Running: python3 -m itrialspace.mask_inserter run ..." +echo " manifest: ${MANIFEST_PATH}" +echo " output: ${OUT_DIR}" + +python3 -m itrialspace.mask_inserter run \ + --manifest "${MANIFEST_PATH}" \ + --output-dir "${OUT_DIR}" \ + ${CFG_ARG} \ + --trial-name "${TRIAL_MODE}_${MANIFEST_BASENAME}" \ + --seed ${SEED} \ + --n-jobs ${N_JOBS} \ + ${EXTRA_ARGS} +EXIT_CODE=$? +echo "Finished: $(date) Exit: ${EXIT_CODE}" +exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/mask_inserter/run_integration_full_volume.sub b/itrialspace/infra/slurm/mask_inserter/run_integration_full_volume.sub new file mode 100644 index 0000000000000000000000000000000000000000..1efe1e8b0d713e275fdba026787ac743ed46b330 --- /dev/null +++ b/itrialspace/infra/slurm/mask_inserter/run_integration_full_volume.sub @@ -0,0 +1,61 @@ +#!/bin/bash +#SBATCH --job-name=inserter_fullvol +#SBATCH --partition=common +#SBATCH --mem=32G +#SBATCH --cpus-per-task=4 +#SBATCH --time=02:00:00 +#SBATCH --output=full_volume_%j.out +#SBATCH --error=full_volume_%j.err + +# ────────────────────────────────────────────────────────────────────────── +# iTrialSpace Mask Inserter — Full-Volume Integration Tests on HPC +# +# Before submitting, generate a test manifest: +# python itrialspace_mask_inserter/tools/make_test_manifest.py \ +# --output ${ITRIALSPACE_DATA_DIR}/test_manifest.csv +# +# Then submit: +# export ITRIALSPACE_TEST_MANIFEST=${ITRIALSPACE_DATA_DIR}/test_manifest.csv +# export ITRIALSPACE_TEST_BASEDIR=${ITRIALSPACE_DATA_DIR} +# sbatch run_integration_full_volume.sub +# ────────────────────────────────────────────────────────────────────────── + +set -euo pipefail + +echo "=== iTrialSpace Mask Inserter: Full-Volume Integration Tests ===" +echo "Job ID: ${SLURM_JOB_ID:-local}" +echo "Node: $(hostname)" +echo "Date: $(date)" +echo "" + +# Activate environment +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh"; itrialspace_activate_conda + +# Navigate to project root +cd ${PROJ_DIR} + +# ── Test data paths (edit these or set env vars before sbatch) ─────────── +export ITRIALSPACE_TEST_MANIFEST="${ITRIALSPACE_TEST_MANIFEST:-${ITRIALSPACE_DATA_DIR}/test_manifest.csv}" +export ITRIALSPACE_TEST_BASEDIR="${ITRIALSPACE_TEST_BASEDIR:-${ITRIALSPACE_DATA_DIR}}" + +echo "Test manifest: ${ITRIALSPACE_TEST_MANIFEST}" +echo "Base dir: ${ITRIALSPACE_TEST_BASEDIR}" +echo "Python: $(which python)" +echo "" + +# Verify data exists before running tests +if [ ! -f "${ITRIALSPACE_TEST_MANIFEST}" ]; then + echo "ERROR: Test manifest not found at ${ITRIALSPACE_TEST_MANIFEST}" + echo "Generate it with: python itrialspace_mask_inserter/tools/make_test_manifest.py" + exit 1 +fi + +# Run full-volume integration tests +python -m pytest \ + itrialspace_mask_inserter/tests/test_full_volume.py \ + -v --tb=long -s \ + -m "full_volume" \ + 2>&1 + +echo "" +echo "=== Full-volume tests complete: $(date) ===" diff --git a/itrialspace/infra/slurm/mask_inserter/run_unit_tests.sub b/itrialspace/infra/slurm/mask_inserter/run_unit_tests.sub new file mode 100644 index 0000000000000000000000000000000000000000..f69869c622b206dc0af6a6805fb0ee28cb5f8b65 --- /dev/null +++ b/itrialspace/infra/slurm/mask_inserter/run_unit_tests.sub @@ -0,0 +1,44 @@ +#!/bin/bash +#SBATCH --job-name=inserter_unit_tests +#SBATCH --partition=common +#SBATCH --mem=16G +#SBATCH --cpus-per-task=4 +#SBATCH --time=01:00:00 +#SBATCH --output=unit_tests_%j.out +#SBATCH --error=unit_tests_%j.err + +# ────────────────────────────────────────────────────────────────────────── +# iTrialSpace Mask Inserter — Unit Tests on HPC +# +# Submit: sbatch run_unit_tests.sub +# ────────────────────────────────────────────────────────────────────────── + +set -euo pipefail + +echo "=== iTrialSpace Mask Inserter: Unit Tests ===" +echo "Job ID: ${SLURM_JOB_ID:-local}" +echo "Node: $(hostname)" +echo "Date: $(date)" +echo "" + +# Activate environment +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh"; itrialspace_activate_conda + +# Navigate to project root +cd ${PROJ_DIR} + +echo "Python: $(which python)" +echo "NumPy: $(python -c 'import numpy; print(numpy.__version__)')" +echo "" + +# Run unit tests (excludes full_volume marker) +python -m pytest \ + itrialspace_mask_inserter/tests/test_placement.py \ + itrialspace_mask_inserter/tests/test_resample.py \ + itrialspace_mask_inserter/tests/test_inserter.py \ + -v --tb=short \ + -m "not full_volume" \ + 2>&1 + +echo "" +echo "=== Unit tests complete: $(date) ===" diff --git a/itrialspace/infra/slurm/mask_inserter/submit_all_arrays.sh b/itrialspace/infra/slurm/mask_inserter/submit_all_arrays.sh new file mode 100644 index 0000000000000000000000000000000000000000..5c01523bec96c193f4fcf84cc8f1319570f579a6 --- /dev/null +++ b/itrialspace/infra/slurm/mask_inserter/submit_all_arrays.sh @@ -0,0 +1,203 @@ +#!/bin/bash + +# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" + +# ────────────────────────────────────────────────────────────────────────────── +# Submit mask insertion ARRAY jobs for all 13 iTrialSpace trial modes. +# +# For each mode this script: +# 1. Generates the manifest list file (manifests_modeN.txt) +# 2. Counts how many manifests exist +# 3. Submits sbatch --array=0-(N-1) modeN_insert_masks_array.sub +# +# Modes with exactly 1 manifest fall back to the single (non-array) .sub. +# Modes with 0 manifests are skipped. +# +# Usage: +# ./submit_all_arrays.sh # submit all 13 modes +# ./submit_all_arrays.sh 2 3 7 # submit only modes 2, 3, 7 +# ./submit_all_arrays.sh --dry-run # submit all with dry-run enabled +# ./submit_all_arrays.sh --list-only # generate manifest lists, don't submit +# ────────────────────────────────────────────────────────────────────────────── + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +PROJECT_DIR="$(cd "$SCRIPT_DIR/../.." && pwd)" +cd "$SCRIPT_DIR" + +# Ensure logs directory exists +mkdir -p logs + +BASE_DIR="${ITRIALSPACE_DATA_DIR}" +MANIFEST_ROOT="${ITRIALSPACE_OUTPUT_DIR}/manifests" +LIST_MANIFESTS="${PROJECT_DIR}/itrialspace_mask_inserter/tools/list_manifests.py" + +MODES=( + "mode1_insert_masks" # Controlled Prevalence + "mode2_insert_masks" # Size Detection Curve + "mode3_insert_masks" # Location Sensitivity + "mode4_insert_masks" # Demographic Stratification + "mode5_insert_masks" # Counterfactual + "mode6_insert_masks" # Cross-Dataset + "mode7_insert_masks" # Bootstrap Confidence + "mode8_insert_masks" # Algorithm Comparison + "mode9_insert_masks" # Screening Simulation + "mode10_insert_masks" # Multi-Nodule Realism + "mode11_insert_masks" # Digital Twin Isolation + "mode12_insert_masks" # Digital Twin Complete + "mode13_insert_masks" # Digital Twin Cross +) + +MODE_DIRS=( + "mode1_controlled_prevalence" + "mode2_size_detection_curve" + "mode3_location_sensitivity" + "mode4_demographic_stratification" + "mode5_counterfactual" + "mode6_cross_dataset" + "mode7_bootstrap_confidence" + "mode8_algorithm_comparison" + "mode9_screening_simulation" + "mode10_multi_nodule_realism" + "mode11_digital_twin_isolation" + "mode12_digital_twin_complete" + "mode13_digital_twin_cross" +) + +MODE_NAMES=( + "Controlled Prevalence" + "Size Detection Curve" + "Location Sensitivity" + "Demographic Stratification" + "Counterfactual" + "Cross-Dataset" + "Bootstrap Confidence" + "Algorithm Comparison" + "Screening Simulation" + "Multi-Nodule Realism" + "Digital Twin Isolation" + "Digital Twin Complete" + "Digital Twin Cross" +) + +# ── Parse flags ─────────────────────────────────────────────────────────────── +DRY_RUN_FLAG="" +LIST_ONLY=false +POSITIONAL=() +for arg in "$@"; do + case "$arg" in + --dry-run) DRY_RUN_FLAG="--export=DRY_RUN=true" ;; + --list-only) LIST_ONLY=true ;; + *) POSITIONAL+=("$arg") ;; + esac +done +set -- "${POSITIONAL[@]+"${POSITIONAL[@]}"}" + +echo "==================================================================" +echo " iTrialSpace Mask Insertion — Array Batch Submission" +echo " Date: $(date)" +if [ -n "$DRY_RUN_FLAG" ]; then + echo " *** DRY RUN MODE ***" +fi +if $LIST_ONLY; then + echo " *** LIST-ONLY MODE (no sbatch) ***" +fi +echo "==================================================================" +echo "" + +# ── Determine which modes to process ───────────────────────────────────────── +if [ $# -eq 0 ]; then + INDICES=($(seq 0 $((${#MODES[@]} - 1)))) +else + INDICES=() + for num in "$@"; do + idx=$((num - 1)) + if [ $idx -ge 0 ] && [ $idx -lt ${#MODES[@]} ]; then + INDICES+=($idx) + else + echo " Invalid mode number: $num (valid: 1-${#MODES[@]})" + fi + done +fi + +SUBMITTED=0 +SKIPPED=0 + +for idx in "${INDICES[@]}"; do + num=$((idx + 1)) + mode="${MODES[$idx]}" + dir="${MODE_DIRS[$idx]}" + name="${MODE_NAMES[$idx]}" + manifest_dir="${MANIFEST_ROOT}/${dir}" + list_file="${SCRIPT_DIR}/manifests_mode${num}.txt" + + echo -n " Mode ${num}: ${name} ... " + + # ── Check if manifest directory exists ──────────────────────────────── + if [ ! -d "${manifest_dir}" ]; then + echo "SKIPPED (no directory: ${dir}/)" + SKIPPED=$((SKIPPED + 1)) + continue + fi + + # ── Generate manifest list file ─────────────────────────────────────── + python3 "${LIST_MANIFESTS}" \ + --dir "${manifest_dir}" \ + --output "${list_file}" \ + --quiet 2>/dev/null || true + + if [ ! -f "${list_file}" ]; then + echo "SKIPPED (list_manifests.py failed)" + SKIPPED=$((SKIPPED + 1)) + continue + fi + + N=$(wc -l < "${list_file}" | tr -d ' ') + + if [ "$N" -eq 0 ]; then + echo "SKIPPED (0 manifests)" + rm -f "${list_file}" + SKIPPED=$((SKIPPED + 1)) + continue + fi + + if $LIST_ONLY; then + echo "${N} manifest(s) → ${list_file}" + continue + fi + + # ── Decide: single job vs array job ───────────────────────────────── + if [ "$N" -eq 1 ]; then + # Single manifest → prefer the non-array .sub (simpler logs) + sub_file="${mode}.sub" + if [ -f "$sub_file" ]; then + sbatch $DRY_RUN_FLAG "${sub_file}" + SUBMITTED=$((SUBMITTED + 1)) + else + echo "SKIPPED (${sub_file} not found)" + SKIPPED=$((SKIPPED + 1)) + fi + else + # Multiple manifests → array job + sub_file="${mode}_array.sub" + if [ -f "$sub_file" ]; then + ARRAY_RANGE="0-$((N - 1))" + sbatch $DRY_RUN_FLAG --array="${ARRAY_RANGE}" "${sub_file}" + SUBMITTED=$((SUBMITTED + 1)) + else + echo "SKIPPED (${sub_file} not found)" + SKIPPED=$((SKIPPED + 1)) + fi + fi +done + +echo "" +echo "──────────────────────────────────────────────────────────────────" +echo " Submitted: ${SUBMITTED} Skipped: ${SKIPPED}" +echo "" +echo " Check status: squeue -u $USER" +echo " Cancel all: scancel -u $USER --name='ins_M*'" +echo " Logs: ${SCRIPT_DIR}/logs/" +echo "──────────────────────────────────────────────────────────────────" diff --git a/itrialspace/infra/slurm/mask_inserter/submit_all_inserts.sh b/itrialspace/infra/slurm/mask_inserter/submit_all_inserts.sh new file mode 100644 index 0000000000000000000000000000000000000000..e1eaf485fa240302e72c53cafaf8be0f3629a41e --- /dev/null +++ b/itrialspace/infra/slurm/mask_inserter/submit_all_inserts.sh @@ -0,0 +1,115 @@ +#!/bin/bash +# ────────────────────────────────────────────────────────────────────────────── +# Submit mask insertion jobs for all 13 iTrialSpace trial modes. +# +# Usage: +# ./submit_all_inserts.sh # submit all 13 modes (single-manifest) +# ./submit_all_inserts.sh 1 3 8 # submit only modes 1, 3, 8 +# ./submit_all_inserts.sh --dry-run # submit all with dry-run enabled +# +# For array jobs (modes with multiple manifests), use the array sub files +# directly — see README.md for details. +# ────────────────────────────────────────────────────────────────────────────── + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd "$SCRIPT_DIR" + +# Ensure logs directory exists +mkdir -p logs + +MODES=( + "mode1_insert_masks" # Controlled Prevalence + "mode2_insert_masks" # Size Detection Curve + "mode3_insert_masks" # Location Sensitivity + "mode4_insert_masks" # Demographic Stratification + "mode5_insert_masks" # Counterfactual + "mode6_insert_masks" # Cross-Dataset + "mode7_insert_masks" # Bootstrap Confidence + "mode8_insert_masks" # Algorithm Comparison + "mode9_insert_masks" # Screening Simulation + "mode10_insert_masks" # Multi-Nodule Realism + "mode11_insert_masks" # Digital Twin Isolation + "mode12_insert_masks" # Digital Twin Complete + "mode13_insert_masks" # Digital Twin Cross +) + +MODE_NAMES=( + "Controlled Prevalence" + "Size Detection Curve" + "Location Sensitivity" + "Demographic Stratification" + "Counterfactual" + "Cross-Dataset" + "Bootstrap Confidence" + "Algorithm Comparison" + "Screening Simulation" + "Multi-Nodule Realism" + "Digital Twin Isolation" + "Digital Twin Complete" + "Digital Twin Cross" +) + +# Parse --dry-run flag +DRY_RUN_FLAG="" +POSITIONAL=() +for arg in "$@"; do + if [ "$arg" = "--dry-run" ]; then + DRY_RUN_FLAG="--export=DRY_RUN=true" + else + POSITIONAL+=("$arg") + fi +done +set -- "${POSITIONAL[@]}" + +echo "==================================================================" +echo " iTrialSpace Mask Insertion — Batch Submission" +echo " Date: $(date)" +if [ -n "$DRY_RUN_FLAG" ]; then + echo " *** DRY RUN MODE ***" +fi +echo "==================================================================" +echo "" + +if [ $# -eq 0 ]; then + # Submit all + echo "Submitting all ${#MODES[@]} trial modes..." + echo "" + for i in "${!MODES[@]}"; do + mode="${MODES[$i]}" + name="${MODE_NAMES[$i]}" + sub_file="${mode}.sub" + if [ -f "$sub_file" ]; then + echo -n " Mode $((i+1)): ${name} ... " + sbatch $DRY_RUN_FLAG "${sub_file}" + else + echo " Mode $((i+1)): ${name} — SKIPPED (${sub_file} not found)" + fi + done +else + # Submit selected modes + echo "Submitting selected trial modes..." + echo "" + for num in "$@"; do + idx=$((num - 1)) + if [ $idx -ge 0 ] && [ $idx -lt ${#MODES[@]} ]; then + mode="${MODES[$idx]}" + name="${MODE_NAMES[$idx]}" + sub_file="${mode}.sub" + if [ -f "$sub_file" ]; then + echo -n " Mode ${num}: ${name} ... " + sbatch $DRY_RUN_FLAG "${sub_file}" + else + echo " Mode ${num}: ${name} — SKIPPED (${sub_file} not found)" + fi + else + echo " Invalid mode number: $num (valid: 1-${#MODES[@]})" + fi + done +fi + +echo "" +echo "──────────────────────────────────────────────────────────────────" +echo "Check status: squeue -u $USER" +echo "Cancel all: scancel -u $USER --name='ins_M*'" +echo "Logs: ${SCRIPT_DIR}/logs/" +echo "──────────────────────────────────────────────────────────────────" diff --git a/itrialspace/infra/slurm/mask_inserter/template_insert_masks.sub b/itrialspace/infra/slurm/mask_inserter/template_insert_masks.sub new file mode 100644 index 0000000000000000000000000000000000000000..f50e1a353dff59ce8f4d0fe1d182b9cc02916688 --- /dev/null +++ b/itrialspace/infra/slurm/mask_inserter/template_insert_masks.sub @@ -0,0 +1,120 @@ +#!/bin/bash +# ────────────────────────────────────────────────────────────────────────────── +# iTrialSpace Mask Insertion Engine — Generic SLURM Template +# +# Reusable template that accepts all parameters via environment variables. +# Set the required variables before calling sbatch: +# +# export TRIAL_MODE=mode1_controlled_prevalence +# export MANIFEST_PATH=/scratch/.../manifest.csv +# export OUT_DIR=/scratch/.../inserted_masks/mode1_controlled_prevalence +# sbatch template_insert_masks.sub +# +# Optional overrides (with defaults shown): +# export CONFIG_PATH=config/defaults.yaml +# export N_JOBS=8 +# export VERIFY_PATHS=true +# export DRY_RUN=false +# export SLURM_MEM=32G +# export SLURM_TIME=04:00:00 +# export SLURM_CPUS=8 +# ────────────────────────────────────────────────────────────────────────────── + +#SBATCH --job-name=iTS_insert +#SBATCH --partition=defq +#SBATCH --ntasks=1 +#SBATCH --gpus=0 +#SBATCH --cpus-per-task=8 +#SBATCH --mem=32G +#SBATCH --time=04:00:00 +#SBATCH --output=logs/insert_%j.out +#SBATCH --error=logs/insert_%j.err + +set -euo pipefail + +# ── Defaults ────────────────────────────────────────────────────────────────── +TRIAL_MODE="${TRIAL_MODE:-unnamed}" +MANIFEST_PATH="${MANIFEST_PATH:?ERROR: MANIFEST_PATH must be set}" +OUT_DIR="${OUT_DIR:?ERROR: OUT_DIR must be set}" +CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}" +N_JOBS="${N_JOBS:-8}" +VERIFY_PATHS="${VERIFY_PATHS:-true}" +DRY_RUN="${DRY_RUN:-false}" +TRIAL_NAME="${TRIAL_NAME:-${TRIAL_MODE}}" +SEED="${SEED:-42}" + +# ── Banner ──────────────────────────────────────────────────────────────────── +echo "==================================================================" +echo " iTrialSpace Mask Insertion Engine" +echo " Mode: ${TRIAL_MODE}" +echo " Job ID: ${SLURM_JOB_ID:-local}" +echo " Node: $(hostname)" +echo " Date: $(date)" +echo "==================================================================" +echo "" +echo " MANIFEST_PATH : ${MANIFEST_PATH}" +echo " OUT_DIR : ${OUT_DIR}" +echo " CONFIG_PATH : ${CONFIG_PATH}" +echo " N_JOBS : ${N_JOBS}" +echo " VERIFY_PATHS : ${VERIFY_PATHS}" +echo " DRY_RUN : ${DRY_RUN}" +echo " TRIAL_NAME : ${TRIAL_NAME}" +echo " SEED : ${SEED}" +echo "" + +# ── Environment ────────────────────────────────────────────────────────────── +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" +itrialspace_activate_conda + +cd ${PROJ_DIR} +echo "Python: $(which python3)" +echo "Working dir: $(pwd)" +echo "" + +# ── Validate inputs ───────────────────────────────────────────────────────── +if [ ! -f "${MANIFEST_PATH}" ]; then + echo "FATAL: Manifest not found at ${MANIFEST_PATH}" + exit 1 +fi + +if [ ! -f "${CONFIG_PATH}" ] && [ ! -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then + echo "WARNING: Config not found at ${CONFIG_PATH}, falling back to built-in defaults" + CONFIG_ARG="" +else + # Resolve relative path under the inserter package if needed + if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then + CONFIG_PATH="src/itrialspace/mask_inserter/${CONFIG_PATH}" + fi + CONFIG_ARG="--config ${CONFIG_PATH}" +fi + +# Create output directory +mkdir -p "${OUT_DIR}" + +# ── Build command ──────────────────────────────────────────────────────────── +CMD="python3 -m itrialspace.mask_inserter run" +CMD+=" --manifest ${MANIFEST_PATH}" +CMD+=" --output-dir ${OUT_DIR}" +CMD+=" ${CONFIG_ARG}" +CMD+=" --trial-name ${TRIAL_NAME}" +CMD+=" --seed ${SEED}" +CMD+=" --n-jobs ${N_JOBS}" + +if [ "${DRY_RUN}" = "true" ]; then + CMD+=" --dry-run" +fi + +echo "Command: ${CMD}" +echo "" + +# ── Execute ────────────────────────────────────────────────────────────────── +eval ${CMD} +EXIT_CODE=$? + +echo "" +echo "==================================================================" +echo " Finished: $(date)" +echo " Exit code: ${EXIT_CODE}" +echo "==================================================================" + +exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/nodulemap/nodulemap.sub b/itrialspace/infra/slurm/nodulemap/nodulemap.sub new file mode 100644 index 0000000000000000000000000000000000000000..2f2237591f4efdeefc0a2e33d34f702a4b1ca546 --- /dev/null +++ b/itrialspace/infra/slurm/nodulemap/nodulemap.sub @@ -0,0 +1,102 @@ +#!/bin/bash +#SBATCH --job-name=NoduleMap +#SBATCH --mail-type=END,FAIL +#SBATCH -p defq +#SBATCH --ntasks=1 +#SBATCH --cpus-per-task=8 +#SBATCH --mem=32G +#SBATCH --time=7-00:00:00 +#SBATCH --output=logs/nodulemap-%j.out +#SBATCH --error=logs/nodulemap-%j.err + +# =========================================================================== +# iTrialSpace NoduleMap — Server (serve only) +# +# Serves the FastAPI + sigma.js web app on port 8422 from pre-built +# artifacts. It does NOT build anything — build once with +# `sbatch rebuild_nodulemap.sub` (or `its-nodulemap build/edges`) first. +# +# Submit: sbatch nodulemap.sub +# Check: squeue -u $USER · tail -f logs/nodulemap-.out +# Stop: scancel +# +# Auto-publish: by default the job reverse-tunnels its port back to the host you ran +# `sbatch` from (the login node), so you always connect at login-node:8422 no matter which +# compute node it lands on. With VS Code on the login node, just open http://localhost:8422. +# (Disable with ITS_AUTOTUNNEL=0; needs passwordless SSH compute→login. Manual fallback: +# ssh -L 8422::8422 @) +# =========================================================================== + +echo "======================================" +echo " iTrialSpace NoduleMap (serve)" +echo " Node: $(hostname)" +echo " Date: $(date)" +echo " Job ID: ${SLURM_JOB_ID:-local}" +echo "======================================" + +# ── Environment ────────────────────────────────────────────────────────── +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" +itrialspace_activate_conda + +APP_DIR="${PROJ_DIR}" +ARTIFACT_DIR="${NODULEMAP_ARTIFACTS:-${ITRIALSPACE_OUTPUT_DIR:-$APP_DIR}/nodulemap_artifacts}" +PORT="${NODULEMAP_PORT:-8422}" + +cd "$APP_DIR" +mkdir -p logs + +# ── Guard: artifacts must already exist ───────────────────────────────── +if ! ls "$ARTIFACT_DIR"/embeddings_*.npy >/dev/null 2>&1; then + echo "ERROR: no embeddings found in $ARTIFACT_DIR" + echo "Build them first: sbatch infra/slurm/nodulemap/rebuild_nodulemap.sub" + echo "(or: its-nodulemap build --all-2d --outdir \"$ARTIFACT_DIR\" && its-nodulemap edges ...)" + exit 1 +fi + +# ── Artifact summary ──────────────────────────────────────────────────── +echo "" +echo "[$(date +%T)] ═══ Artifact summary ═══" +python -m itrialspace.apps.nodulemap info --artifact-dir "$ARTIFACT_DIR" + +# ── Auto-publish to the login node (reverse tunnel) ────────────────────── +# Reverse-tunnel the port BACK to the host you ran `sbatch` from ($SLURM_SUBMIT_HOST = +# the login node), so you always connect at login-node:$PORT regardless of which compute +# node this is — no manual `ssh -L`. With VS Code on the login node, just open +# http://localhost:$PORT. Disable with ITS_AUTOTUNNEL=0; needs passwordless SSH compute→login. +TUNNEL_PID="" +if [ "${ITS_AUTOTUNNEL:-1}" = "1" ] && [ -n "${SLURM_SUBMIT_HOST:-}" ]; then + echo "[$(date +%T)] Reverse-tunneling $PORT to ${SLURM_SUBMIT_HOST} …" + ssh -NR ${PORT}:localhost:${PORT} \ + -o BatchMode=yes -o ExitOnForwardFailure=yes \ + -o StrictHostKeyChecking=accept-new -o ServerAliveInterval=60 \ + "${SLURM_SUBMIT_HOST}" & + TUNNEL_PID=$! + sleep 3 + if kill -0 "$TUNNEL_PID" 2>/dev/null; then + echo "[$(date +%T)] Auto-tunnel UP — open http://localhost:$PORT on ${SLURM_SUBMIT_HOST}" + else + echo "[$(date +%T)] Auto-tunnel could not bind / no passwordless SSH back — tunnel manually." + TUNNEL_PID="" + fi +fi +trap '[ -n "$TUNNEL_PID" ] && kill "$TUNNEL_PID" 2>/dev/null' EXIT + +# ── Start server (blocks until the job is cancelled) ──────────────────── +echo "" +echo "[$(date +%T)] ═══ Starting NoduleMap server ═══" +export NODULEMAP_ARTIFACTS="$ARTIFACT_DIR" + +echo "======================================" +echo " NoduleMap running on $(hostname):$PORT" +echo "" +if [ -n "$TUNNEL_PID" ]; then + echo " Auto-published — open: http://localhost:$PORT (on ${SLURM_SUBMIT_HOST} / VS Code)" +else + echo " SSH tunnel (from your laptop):" + echo " ssh -L $PORT:$(hostname):$PORT \$USER@ → http://localhost:$PORT" +fi +echo "======================================" + +python -m itrialspace.apps.nodulemap serve --artifact-dir "$ARTIFACT_DIR" --port "$PORT" + +echo "[$(date +%T)] Done." diff --git a/itrialspace/infra/slurm/nodulemap/rebuild_nodulemap.sub b/itrialspace/infra/slurm/nodulemap/rebuild_nodulemap.sub new file mode 100644 index 0000000000000000000000000000000000000000..f27dcf1e693e33a400619981d34801cfc9011995 --- /dev/null +++ b/itrialspace/infra/slurm/nodulemap/rebuild_nodulemap.sub @@ -0,0 +1,93 @@ +#!/bin/bash +#SBATCH --job-name=NMap-Rebuild +#SBATCH --mail-type=END,FAIL +#SBATCH -p defq +#SBATCH --ntasks=1 +#SBATCH --cpus-per-task=8 +#SBATCH --mem=48G +#SBATCH --time=4:00:00 +#SBATCH --output=logs/rebuild_nodulemap-%j.out +#SBATCH --error=logs/rebuild_nodulemap-%j.err + +# =========================================================================== +# NoduleMap Artifact Rebuild — Purge NLST3D +# +# Deletes ALL existing NoduleMap artifacts and rebuilds from scratch. +# After the rebuild, NLST3D rows will be absent (it was removed from +# datasets.yaml). +# +# Runs: +# 1) Clean artifacts directory +# 2) Rebuild 6 embedding models (PCA_2D, PCA_32, UMAP_2D, UMAP_16, +# UMAP_32, TSNE_2D) +# 3) Compute edge lists for all models (k=3,5,10,25) +# 4) Verify NLST3D is absent from every rebuilt artifact +# 5) Run pytest regression tests +# +# Submit: sbatch rebuild_nodulemap.sub +# Check: tail -f logs/rebuild_nodulemap-.out +# =========================================================================== + +set -euo pipefail + +echo "======================================================" +echo " NoduleMap Artifact Rebuild (Purge NLST3D)" +echo " Node: $(hostname)" +echo " Date: $(date)" +echo " Job ID: ${SLURM_JOB_ID:-local}" +echo "======================================================" + +# ── Environment ────────────────────────────────────────────────────────── +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" +itrialspace_activate_conda +echo "[$(date +%T)] Python: $(which python3)" +echo "[$(date +%T)] conda env: $CONDA_DEFAULT_ENV" + +APP_DIR="${PROJ_DIR}" +ARTIFACT_DIR="${NODULEMAP_ARTIFACTS:-${ITRIALSPACE_OUTPUT_DIR:-$APP_DIR}/nodulemap_artifacts}" +cd "$APP_DIR" +mkdir -p logs "$ARTIFACT_DIR" + +# ── Step 1: Verify NLST3D is absent from the resolved dataset registry ── +echo "" +echo "[$(date +%T)] ═══ Pre-flight: Checking the dataset registry ═══" +python3 -c " +from itrialspace.io.registry import DatasetRegistry +reg = DatasetRegistry.from_yaml() +assert reg.get('NLST3D') is None, 'NLST3D is active in the dataset registry — remove it before rebuilding.' +print('OK — NLST3D is not in the resolved registry') +" + +# ── Step 2: Clean + Rebuild all artifacts ─────────────────────────────── +echo "" +echo "[$(date +%T)] ═══ Rebuilding all artifacts (clean) ═══" +python3 -m itrialspace.apps.nodulemap.tools.rebuild_artifacts --clean --outdir "$ARTIFACT_DIR" +echo "" +echo "[$(date +%T)] ═══ Artifact rebuild complete ═══" + +# ── Step 3: Post-rebuild verification ─────────────────────────────────── +echo "" +echo "[$(date +%T)] ═══ Running NLST3D purge verification ═══" +python3 -m itrialspace.apps.nodulemap.tools.verify_purge --artifact-dir "$ARTIFACT_DIR" +VERIFY_RC=$? + +if [ $VERIFY_RC -ne 0 ]; then + echo "" + echo "FATAL: Verification FAILED — NLST3D still present in artifacts!" + exit 1 +fi + +# ── Step 4: Run regression tests ──────────────────────────────────────── +echo "" +echo "[$(date +%T)] ═══ Running pytest regression tests ═══" +python3 -m pytest tests/nodulemap/test_models.py -v --tb=short 2>&1 || true +echo "" +echo "[$(date +%T)] ═══ Running pytest purge tests ═══" +python3 -m pytest tests/nodulemap/test_nlst3d_purge.py -v --tb=short 2>&1 + +echo "" +echo "======================================================" +echo " Rebuild complete." +echo " Artifacts: $ARTIFACT_DIR" +echo " $(date)" +echo "======================================================" diff --git a/itrialspace/infra/slurm/retriever/app.sub b/itrialspace/infra/slurm/retriever/app.sub new file mode 100644 index 0000000000000000000000000000000000000000..e683e8f3c1a2db479702b2f4a70dcc3ddaf33a2b --- /dev/null +++ b/itrialspace/infra/slurm/retriever/app.sub @@ -0,0 +1,128 @@ +#!/bin/bash +#SBATCH --job-name=iTrialSpace_Retriever +#SBATCH --mail-type=END,FAIL +#SBATCH -p defq +#SBATCH --ntasks=1 +#SBATCH --cpus-per-task=8 +#SBATCH --mem=32G +#SBATCH --time=7-00:00:00 +#SBATCH --output=logs/retriever-app-%j.out +#SBATCH --error=logs/retriever-app-%j.err + +# =========================================================================== +# iTrialSpace Retriever — FastAPI (8421) + Streamlit UI (8501) in one job +# +# Submit: sbatch infra/slurm/retriever/app.sub +# Check: squeue -u $USER +# Logs: tail -f logs/retriever-app-.out (prints node, ports, tunnel line) +# Stop: scancel +# Ports are env-overridable: RETRIEVER_API_PORT / RETRIEVER_UI_PORT. +# +# Auto-publish: by default the job reverse-tunnels its ports back to the host you ran +# `sbatch` from (the login node), so you ALWAYS connect at login-node:8501 — no matter +# which compute node it lands on, and no manual `ssh -L`. With VS Code on the login node, +# just open http://localhost:8501. (Disable with ITS_AUTOTUNNEL=0; needs passwordless +# SSH compute→login. Fallback manual tunnel is printed in the log.) +# =========================================================================== + +echo "======================================" +echo " iTrialSpace Retriever — starting" +echo " Node: $(hostname)" +echo " Date: $(date)" +echo " Job ID: ${SLURM_JOB_ID:-local}" +echo "======================================" + +# ── Environment ────────────────────────────────────────────────────────── +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" +itrialspace_activate_conda + +APP_DIR="${PROJ_DIR}" +cd "$APP_DIR" + +API_PORT="${RETRIEVER_API_PORT:-8421}" +UI_PORT="${RETRIEVER_UI_PORT:-8501}" + +# Create logs dir if missing +mkdir -p logs + +# ── Launch FastAPI backend ─────────────────────────────────────────────── +echo "[$(date +%T)] Starting FastAPI on port $API_PORT …" +uvicorn itrialspace.apps.retriever.api.app:create_app \ + --factory \ + --host 0.0.0.0 \ + --port $API_PORT \ + --workers 1 \ + & +API_PID=$! +echo "[$(date +%T)] FastAPI PID = $API_PID" + +# Wait for API to be ready (up to 120s for 14k nodule load) +echo "[$(date +%T)] Waiting for API to be ready …" +for i in $(seq 1 120); do + if curl -sf http://localhost:$API_PORT/health > /dev/null 2>&1; then + echo "[$(date +%T)] API ready after ${i}s" + break + fi + sleep 1 +done + +# ── Launch Streamlit frontend ──────────────────────────────────────────── +echo "[$(date +%T)] Starting Streamlit on port $UI_PORT …" +streamlit run src/itrialspace/apps/retriever/ui/app.py \ + --server.port $UI_PORT \ + --server.headless true \ + --server.address 0.0.0.0 \ + -- --api-url http://localhost:$API_PORT \ + & +UI_PID=$! +echo "[$(date +%T)] Streamlit PID = $UI_PID" + +# ── Auto-publish to the login node (reverse tunnel) ────────────────────── +# The job runs on a compute node that changes every launch. To avoid re-doing an +# `ssh -L` each time, we reverse-tunnel the ports BACK to the host you ran `sbatch` +# from ($SLURM_SUBMIT_HOST = the login node). Then you always connect at the SAME +# place — login-node:$UI_PORT — regardless of which compute node this is. +# Since VS Code runs on the login node, http://localhost:$UI_PORT then "just works". +# Requires passwordless SSH compute→login (typical on HPC). Disable with ITS_AUTOTUNNEL=0. +TUNNEL_PID="" +if [ "${ITS_AUTOTUNNEL:-1}" = "1" ] && [ -n "${SLURM_SUBMIT_HOST:-}" ]; then + echo "[$(date +%T)] Reverse-tunneling $UI_PORT/$API_PORT to ${SLURM_SUBMIT_HOST} …" + ssh -NR ${UI_PORT}:localhost:${UI_PORT} -R ${API_PORT}:localhost:${API_PORT} \ + -o BatchMode=yes -o ExitOnForwardFailure=yes \ + -o StrictHostKeyChecking=accept-new -o ServerAliveInterval=60 \ + "${SLURM_SUBMIT_HOST}" & + TUNNEL_PID=$! + sleep 3 + if kill -0 "$TUNNEL_PID" 2>/dev/null; then + echo "[$(date +%T)] Auto-tunnel UP — open http://localhost:$UI_PORT on ${SLURM_SUBMIT_HOST}" + else + echo "[$(date +%T)] Auto-tunnel could not bind (port busy on ${SLURM_SUBMIT_HOST}, or" + echo " no passwordless SSH back). Use the manual tunnel below instead." + TUNNEL_PID="" + fi +fi + +echo "======================================" +echo " Services running on $(hostname)" +echo " FastAPI : http://$(hostname):$API_PORT" +echo " Streamlit: http://$(hostname):$UI_PORT" +echo "" +if [ -n "$TUNNEL_PID" ]; then + echo " Auto-published to ${SLURM_SUBMIT_HOST} — just open:" + echo " http://localhost:$UI_PORT (from ${SLURM_SUBMIT_HOST} / VS Code)" +else + echo " Manual SSH tunnel (from your laptop) — UI only needs $UI_PORT:" + echo " ssh -L $UI_PORT:$(hostname):$UI_PORT \$USER@" + echo " Then open: http://localhost:$UI_PORT" +fi +echo "======================================" + +# ── Wait for either process to exit ───────────────────────────────────── +wait -n $API_PID $UI_PID +EXIT_CODE=$? +echo "[$(date +%T)] One process exited (code=$EXIT_CODE). Cleaning up …" + +# Kill servers + tunnel on exit +kill $API_PID $UI_PID $TUNNEL_PID 2>/dev/null +wait +echo "[$(date +%T)] Done." diff --git a/itrialspace/infra/slurm/retriever/cli.sub b/itrialspace/infra/slurm/retriever/cli.sub new file mode 100644 index 0000000000000000000000000000000000000000..0e85a7f8ac25c5eb0fe15b3755c6df3cbcf5ae5a --- /dev/null +++ b/itrialspace/infra/slurm/retriever/cli.sub @@ -0,0 +1,120 @@ +#!/bin/bash +#SBATCH --job-name=iTrialSpace_CLI +#SBATCH --mail-type=END,FAIL +#SBATCH -p defq +#SBATCH --ntasks=1 +#SBATCH --cpus-per-task=4 +#SBATCH --mem=16G +#SBATCH --time=1:00:00 +#SBATCH --output=logs/retriever-cli-%j.out +#SBATCH --error=logs/retriever-cli-%j.err + +# =========================================================================== +# iTrialSpace Retriever — Mode 3: CLI batch job +# +# Submit: sbatch retriever_cli.sub +# Check: squeue -u $USER +# Output: logs/retriever-cli-.out +# exports/ (CSV / JSON files) +# +# Edit the CLI_COMMANDS section below to run your queries. +# =========================================================================== + +echo "======================================" +echo " iTrialSpace Retriever — CLI Mode" +echo " Node: $(hostname)" +echo " Date: $(date)" +echo " Job ID: $SLURM_JOB_ID" +echo "======================================" + +# ── Environment ────────────────────────────────────────────────────────── +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" +itrialspace_activate_conda + +APP_DIR="${PROJ_DIR}" +cd "$APP_DIR" + +# Create output dirs +mkdir -p logs exports + +# ══════════════════════════════════════════════════════════════════════════ +# CLI COMMANDS — edit these to customise your batch queries +# ══════════════════════════════════════════════════════════════════════════ + +echo "" +echo "==================================================================" +echo " 1. Index summary" +echo "==================================================================" +python -m itrialspace.apps.retriever.cli info + +echo "" +echo "==================================================================" +echo " 2. Search: all malignant nodules in RUL" +echo "==================================================================" +python -m itrialspace.apps.retriever.cli search \ + --label 1 \ + --lobe right_lung_upper_lobe \ + --limit 50 + +echo "" +echo "==================================================================" +echo " 3. Similarity: top-10 similar to DLCS_0001_01" +echo "==================================================================" +python -m itrialspace.apps.retriever.cli similar \ + --id DLCS_0001_01 \ + --k 10 + +echo "" +echo "==================================================================" +echo " 4. Reinsertion match: LUL, 12mm diameter, 50% CC" +echo "==================================================================" +python -m itrialspace.apps.retriever.cli match \ + --lobe left_lung_upper_lobe \ + --diameter 12 \ + --cc-pct 50 \ + --k 10 + +echo "" +echo "==================================================================" +echo " 5. Nodule detail (JSON)" +echo "==================================================================" +python -m itrialspace.apps.retriever.cli detail \ + --id DLCS_0001_01 \ + --json + +echo "" +echo "==================================================================" +echo " 6. Export: all malignant nodules → CSV" +echo "==================================================================" +python -m itrialspace.apps.retriever.cli export \ + --label 1 \ + --include-paths \ + --format csv \ + -o exports/malignant_nodules.csv + +echo "" +echo "==================================================================" +echo " 7. Export: all LUNA16 + LUNA25 benign → JSON" +echo "==================================================================" +python -m itrialspace.apps.retriever.cli export \ + --label 0 \ + --datasets LUNA16 LUNA25 \ + --format json \ + -o exports/luna_benign.json + +echo "" +echo "==================================================================" +echo " 8. Export: large nodules (>15mm) across all datasets → CSV" +echo "==================================================================" +python -m itrialspace.apps.retriever.cli export \ + --diam-min 15 \ + --format csv \ + -o exports/large_nodules_gt15mm.csv + +echo "" +echo "======================================" +echo " All commands completed" +echo " Exports saved to: $APP_DIR/exports/" +echo " Date: $(date)" +echo "======================================" +ls -lh exports/ diff --git a/itrialspace/infra/slurm/retriever/jupyter.sub b/itrialspace/infra/slurm/retriever/jupyter.sub new file mode 100644 index 0000000000000000000000000000000000000000..4190210637f1fa66d1923fb4809544692056cfbd --- /dev/null +++ b/itrialspace/infra/slurm/retriever/jupyter.sub @@ -0,0 +1,117 @@ +#!/bin/bash +#SBATCH --job-name=iTrialSpace_Jupyter +#SBATCH --mail-type=END,FAIL +#SBATCH -p defq +#SBATCH --ntasks=1 +#SBATCH --cpus-per-task=8 +#SBATCH --mem=32G +#SBATCH --time=7-00:00:00 +#SBATCH --output=logs/retriever-jupyter-%j.out +#SBATCH --error=logs/retriever-jupyter-%j.err + +# =========================================================================== +# iTrialSpace Retriever — Mode 2: Jupyter Notebook +# +# Submit: sbatch retriever_jupyter.sub +# Check: squeue -u $USER +# Logs: tail -f logs/retriever-jupyter-.out +# +# Once running, connect from your local machine: +# ssh -L 8888::8888 @ +# Then open the URL printed in the log (with token). +# +# Two ways to use inside the notebook: +# A) Direct mode — loads the full index in-process: +# from itrialspace.apps.retriever.notebook import RetrieverClient +# client = RetrieverClient() +# +# B) API mode — connects to the FastAPI backend (also launched here): +# from itrialspace.apps.retriever.notebook import RetrieverClient +# client = RetrieverClient(api_url="http://localhost:8421") +# =========================================================================== + +echo "======================================" +echo " iTrialSpace Retriever — Jupyter Mode" +echo " Node: $(hostname)" +echo " Date: $(date)" +echo " Job ID: $SLURM_JOB_ID" +echo "======================================" + +# ── Environment ────────────────────────────────────────────────────────── +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" +itrialspace_activate_conda + +APP_DIR="${PROJ_DIR}" +cd "$APP_DIR" + +# Ensure jupyter is available +if ! command -v jupyter &> /dev/null; then + echo "[$(date +%T)] Installing jupyterlab …" + pip install --quiet jupyterlab ipywidgets +fi + +# Create logs dir +mkdir -p logs + +API_PORT="${RETRIEVER_API_PORT:-8421}" +JUPYTER_PORT="${RETRIEVER_JUPYTER_PORT:-8888}" + +# ── Launch FastAPI backend (so notebook can use API mode too) ──────────── +echo "[$(date +%T)] Starting FastAPI on port $API_PORT …" +uvicorn itrialspace.apps.retriever.api.app:create_app \ + --factory \ + --host 0.0.0.0 \ + --port $API_PORT \ + --workers 1 \ + & +API_PID=$! +echo "[$(date +%T)] FastAPI PID = $API_PID" + +# Wait for API ready +echo "[$(date +%T)] Waiting for API …" +for i in $(seq 1 120); do + if curl -sf http://localhost:$API_PORT/health > /dev/null 2>&1; then + echo "[$(date +%T)] API ready after ${i}s" + break + fi + sleep 1 +done + +# ── Launch Jupyter ─────────────────────────────────────────────────────── +echo "[$(date +%T)] Starting JupyterLab on port $JUPYTER_PORT …" +jupyter lab \ + --ip=0.0.0.0 \ + --port=$JUPYTER_PORT \ + --no-browser \ + --NotebookApp.allow_origin='*' \ + --notebook-dir="$APP_DIR" \ + & +JUPYTER_PID=$! +echo "[$(date +%T)] Jupyter PID = $JUPYTER_PID" + +sleep 3 + +echo "======================================" +echo " Services running on $(hostname)" +echo " FastAPI : http://$(hostname):$API_PORT" +echo " JupyterLab: http://$(hostname):$JUPYTER_PORT" +echo "" +echo " SSH tunnel command:" +echo " ssh -L $JUPYTER_PORT:$(hostname):$JUPYTER_PORT -L $API_PORT:$(hostname):$API_PORT \$USER@" +echo "" +echo " Jupyter URL (check log for token):" +echo " http://localhost:$JUPYTER_PORT" +echo "======================================" + +# Print Jupyter token URL +sleep 5 +jupyter lab list 2>/dev/null + +# ── Wait for either process to exit ───────────────────────────────────── +wait -n $API_PID $JUPYTER_PID +EXIT_CODE=$? +echo "[$(date +%T)] One process exited (code=$EXIT_CODE). Cleaning up …" + +kill $API_PID $JUPYTER_PID 2>/dev/null +wait +echo "[$(date +%T)] Done." diff --git a/itrialspace/infra/slurm/run_pipeline.sh b/itrialspace/infra/slurm/run_pipeline.sh new file mode 100644 index 0000000000000000000000000000000000000000..adf3cac3651a75186ee4fb8b4849658a47b1f9c0 --- /dev/null +++ b/itrialspace/infra/slurm/run_pipeline.sh @@ -0,0 +1,99 @@ +#!/usr/bin/env bash +# ============================================================================ +# run_pipeline.sh — drive the iTrialSpace pipeline end-to-end for one trial mode +# trials (manifest) -> insertion (label-23 masks + audit) -> synthesis (CT) +# +# Stages are chained with SLURM dependencies that wait for the *array* jobs to +# finish (not just their submitters), so synthesis only runs after every mask + +# audit exists. Manifests are discovered recursively (modes 11-13 nest them under +# a dataset subdirectory). Run from the repo root. +# +# Usage: +# infra/slurm/run_pipeline.sh [stage] +# 1..13 +# [stage] all (default) | trials | insert | synth +# (_insert_chain / _synth_chain are internal dependency steps) +# +# Examples: +# infra/slurm/run_pipeline.sh 1 +# for m in $(seq 1 13); do infra/slurm/run_pipeline.sh $m; done +# +# Run size comes from the mode .sub files (edit those / see docs §5). +# Paths/conda-env come from your .env via infra/slurm/env.sh. +# ============================================================================ +set -euo pipefail + +MODE="${1:?usage: run_pipeline.sh [all|trials|insert|synth]}" +STAGE="${2:-all}" + +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +source "${HERE}/env.sh" +cd "${PROJ_DIR}" + +TRIALS_SUB=$(ls "${HERE}"/trials/mode${MODE}_*.sub 2>/dev/null | head -1) +INSERT_SUB="${HERE}/mask_inserter/mode${MODE}_insert_masks_array.sub" +SYNTH_SUB="${HERE}/synthesis/mode1_nodmaisi_array.sub" # generic; driven by env overrides +SELF="${HERE}/run_pipeline.sh" +G="${ITRIALSPACE_OUTPUT_DIR}" +ML="${G}/manifest_lists/mode${MODE}.txt" +mkdir -p "${G}/manifest_lists" "${G}/nodmaisi_case_lists" logs + +# Recursively find a mode's manifest CSVs (handles the modes 11-13 dataset subdirs). +list_manifests() { find "${G}/manifests/mode${MODE}_"*/ -name '*.csv' 2>/dev/null | sort; } + +case "${STAGE}" in + + trials|all) + [ -f "${TRIALS_SUB}" ] || { echo "No trials .sub for mode ${MODE}"; exit 1; } + TJOB=$(sbatch --parsable "${TRIALS_SUB}") + echo "[mode ${MODE}] trials -> job ${TJOB}" + [ "${STAGE}" = "trials" ] && exit 0 + # After trials finish, build the manifest list and submit insertion (+ chain synth). + sbatch --parsable --dependency=afterok:${TJOB} \ + --job-name=drv_ins_M${MODE} --partition="${SLURM_PARTITION_CPU}" --time=00:15:00 \ + --output=logs/drv_ins_M${MODE}_%j.out --error=logs/drv_ins_M${MODE}_%j.err \ + --wrap="bash '${SELF}' ${MODE} _insert_chain" + echo "[mode ${MODE}] insertion+synthesis chained after trials" + ;; + + insert) + # trials already done — submit insertion array now (no synth chain) + list_manifests > "${ML}"; N=$(wc -l < "${ML}") + [ "${N}" -gt 0 ] || { echo "No manifests for mode ${MODE} (run trials first)"; exit 1; } + sbatch --array=0-$((N-1)) --export=ALL,MANIFEST_LIST="${ML}" "${INSERT_SUB}" + echo "[mode ${MODE}] insertion -> ${N} manifest task(s)" + ;; + + _insert_chain) + # runs as a dependency job AFTER trials: submit the insert array, then chain + # the synth driver on that ARRAY (so it waits for all masks/audits). + list_manifests > "${ML}"; N=$(wc -l < "${ML}") + [ "${N}" -gt 0 ] || { echo "No manifests for mode ${MODE}"; exit 1; } + IARR=$(sbatch --parsable --array=0-$((N-1)) --export=ALL,MANIFEST_LIST="${ML}" "${INSERT_SUB}") + echo "[mode ${MODE}] insertion array -> ${IARR} (${N} task(s))" + sbatch --parsable --dependency=afterok:${IARR} \ + --job-name=drv_syn_M${MODE} --partition="${SLURM_PARTITION_CPU}" --time=00:15:00 \ + --output=logs/drv_syn_M${MODE}_%j.out --error=logs/drv_syn_M${MODE}_%j.err \ + --wrap="bash '${SELF}' ${MODE} synth" + ;; + + synth) + # one synthesis array per audit.json (one task per case). Audits exist now. + nsub=0 + while IFS= read -r audit; do + [ -z "${audit}" ] && continue + sub=$(basename "$(dirname "${audit}")") + cl="${G}/nodmaisi_case_lists/mode${MODE}_${sub}.txt" + n=$(python "${HERE}/_gen_caselist.py" "${audit}" "${cl}") + [ "${n}" -gt 0 ] || continue + sbatch --array=0-$((n-1)) \ + --export=ALL,AUDIT_PATH="${audit}",CASE_LIST="${cl}",OUT_DIR="${G}/generated_cts/mode${MODE}/${sub}" \ + "${SYNTH_SUB}" + nsub=$((nsub+1)) + done < <(find "${G}/inserted_masks/mode${MODE}_"*/ -name audit.json 2>/dev/null | sort) + echo "[mode ${MODE}] synthesis -> ${nsub} array job(s)" + [ "${nsub}" -gt 0 ] || { echo "[mode ${MODE}] no audits found — insertion incomplete?"; exit 1; } + ;; + + *) echo "unknown stage: ${STAGE}"; exit 1 ;; +esac diff --git a/itrialspace/infra/slurm/synthesis/audit_mode.py b/itrialspace/infra/slurm/synthesis/audit_mode.py new file mode 100644 index 0000000000000000000000000000000000000000..3356c54a1e0b0fef8bccf217182c6df3012cdfe2 --- /dev/null +++ b/itrialspace/infra/slurm/synthesis/audit_mode.py @@ -0,0 +1,308 @@ +#!/usr/bin/env python3 +"""Post-run audit for a NodMAISI mode output directory. + +Scans all case directories, checks completeness (synthetic_ct, audit, QC), +aggregates per-case results, and writes a mode-level pipeline_summary.json. + +Usage: + python3 audit_mode.py [--mask-dir ] + +Example: + python3 audit_mode.py /scratch/.../generated_cts/mode1_controlled_prevalence \ + --mask-dir /scratch/.../inserted_masks/mode1_controlled_prevalence +""" + +import argparse +import glob +import json +import os +import sys +from datetime import datetime + + +def discover_case_dirs(out_dir): + """Find all case directories (flat and sub-bin layouts).""" + case_dirs = {} + for entry in sorted(os.listdir(out_dir)): + fp = os.path.join(out_dir, entry) + if not os.path.isdir(fp): + continue + if entry.startswith("iTS--"): + case_dirs[entry] = fp + else: + # Sub-bin directory (e.g. size_curve_<5mm/) + for sub in sorted(os.listdir(fp)): + sfp = os.path.join(fp, sub) + if os.path.isdir(sfp) and sub.startswith("iTS--"): + case_dirs[sub] = sfp + return case_dirs + + +def discover_expected_cases(mask_dir): + """Discover all expected case IDs from the mask directory.""" + case_ids = set() + if not mask_dir or not os.path.isdir(mask_dir): + return case_ids + + # Pass 1: audit.json files + audited_dirs = set() + for af in sorted(glob.glob(os.path.join(mask_dir, "**", "audit.json"), recursive=True)): + audited_dirs.add(os.path.dirname(af)) + try: + audit = json.load(open(af)) + except Exception: + continue + for r in audit.get("records", []): + if r.get("status") != "success": + continue + cp = r.get("output_combined_path", "") + if not cp or not os.path.isfile(cp): + continue + name = os.path.basename(cp) + for sfx in ("_mask.nii.gz", ".nii.gz"): + if name.endswith(sfx): + name = name[: -len(sfx)] + break + case_ids.add(name) + + # Pass 2: file-scan for dirs without audit.json + for root, dirs, files in os.walk(mask_dir): + if root in audited_dirs: + continue + for f in files: + if not f.endswith(".nii.gz"): + continue + name = f + for sfx in ("_mask.nii.gz", ".nii.gz"): + if name.endswith(sfx): + name = name[: -len(sfx)] + break + case_ids.add(name) + + return case_ids + + +def audit_case(case_id, case_dir): + """Audit a single case directory for completeness.""" + result = { + "case_id": case_id, + "status": "unknown", + "has_synthetic_ct": False, + "has_nodmaisi_audit": False, + "has_qc_slices": False, + "qc_slice_count": 0, + "has_failure_json": False, + "has_dataset_json": False, + "has_input_mask": False, + "synthetic_ct_path": "", + "reason": "", + "total_sec": 0.0, + } + + if not os.path.isdir(case_dir): + result["status"] = "missing" + result["reason"] = "No output directory" + return result + + ct_path = os.path.join(case_dir, "synthetic_ct.nii.gz") + result["has_synthetic_ct"] = os.path.isfile(ct_path) + if result["has_synthetic_ct"]: + result["synthetic_ct_path"] = ct_path + + result["has_nodmaisi_audit"] = os.path.isfile( + os.path.join(case_dir, "nodmaisi_audit.json") + ) + result["has_dataset_json"] = os.path.isfile( + os.path.join(case_dir, "dataset.json") + ) + result["has_input_mask"] = os.path.isfile( + os.path.join(case_dir, "input_mask.nii.gz") + ) + + qc_slices = glob.glob(os.path.join(case_dir, "qc", "qc_slice_*.png")) + result["has_qc_slices"] = len(qc_slices) > 0 + result["qc_slice_count"] = len(qc_slices) + + fail_path = os.path.join(case_dir, "nodmaisi_failure.json") + result["has_failure_json"] = os.path.isfile(fail_path) + + # Read failure reason + if result["has_failure_json"]: + try: + fdata = json.load(open(fail_path)) + result["reason"] = fdata.get("error", fdata.get("reason", "")) + except Exception: + result["reason"] = "unreadable failure json" + + # Read audit for timing / extra info + audit_path = os.path.join(case_dir, "nodmaisi_audit.json") + if os.path.isfile(audit_path): + try: + adata = json.load(open(audit_path)) + result["total_sec"] = adata.get("elapsed_sec", 0.0) + if not result["reason"] and adata.get("status") == "failed": + result["reason"] = adata.get("reason", "") + except Exception: + pass + + # Read per-case pipeline_summary for timing if audit didn't have it + ps_path = os.path.join(case_dir, "pipeline_summary.json") + if os.path.isfile(ps_path) and result["total_sec"] == 0.0: + try: + ps = json.load(open(ps_path)) + cases = ps.get("cases", []) + if cases: + result["total_sec"] = cases[0].get("total_sec", 0.0) + if not result["reason"]: + result["reason"] = cases[0].get("reason", "") + except Exception: + pass + + # Determine overall status + if result["has_synthetic_ct"] and result["has_nodmaisi_audit"] and result["has_qc_slices"]: + result["status"] = "success" + elif result["has_failure_json"]: + result["status"] = "failed" + elif result["has_synthetic_ct"] and not result["has_qc_slices"]: + result["status"] = "incomplete" + if not result["reason"]: + result["reason"] = "synthetic_ct exists but QC slices missing" + elif result["has_nodmaisi_audit"] and not result["has_synthetic_ct"]: + result["status"] = "failed" + if not result["reason"]: + result["reason"] = "audit exists but no synthetic_ct produced" + else: + result["status"] = "incomplete" + if not result["reason"]: + missing = [] + if not result["has_synthetic_ct"]: + missing.append("synthetic_ct") + if not result["has_nodmaisi_audit"]: + missing.append("nodmaisi_audit") + if not result["has_qc_slices"]: + missing.append("qc_slices") + result["reason"] = f"Missing: {', '.join(missing)}" + + return result + + +def main(): + parser = argparse.ArgumentParser(description="Audit NodMAISI mode output") + parser.add_argument("out_dir", help="Mode output directory (generated_cts/modeN_*)") + parser.add_argument("--mask-dir", default="", help="Mask directory for expected case count") + parser.add_argument("--output", default="", help="Output path for pipeline_summary.json (default: /pipeline_summary.json)") + args = parser.parse_args() + + out_dir = args.out_dir + if not os.path.isdir(out_dir): + print(f"ERROR: Output directory not found: {out_dir}", file=sys.stderr) + return 1 + + mode_name = os.path.basename(out_dir) + print(f"Auditing: {mode_name}") + print(f" Output dir: {out_dir}") + + # Discover case dirs + case_dirs = discover_case_dirs(out_dir) + print(f" Case directories found: {len(case_dirs)}") + + # Discover expected cases from masks + expected = discover_expected_cases(args.mask_dir) + if expected: + print(f" Expected cases (from masks): {len(expected)}") + + # Identify cases that have no output dir at all + missing_cases = sorted(expected - set(case_dirs.keys())) if expected else [] + + # Audit each case dir + results = [] + for cid, cdir in sorted(case_dirs.items()): + results.append(audit_case(cid, cdir)) + + # Add missing cases (no output dir) + for cid in missing_cases: + results.append({ + "case_id": cid, + "status": "missing", + "has_synthetic_ct": False, + "has_nodmaisi_audit": False, + "has_qc_slices": False, + "qc_slice_count": 0, + "has_failure_json": False, + "has_dataset_json": False, + "has_input_mask": False, + "synthetic_ct_path": "", + "reason": "No output directory", + "total_sec": 0.0, + }) + + # Tally + n_success = sum(1 for r in results if r["status"] == "success") + n_failed = sum(1 for r in results if r["status"] == "failed") + n_incomplete = sum(1 for r in results if r["status"] == "incomplete") + n_missing = sum(1 for r in results if r["status"] == "missing") + total = len(results) + total_sec = sum(r["total_sec"] for r in results) + + # Failure reason breakdown + failure_reasons = {} + for r in results: + if r["status"] in ("failed", "incomplete", "missing"): + reason = r["reason"] or "unknown" + failure_reasons.setdefault(reason, []).append(r["case_id"]) + + # Print summary + print(f"\n{'='*60}") + print(f" AUDIT SUMMARY: {mode_name}") + print(f"{'='*60}") + print(f" Total cases: {total}") + if expected: + print(f" Expected: {len(expected)}") + print(f" Success: {n_success} ({100*n_success/total:.1f}%)" if total else "") + print(f" Failed: {n_failed}") + print(f" Incomplete: {n_incomplete}") + print(f" Missing: {n_missing}") + print(f" Total GPU time: {total_sec/3600:.1f} hours") + + if failure_reasons: + print(f"\n Failure/issue breakdown:") + for reason, cases in sorted(failure_reasons.items(), key=lambda x: -len(x[1])): + print(f" [{len(cases):4d}] {reason[:100]}") + + # Build pipeline_summary.json + summary = { + "pipeline": "itrialspace_to_nodmaisi", + "mode": mode_name, + "timestamp": datetime.now().isoformat(), + "audit_type": "post_run_aggregate", + "total_cases": total, + "expected_cases": len(expected) if expected else None, + "n_success": n_success, + "n_failed": n_failed, + "n_incomplete": n_incomplete, + "n_missing": n_missing, + "success_rate": round(n_success / total, 4) if total else 0, + "total_gpu_hours": round(total_sec / 3600, 2), + "failure_breakdown": { + reason: { + "count": len(cases), + "examples": cases[:5], + } + for reason, cases in sorted( + failure_reasons.items(), key=lambda x: -len(x[1]) + ) + }, + "cases": results, + } + + output_path = args.output or os.path.join(out_dir, "pipeline_summary.json") + with open(output_path, "w") as f: + json.dump(summary, f, indent=2, default=str) + print(f"\n Written: {output_path}") + print(f"{'='*60}") + + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/itrialspace/infra/slurm/synthesis/audit_mode.sub b/itrialspace/infra/slurm/synthesis/audit_mode.sub new file mode 100644 index 0000000000000000000000000000000000000000..4ec4dacd8440937b01e9a4e9fa1befd9a743dc76 --- /dev/null +++ b/itrialspace/infra/slurm/synthesis/audit_mode.sub @@ -0,0 +1,34 @@ +#!/bin/bash +#SBATCH --partition=defq +#SBATCH --ntasks=1 +#SBATCH --cpus-per-task=1 +#SBATCH --mem=4G +#SBATCH --time=00:30:00 +#SBATCH --output=${PROJ_DIR}/src/itrialspace/synthesis/slurm_nodmaisi/logs/audit_%x_%j.out +#SBATCH --error=${PROJ_DIR}/src/itrialspace/synthesis/slurm_nodmaisi/logs/audit_%x_%j.err + +# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" +itrialspace_activate_conda + + +# Post-run audit job — runs after all NodMAISI array tasks finish. +# Scans the mode output directory and writes pipeline_summary.json. +# +# Required exports: TRIAL_MODE, OUT_DIR, MASK_DIR + +set -euo pipefail + +SCRIPT_DIR="${PROJ_DIR}/src/itrialspace/synthesis/slurm_nodmaisi" + +echo "========================================" +echo " Post-run Audit: ${TRIAL_MODE}" +echo " Output dir: ${OUT_DIR}" +echo " Mask dir: ${MASK_DIR}" +echo " Time: $(date)" +echo "========================================" + +python3 "${SCRIPT_DIR}/audit_mode.py" "${OUT_DIR}" --mask-dir "${MASK_DIR}" + +echo "" +echo "Audit complete at $(date)" diff --git a/itrialspace/infra/slurm/synthesis/mode1_nodmaisi_array.sub b/itrialspace/infra/slurm/synthesis/mode1_nodmaisi_array.sub new file mode 100644 index 0000000000000000000000000000000000000000..7b4d24f46c62e8d7397c070b52b4ddbd8a64cc5e --- /dev/null +++ b/itrialspace/infra/slurm/synthesis/mode1_nodmaisi_array.sub @@ -0,0 +1,94 @@ +#!/bin/bash +# ============================================================================ +# Mode 1: Controlled Prevalence — NodMAISI CT synthesis (array job) +# +# Processes each case as a separate SLURM array task for maximum parallelism. +# Reads case IDs from the audit.json and distributes one case per task. +# +# Usage: +# # First, generate the case list: +# python -c " +# import json +# audit = json.load(open('$AUDIT_PATH')) +# cases = sorted({__import__('os').path.basename(r['output_combined_path']).replace('_mask.nii.gz','') for r in audit['records'] if r['status']=='success'}) +# open('/tmp/mode1_cases.txt','w').write('\n'.join(cases)) +# print(f'{len(cases)} cases') +# " +# # Then submit: +# sbatch --array=0-$(( $(wc -l < /tmp/mode1_cases.txt) - 1 )) mode1_nodmaisi_array.sub +# ============================================================================ + +#SBATCH --job-name=NM_M1_arr +#SBATCH --partition=vram48 +#SBATCH --ntasks=1 +#SBATCH --gpus=1 +#SBATCH --cpus-per-task=16 +#SBATCH --mem=64G +#SBATCH --time=02:00:00 +#SBATCH --output=logs/NM_M1_arr_%A_%a.out +#SBATCH --error=logs/NM_M1_arr_%A_%a.err + +# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" +itrialspace_activate_conda + + +set -euo pipefail + +NOMAISI_DIR="${PROJ_DIR}/src/itrialspace/synthesis" +ITRIALSPACE_BASE="${ITRIALSPACE_OUTPUT_DIR}" +TRIAL_MODE="mode1_controlled_prevalence" + +AUDIT_PATH="${AUDIT_PATH:-${ITRIALSPACE_BASE}/inserted_masks/${TRIAL_MODE}/audit.json}" +OUT_DIR="${OUT_DIR:-${ITRIALSPACE_BASE}/generated_cts/${TRIAL_MODE}}" +CASE_LIST="${CASE_LIST:-${ITRIALSPACE_OUTPUT_DIR}/nodmaisi_case_lists/${TRIAL_MODE}_cases.txt}" +CONFIG_PATH="${CONFIG_PATH:-${NOMAISI_DIR}/tools/integration_config.yaml}" + +# Auto-generate the case list from the audit if missing. Case IDs MUST be the +# mask-filename stems (what the runner matches against --case-ids), NOT the audit's +# integer case_id field. +if [ ! -s "${CASE_LIST}" ]; then + mkdir -p "$(dirname "${CASE_LIST}")" + python3 - "${AUDIT_PATH}" "${CASE_LIST}" <<'PYGEN' +import json, os, sys +def stem(p): + b = os.path.basename(p) + for s in ("_mask.nii.gz", ".nii.gz"): + if b.endswith(s): + return b[: -len(s)] + return b +audit = json.load(open(sys.argv[1])) +recs = audit.get("records", audit.get("cases", [])) +cases = sorted({stem(r["output_combined_path"]) for r in recs + if r.get("status") == "success" and r.get("output_combined_path")}) +open(sys.argv[2], "w").write("\n".join(cases) + "\n") +print(f"Generated {len(cases)} case IDs -> {sys.argv[2]}") +PYGEN +fi + +# Read case ID for this array task +CASE_ID=$(sed -n "$((SLURM_ARRAY_TASK_ID + 1))p" "${CASE_LIST}") +if [ -z "${CASE_ID}" ]; then + echo "FATAL: No case ID at array index ${SLURM_ARRAY_TASK_ID}" + exit 1 +fi + +echo "==================================================================" +echo " NodMAISI CT Synthesis — ${TRIAL_MODE} — Case ${CASE_ID}" +echo " Array Job: ${SLURM_ARRAY_JOB_ID} Task: ${SLURM_ARRAY_TASK_ID}" +echo " Node: $(hostname) Date: $(date)" +echo "==================================================================" + +export MONAI_DATA_DIRECTORY="${NOMAISI_DIR}/" +export PYTHONPATH="${NOMAISI_DIR}:${PYTHONPATH:-}" + +python "${NOMAISI_DIR}/tools/run_itrialspace_to_ct.py" \ + --audit "${AUDIT_PATH}" \ + --config "${CONFIG_PATH}" \ + --outdir "${OUT_DIR}" \ + --case-ids "${CASE_ID}" \ + -v + +EXIT_CODE=$? +echo "Finished case ${CASE_ID}: $(date) Exit: ${EXIT_CODE}" +exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/synthesis/nodmaisi_array.sub b/itrialspace/infra/slurm/synthesis/nodmaisi_array.sub new file mode 100644 index 0000000000000000000000000000000000000000..ed4b2e961eff05e3501d5e3fe5f0ee0bfd5e198a --- /dev/null +++ b/itrialspace/infra/slurm/synthesis/nodmaisi_array.sub @@ -0,0 +1,114 @@ +#!/bin/bash +# ============================================================================ +# iTrialSpace -> NodMAISI CT Synthesis — SLURM Array Job (any mode) +# +# Processes each case as a separate SLURM array task (one case per GPU). +# Works with both audit.json and --mask-root discovery. +# +# Required env vars: +# TRIAL_MODE - e.g., mode1_controlled_prevalence +# CASE_LIST - path to a text file with one case ID per line +# +# Optional env vars (with defaults): +# AUDIT_PATH - path to iTrialSpace audit.json (preferred) +# MASK_ROOT - directory of inserted mask NIfTIs (fallback) +# OUT_DIR - output directory for generated CTs +# CONFIG_PATH - integration config YAML +# +# Usage: +# # Step 1: Generate case list +# python3 scripts/gen_case_list.py --mode mode1_controlled_prevalence +# # Step 2: Submit array job +# N=$(wc -l < /tmp/mode1_controlled_prevalence_cases.txt) +# sbatch --array=0-$((N-1))%10 \ +# --export=ALL,TRIAL_MODE=mode1_controlled_prevalence \ +# nodmaisi_array.sub +# ============================================================================ + +#SBATCH --job-name=NM_arr +#SBATCH --partition=vram48 +#SBATCH --ntasks=1 +#SBATCH --gpus=1 +#SBATCH --cpus-per-task=16 +#SBATCH --mem=64G +#SBATCH --time=02:00:00 +#SBATCH --output=logs/NM_%x_%A_%a.out +#SBATCH --error=logs/NM_%x_%A_%a.err + +# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" +itrialspace_activate_conda + + +set -euo pipefail + +# ── Configurable paths ─────────────────────────────────────────────────────── +NOMAISI_DIR="${PROJ_DIR}/src/itrialspace/synthesis" +ITRIALSPACE_BASE="${ITRIALSPACE_OUTPUT_DIR}" + +TRIAL_MODE="${TRIAL_MODE:?ERROR: TRIAL_MODE must be set}" +CASE_LIST="${CASE_LIST:-${ITRIALSPACE_BASE}/nodmaisi_case_lists/${TRIAL_MODE}_cases.txt}" + +AUDIT_PATH="${AUDIT_PATH:-${ITRIALSPACE_BASE}/inserted_masks/${TRIAL_MODE}/audit.json}" +MASK_ROOT="${MASK_ROOT:-${ITRIALSPACE_BASE}/inserted_masks/${TRIAL_MODE}}" +OUT_DIR="${OUT_DIR:-${ITRIALSPACE_BASE}/generated_cts/${TRIAL_MODE}}" +CONFIG_PATH="${CONFIG_PATH:-${NOMAISI_DIR}/tools/integration_config.yaml}" + +# ── Read case ID for this array task ───────────────────────────────────────── +if [ ! -f "${CASE_LIST}" ]; then + echo "FATAL: Case list not found: ${CASE_LIST}" + echo "Generate it first with: python3 scripts/gen_case_list.py --mode ${TRIAL_MODE}" + exit 1 +fi + +# CASE_OFFSET allows chunked array jobs (default 0 for backward compat) +CASE_OFFSET=${CASE_OFFSET:-0} +LINE_NUM=$(( SLURM_ARRAY_TASK_ID + CASE_OFFSET + 1 )) + +CASE_ID=$(sed -n "${LINE_NUM}p" "${CASE_LIST}") +if [ -z "${CASE_ID}" ]; then + echo "FATAL: No case ID at line ${LINE_NUM} (array_idx=${SLURM_ARRAY_TASK_ID}, offset=${CASE_OFFSET}) in ${CASE_LIST}" + exit 1 +fi + +# ── Banner ─────────────────────────────────────────────────────────────────── +echo "==================================================================" +echo " NodMAISI CT Synthesis — ${TRIAL_MODE} — Case ${CASE_ID}" +echo " Array Job: ${SLURM_ARRAY_JOB_ID} Task: ${SLURM_ARRAY_TASK_ID}" +echo " Node: $(hostname) Date: $(date)" +echo "==================================================================" +echo " CASE_LIST : ${CASE_LIST}" +echo " AUDIT_PATH : ${AUDIT_PATH}" +echo " MASK_ROOT : ${MASK_ROOT}" +echo " OUT_DIR : ${OUT_DIR}" +echo "" + +# ── Environment ────────────────────────────────────────────────────────────── +export MONAI_DATA_DIRECTORY="${NOMAISI_DIR}/" +export PYTHONPATH="${NOMAISI_DIR}:${PYTHONPATH:-}" +export LD_LIBRARY_PATH="$(python -c 'import os,nvidia.cudnn;print(os.path.dirname(nvidia.cudnn.__file__)+"/lib")' 2>/dev/null):${LD_LIBRARY_PATH:-}" + +mkdir -p "${OUT_DIR}" + +# ── Build command — prefer audit.json, fallback to mask-root ───────────────── +CMD=( + python "${NOMAISI_DIR}/tools/run_itrialspace_to_ct.py" + --config "${CONFIG_PATH}" + --outdir "${OUT_DIR}" + --case-ids "${CASE_ID}" + -v +) + +if [ -f "${AUDIT_PATH}" ]; then + CMD+=(--audit "${AUDIT_PATH}") +else + CMD+=(--mask-root "${MASK_ROOT}") +fi + +echo "Command: ${CMD[*]}" +"${CMD[@]}" +EXIT_CODE=$? + +echo "" +echo "Finished case ${CASE_ID}: $(date) Exit: ${EXIT_CODE}" +exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/synthesis/nodmaisi_combined_rerun.sub b/itrialspace/infra/slurm/synthesis/nodmaisi_combined_rerun.sub new file mode 100644 index 0000000000000000000000000000000000000000..458d14065fbd6031a256c8e9d42809ac41551e9d --- /dev/null +++ b/itrialspace/infra/slurm/synthesis/nodmaisi_combined_rerun.sub @@ -0,0 +1,107 @@ +#!/bin/bash +# ============================================================================ +# Combined multi-mode NodMAISI CT rerun — single SLURM array job +# +# Reads from a combined case list where each line is: +# MODE_NAMECASE_ID +# +# This allows a single array job with a single throttle to control +# total GPU usage across all modes. +# +# Usage: +# N=$(wc -l < /path/to/all_modes_rerun_combined.txt) +# sbatch --array=0-$((N-1))%4 nodmaisi_combined_rerun.sub +# ============================================================================ + +#SBATCH --job-name=NM_rerun +#SBATCH --partition=vram48 +#SBATCH --ntasks=1 +#SBATCH --gpus=1 +#SBATCH --cpus-per-task=8 +#SBATCH --mem=48G +#SBATCH --time=02:00:00 +#SBATCH --output=logs/NM_%x_%A_%a.out +#SBATCH --error=logs/NM_%x_%A_%a.err + +# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" +itrialspace_activate_conda + + +set -euo pipefail + +# ── Configurable paths ─────────────────────────────────────────────────────── +NOMAISI_DIR="${PROJ_DIR}/src/itrialspace/synthesis" +ITRIALSPACE_BASE="${ITRIALSPACE_OUTPUT_DIR}" + +COMBINED_LIST="${COMBINED_LIST:-${ITRIALSPACE_BASE}/nodmaisi_case_lists/all_modes_rerun_combined.txt}" + +# ── Read mode + case ID for this array task ────────────────────────────────── +if [ ! -f "${COMBINED_LIST}" ]; then + echo "FATAL: Combined case list not found: ${COMBINED_LIST}" + exit 1 +fi + +LINE_NUM=$(( SLURM_ARRAY_TASK_ID + 1 )) +LINE=$(sed -n "${LINE_NUM}p" "${COMBINED_LIST}") + +if [ -z "${LINE}" ]; then + echo "FATAL: No entry at line ${LINE_NUM} (task_id=${SLURM_ARRAY_TASK_ID}) in ${COMBINED_LIST}" + exit 1 +fi + +TRIAL_MODE=$(echo "${LINE}" | cut -f1) +CASE_ID=$(echo "${LINE}" | cut -f2) + +if [ -z "${TRIAL_MODE}" ] || [ -z "${CASE_ID}" ]; then + echo "FATAL: Could not parse mode/case from line ${LINE_NUM}: '${LINE}'" + exit 1 +fi + +# ── Derive paths from mode ─────────────────────────────────────────────────── +AUDIT_PATH="${ITRIALSPACE_BASE}/inserted_masks/${TRIAL_MODE}/audit.json" +MASK_ROOT="${ITRIALSPACE_BASE}/inserted_masks/${TRIAL_MODE}" +OUT_DIR="${ITRIALSPACE_BASE}/generated_cts/${TRIAL_MODE}" +CONFIG_PATH="${NOMAISI_DIR}/tools/integration_config.yaml" + +# ── Banner ─────────────────────────────────────────────────────────────────── +echo "==================================================================" +echo " NodMAISI CT Rerun — ${TRIAL_MODE} — Case ${CASE_ID}" +echo " Array Job: ${SLURM_ARRAY_JOB_ID} Task: ${SLURM_ARRAY_TASK_ID}" +echo " Node: $(hostname) Date: $(date)" +echo "==================================================================" +echo " COMBINED_LIST: ${COMBINED_LIST}" +echo " AUDIT_PATH : ${AUDIT_PATH}" +echo " MASK_ROOT : ${MASK_ROOT}" +echo " OUT_DIR : ${OUT_DIR}" +echo "" + +# ── Environment ────────────────────────────────────────────────────────────── +export MONAI_DATA_DIRECTORY="${NOMAISI_DIR}/" +export PYTHONPATH="${NOMAISI_DIR}:${PYTHONPATH:-}" +export LD_LIBRARY_PATH="$(python -c 'import os,nvidia.cudnn;print(os.path.dirname(nvidia.cudnn.__file__)+"/lib")' 2>/dev/null):${LD_LIBRARY_PATH:-}" + +mkdir -p "${OUT_DIR}" + +# ── Build command — prefer audit.json, fallback to mask-root ───────────────── +CMD=( + python "${NOMAISI_DIR}/tools/run_itrialspace_to_ct.py" + --config "${CONFIG_PATH}" + --outdir "${OUT_DIR}" + --case-ids "${CASE_ID}" + -v +) + +if [ -f "${AUDIT_PATH}" ]; then + CMD+=(--audit "${AUDIT_PATH}") +else + CMD+=(--mask-root "${MASK_ROOT}") +fi + +echo "Command: ${CMD[*]}" +"${CMD[@]}" +EXIT_CODE=$? + +echo "" +echo "Finished case ${CASE_ID} (${TRIAL_MODE}): $(date) Exit: ${EXIT_CODE}" +exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/synthesis/submit_all_nodmaisi.sh b/itrialspace/infra/slurm/synthesis/submit_all_nodmaisi.sh new file mode 100644 index 0000000000000000000000000000000000000000..2a149341924efdc5e5602f3073cd383a7d2019ec --- /dev/null +++ b/itrialspace/infra/slurm/synthesis/submit_all_nodmaisi.sh @@ -0,0 +1,134 @@ +#!/bin/bash + +# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" + +# ============================================================================ +# Submit NodMAISI CT synthesis jobs for all 9 iTrialSpace trial modes. +# +# Reads audit.json from each mode's inserted_masks directory. +# +# Usage: +# ./submit_all_nodmaisi.sh # submit all 9 modes +# ./submit_all_nodmaisi.sh 1 3 8 # submit only modes 1, 3, 8 +# ./submit_all_nodmaisi.sh --dry-run # all modes, dry-run +# ============================================================================ + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd "$SCRIPT_DIR" + +NOMAISI_DIR="${PROJ_DIR}/src/itrialspace/synthesis" +ITRIALSPACE_BASE="${ITRIALSPACE_OUTPUT_DIR}" +MASK_BASE="${ITRIALSPACE_BASE}/inserted_masks" +CT_BASE="${ITRIALSPACE_BASE}/generated_cts" + +mkdir -p logs + +MODES=( + "mode1_controlled_prevalence" + "mode2_size_detection_curve" + "mode3_location_sensitivity" + "mode4_demographic_stratification" + "mode5_counterfactual" + "mode6_cross_dataset" + "mode7_bootstrap_confidence" + "mode8_algorithm_comparison" + "mode9_screening_simulation" +) + +MODE_NAMES=( + "Controlled Prevalence" + "Size Detection Curve" + "Location Sensitivity" + "Demographic Stratification" + "Counterfactual" + "Cross-Dataset" + "Bootstrap Confidence" + "Algorithm Comparison" + "Screening Simulation" +) + +# Parse --dry-run flag +DRY_RUN_EXPORT="" +POSITIONAL=() +for arg in "$@"; do + if [ "$arg" = "--dry-run" ]; then + DRY_RUN_EXPORT="--export=ALL,DRY_RUN=true" + else + POSITIONAL+=("$arg") + fi +done +set -- "${POSITIONAL[@]}" + +echo "==================================================================" +echo " iTrialSpace -> NodMAISI CT Synthesis — Batch Submission" +echo " Date: $(date)" +if [ -n "$DRY_RUN_EXPORT" ]; then + echo " *** DRY RUN MODE ***" +fi +echo "==================================================================" +echo "" + +submit_mode() { + local idx=$1 + local mode="${MODES[$idx]}" + local name="${MODE_NAMES[$idx]}" + local mask_dir="${MASK_BASE}/${mode}" + local audit_path="${mask_dir}/audit.json" + local out_dir="${CT_BASE}/${mode}" + + echo -n " Mode $((idx+1)): ${name} ... " + + # Check for audit.json at root or in any subdirectory + local audit_path="${mask_dir}/audit.json" + local has_sub_audits + has_sub_audits=$(find "${mask_dir}" -mindepth 2 -name "audit.json" 2>/dev/null | head -1) + + if [ -f "${audit_path}" ]; then + sbatch $DRY_RUN_EXPORT \ + --export=ALL,AUDIT_PATH="${audit_path}",OUT_DIR="${out_dir}" \ + --job-name="NM_M$((idx+1))" \ + template_nodmaisi_from_masks.sub + elif [ -n "${has_sub_audits}" ]; then + echo -n "(subdirectory audits found, using --mask-root) " + sbatch $DRY_RUN_EXPORT \ + --export=ALL,MASK_ROOT="${mask_dir}",OUT_DIR="${out_dir}" \ + --job-name="NM_M$((idx+1))" \ + template_nodmaisi_from_masks.sub + elif [ -d "${mask_dir}" ] && find "${mask_dir}" -name "*.nii.gz" -print -quit | grep -q .; then + echo -n "(no audit.json, using --mask-root) " + sbatch $DRY_RUN_EXPORT \ + --export=ALL,MASK_ROOT="${mask_dir}",OUT_DIR="${out_dir}" \ + --job-name="NM_M$((idx+1))" \ + template_nodmaisi_from_masks.sub + else + echo "SKIPPED (no audit.json and no masks in ${mask_dir})" + return + fi +} + +if [ $# -eq 0 ]; then + echo "Submitting all 9 trial modes..." + echo "" + for i in "${!MODES[@]}"; do + submit_mode "$i" + done +else + echo "Submitting selected trial modes..." + echo "" + for num in "$@"; do + idx=$((num - 1)) + if [ $idx -ge 0 ] && [ $idx -lt ${#MODES[@]} ]; then + submit_mode "$idx" + else + echo " Invalid mode number: $num (valid: 1-9)" + fi + done +fi + +echo "" +echo "--------------------------------------------------------------" +echo "Check status: squeue -u $USER" +echo "Cancel all: scancel -u $USER --name='NM_M*'" +echo "Logs: ${SCRIPT_DIR}/logs/" +echo "--------------------------------------------------------------" diff --git a/itrialspace/infra/slurm/synthesis/submit_array_jobs.sh b/itrialspace/infra/slurm/synthesis/submit_array_jobs.sh new file mode 100644 index 0000000000000000000000000000000000000000..9b3a396f3ef201ebe761a8bf9c24e866cf2e1cec --- /dev/null +++ b/itrialspace/infra/slurm/synthesis/submit_array_jobs.sh @@ -0,0 +1,326 @@ +#!/bin/bash + +# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" + +# ============================================================================ +# Submit NodMAISI CT synthesis ARRAY jobs for iTrialSpace trial modes. +# +# For each mode: generates a case list, then submits a SLURM array job +# (one case per GPU task) for maximum parallelism. +# +# Usage: +# ./submit_array_jobs.sh # all 13 modes +# ./submit_array_jobs.sh 1 3 8 # selected modes +# ./submit_array_jobs.sh --dry-run # all modes, dry-run +# ./submit_array_jobs.sh --max-concurrent 20 # limit concurrent GPU tasks +# ./submit_array_jobs.sh --time 04:00:00 # override walltime per task +# ./submit_array_jobs.sh --skip-existing # skip cases with synthetic_ct +# ./submit_array_jobs.sh --nodelist node001 # pin jobs to specific node +# ============================================================================ + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd "$SCRIPT_DIR" + +ITRIALSPACE_BASE="${ITRIALSPACE_OUTPUT_DIR}" +MASK_BASE="${ITRIALSPACE_BASE}/inserted_masks" +CT_BASE="${ITRIALSPACE_BASE}/generated_cts" +CASE_LIST_DIR="${ITRIALSPACE_BASE}/nodmaisi_case_lists" + +MAX_CONCURRENT="${MAX_CONCURRENT:-10}" +TIME_OVERRIDE="" +DRY_RUN="" +SKIP_EXISTING="" +NODELIST="" + +MODES=( + "mode1_controlled_prevalence" + "mode2_size_detection_curve" + "mode3_location_sensitivity" + "mode4_demographic_stratification" + "mode5_counterfactual" + "mode6_cross_dataset" + "mode7_bootstrap_confidence" + "mode8_algorithm_comparison" + "mode9_screening_simulation" + "mode10_multi_nodule_realism" + "mode11_digital_twin_isolation" + "mode12_digital_twin_complete" + "mode13_digital_twin_cross" +) + +MODE_NAMES=( + "Controlled Prevalence" + "Size Detection Curve" + "Location Sensitivity" + "Demographic Stratification" + "Counterfactual" + "Cross-Dataset" + "Bootstrap Confidence" + "Algorithm Comparison" + "Screening Simulation" + "Multi-Nodule Realism" + "Digital Twin Isolation" + "Digital Twin Complete" + "Digital Twin Cross" +) + +# ── Parse arguments ────────────────────────────────────────────────────────── +POSITIONAL=() +while [[ $# -gt 0 ]]; do + case "$1" in + --dry-run) DRY_RUN="true"; shift ;; + --skip-existing) SKIP_EXISTING="true"; shift ;; + --max-concurrent) MAX_CONCURRENT="$2"; shift 2 ;; + --time) TIME_OVERRIDE="$2"; shift 2 ;; + --nodelist) NODELIST="$2"; shift 2 ;; + *) POSITIONAL+=("$1"); shift ;; + esac +done +set -- "${POSITIONAL[@]+"${POSITIONAL[@]}"}" + +mkdir -p logs "${CASE_LIST_DIR}" + +echo "==================================================================" +echo " iTrialSpace -> NodMAISI — Array Job Submission" +echo " Date: $(date)" +echo " Max concurrent tasks per mode: ${MAX_CONCURRENT}" +[ -n "$DRY_RUN" ] && echo " *** DRY RUN MODE ***" +[ -n "$SKIP_EXISTING" ] && echo " Skip existing: YES (requires synthetic_ct + audit + QC slices)" +[ -n "$NODELIST" ] && echo " Node constraint: ${NODELIST}" +echo "==================================================================" +echo "" + +# ── Generate case list from audit.json or mask directory ───────────────────── +generate_case_list() { + local mode="$1" + local mask_dir="${MASK_BASE}/${mode}" + local case_list="${CASE_LIST_DIR}/${mode}_cases.txt" + + if [ -d "${mask_dir}" ]; then + # Hybrid discovery: use audit.json where available, fall back to + # file-scan for subdirectories that lack one (e.g. timed-out jobs). + python3 -c " +import json, os, glob + +mask_dir = '${mask_dir}' +case_ids = set() + +# --- Pass 1: extract from audit.json files --- +audited_dirs = set() +all_audits = sorted(glob.glob(os.path.join(mask_dir, '**', 'audit.json'), recursive=True)) +for af in all_audits: + audited_dirs.add(os.path.dirname(af)) + try: + audit = json.load(open(af)) + except Exception: + continue + for r in audit.get('records', []): + if r.get('status') != 'success': + continue + cp = r.get('output_combined_path', '') + if not cp or not os.path.isfile(cp): + continue + name = os.path.basename(cp) + for sfx in ('_mask.nii.gz', '.nii.gz'): + if name.endswith(sfx): + name = name[:-len(sfx)] + break + case_ids.add(name) + +# --- Pass 2: file-scan for dirs WITHOUT audit.json --- +for root, dirs, files in os.walk(mask_dir): + if root in audited_dirs: + continue # already covered by audit + for f in files: + if not f.endswith('.nii.gz'): + continue + name = f + for sfx in ('_mask.nii.gz', '.nii.gz'): + if name.endswith(sfx): + name = name[:-len(sfx)] + break + case_ids.add(name) + +cases = sorted(case_ids) +if cases: + open('${case_list}', 'w').write('\n'.join(cases) + '\n') +print(len(cases)) +" + else + echo "0" + return 1 + fi +} + +# ── Submit a single mode ──────────────────────────────────────────────────── +submit_mode() { + local idx=$1 + local mode="${MODES[$idx]}" + local name="${MODE_NAMES[$idx]}" + local mask_dir="${MASK_BASE}/${mode}" + local out_dir="${CT_BASE}/${mode}" + local case_list="${CASE_LIST_DIR}/${mode}_cases.txt" + + printf " Mode %d: %-30s " "$((idx+1))" "${name}" + + # Generate case list + local n_cases + n_cases=$(generate_case_list "$mode" 2>/dev/null) + if [ -z "$n_cases" ] || [ "$n_cases" -eq 0 ]; then + echo "SKIPPED (no cases found in ${mask_dir})" + return + fi + + # Optionally filter out already-completed cases + if [ -n "$SKIP_EXISTING" ] && [ -d "${out_dir}" ]; then + local orig_count=$n_cases + python3 -c " +import os, glob +case_list = '${case_list}' +out_dir = '${out_dir}' +cases = open(case_list).read().strip().split('\n') + +def is_complete(case_dir): + \"\"\"A case is complete only if it has synthetic_ct, audit, and QC slices.\"\"\" + if not os.path.isdir(case_dir): + return False + has_ct = os.path.isfile(os.path.join(case_dir, 'synthetic_ct.nii.gz')) + has_audit = os.path.isfile(os.path.join(case_dir, 'nodmaisi_audit.json')) + has_qc = len(glob.glob(os.path.join(case_dir, 'qc', 'qc_slice_*.png'))) > 0 + return has_ct and has_audit and has_qc + +pending = [] +for c in cases: + # Check both flat and sub-directory layouts + case_dir = os.path.join(out_dir, c) + found = is_complete(case_dir) + if not found: + for entry in (os.listdir(out_dir) if os.path.isdir(out_dir) else []): + sub_dir = os.path.join(out_dir, entry, c) + if is_complete(sub_dir): + found = True + break + if not found: + pending.append(c) +open(case_list, 'w').write('\n'.join(pending) + '\n' if pending else '') +print(len(pending)) +" + n_cases=$(wc -l < "${case_list}" | tr -d ' ') + local skipped=$((orig_count - n_cases)) + if [ "$skipped" -gt 0 ]; then + printf "(%d cases, skipped %d existing) " "$n_cases" "$skipped" + else + printf "(%4d cases) " "$n_cases" + fi + if [ "$n_cases" -eq 0 ]; then + echo "ALL DONE" + return + fi + else + printf "(%4d cases) " "$n_cases" + fi + + # SLURM MaxArraySize is typically 1001; chunk large case lists + local MAX_ARRAY_SIZE=1000 + local offset=0 + local chunk_idx=0 + local job_ids=() + + while [ $offset -lt $n_cases ]; do + local remaining=$((n_cases - offset)) + local chunk_size=$remaining + if [ $chunk_size -gt $MAX_ARRAY_SIZE ]; then + chunk_size=$MAX_ARRAY_SIZE + fi + + local sbatch_args="--array=0-$((chunk_size - 1))%${MAX_CONCURRENT}" + sbatch_args+=" --job-name=NM_M$((idx+1))_arr" + + if [ -n "$TIME_OVERRIDE" ]; then + sbatch_args+=" --time=${TIME_OVERRIDE}" + fi + + if [ -n "$NODELIST" ]; then + sbatch_args+=" --nodelist=${NODELIST}" + fi + + local export_vars="ALL,TRIAL_MODE=${mode},CASE_LIST=${case_list},OUT_DIR=${out_dir},CASE_OFFSET=${offset}" + sbatch_args+=" --export=${export_vars}" + + if [ -n "$DRY_RUN" ]; then + echo "Submitted batch job DRY-RUN (chunk $chunk_idx, ${chunk_size} tasks)" + else + # Wait for SLURM queue capacity (MaxJobCount=10000) + while true; do + local qcount + qcount=$(squeue -u "$USER" -r --noheader 2>/dev/null | wc -l) + local avail=$((10000 - qcount)) + if [ "$avail" -ge "$((chunk_size + 200))" ]; then + break + fi + printf "\n [waiting] Queue %d/10000, need %d free slots..." "$qcount" "$((chunk_size + 200))" + sleep 120 + done + + local sbatch_out + sbatch_out=$(sbatch ${sbatch_args} nodmaisi_array.sub) + echo "$sbatch_out" + local jid + jid=$(echo "$sbatch_out" | grep -oP '\d+') + if [ -n "$jid" ]; then + job_ids+=("$jid") + fi + fi + + offset=$((offset + chunk_size)) + chunk_idx=$((chunk_idx + 1)) + done + + # Submit post-run audit job (runs after all array chunks finish) + if [ ${#job_ids[@]} -gt 0 ]; then + local dep_str + dep_str=$(IFS=:; echo "${job_ids[*]}") + local audit_export="ALL,TRIAL_MODE=${mode},OUT_DIR=${out_dir},MASK_DIR=${mask_dir}" + local audit_out + audit_out=$(sbatch --dependency=afterany:${dep_str} \ + --job-name="audit_M$((idx+1))" \ + --export="${audit_export}" \ + audit_mode.sub 2>&1) + local audit_jid + audit_jid=$(echo "$audit_out" | grep -oP '\d+') + printf "\n -> Audit job %s (after %s)\n" "${audit_jid:-??}" "${dep_str}" + elif [ -n "$DRY_RUN" ]; then + printf "\n -> Audit job DRY-RUN (after all chunks)\n" + fi +} + +# ── Main ───────────────────────────────────────────────────────────────────── +if [ ${#POSITIONAL[@]} -eq 0 ] 2>/dev/null || [ $# -eq 0 ]; then + echo "Submitting all ${#MODES[@]} trial modes (1-${#MODES[@]})..." + echo "" + for i in "${!MODES[@]}"; do + submit_mode "$i" + done +else + echo "Submitting selected trial modes..." + echo "" + for num in "$@"; do + idx=$((num - 1)) + if [ $idx -ge 0 ] && [ $idx -lt ${#MODES[@]} ]; then + submit_mode "$idx" + else + echo " Invalid mode number: $num (valid: 1-${#MODES[@]})" + fi + done +fi + +echo "" +echo "--------------------------------------------------------------" +echo "Case lists: ${CASE_LIST_DIR}/" +echo "Check status: squeue -u $USER" +echo "Cancel all: scancel -u $USER --name='NM_M*'" +echo "Logs: ${SCRIPT_DIR}/logs/" +echo "--------------------------------------------------------------" diff --git a/itrialspace/infra/slurm/synthesis/template_nodmaisi_from_masks.sub b/itrialspace/infra/slurm/synthesis/template_nodmaisi_from_masks.sub new file mode 100644 index 0000000000000000000000000000000000000000..d7c3e4251a9e3c1c6c882d06ad88d3a1c8a3f0ec --- /dev/null +++ b/itrialspace/infra/slurm/synthesis/template_nodmaisi_from_masks.sub @@ -0,0 +1,79 @@ +#!/bin/bash +# ============================================================================ +# Template: iTrialSpace masks -> NodMAISI CT synthesis +# +# Generic SLURM template for running the integration pipeline. +# All parameters are configurable via environment variables. +# +# Usage: +# AUDIT_PATH=/path/to/audit.json OUT_DIR=/scratch/.../out sbatch template_nodmaisi_from_masks.sub +# MASK_ROOT=/path/to/masks OUT_DIR=/scratch/.../out sbatch template_nodmaisi_from_masks.sub +# ============================================================================ + +#SBATCH --job-name=iTS_NodMAISI +#SBATCH --partition=vram48 +#SBATCH --ntasks=1 +#SBATCH --gpus=1 +#SBATCH --cpus-per-task=16 +#SBATCH --mem=64G +#SBATCH --time=24:00:00 +#SBATCH --output=logs/iTS_NodMAISI_%j.out +#SBATCH --error=logs/iTS_NodMAISI_%j.err + +# ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) — before any var use ── +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" +itrialspace_activate_conda + + +set -euo pipefail + +# -- Configurable paths (override via environment) -- +NOMAISI_DIR="${NOMAISI_DIR:-${PROJ_DIR}/src/itrialspace/synthesis}" +CONFIG_PATH="${CONFIG_PATH:-${NOMAISI_DIR}/tools/integration_config.yaml}" +AUDIT_PATH="${AUDIT_PATH:-}" +MASK_ROOT="${MASK_ROOT:-}" +OUT_DIR="${OUT_DIR:-${ITRIALSPACE_OUTPUT_DIR}/generated_cts/default}" +DRY_RUN="${DRY_RUN:-false}" +CASE_IDS="${CASE_IDS:-}" +VERBOSE="${VERBOSE:--v}" + +echo "==================================================================" +echo " iTrialSpace -> NodMAISI CT Synthesis Pipeline" +echo " Job ID: ${SLURM_JOB_ID:-local} Node: $(hostname) Date: $(date)" +echo "==================================================================" +echo " AUDIT_PATH : ${AUDIT_PATH:-}" +echo " MASK_ROOT : ${MASK_ROOT:-}" +echo " OUT_DIR : ${OUT_DIR}" +echo " CONFIG_PATH : ${CONFIG_PATH}" +echo " DRY_RUN : ${DRY_RUN}" +echo "" + +# -- Environment setup -- +export MONAI_DATA_DIRECTORY="${NOMAISI_DIR}/" +export PYTHONPATH="${NOMAISI_DIR}:${PYTHONPATH:-}" + +mkdir -p "${OUT_DIR}" + +# -- Build command -- +CMD="python ${NOMAISI_DIR}/tools/run_itrialspace_to_ct.py" +CMD+=" --config ${CONFIG_PATH}" +CMD+=" --outdir ${OUT_DIR}" +CMD+=" ${VERBOSE}" + +if [ -n "${AUDIT_PATH}" ]; then + CMD+=" --audit ${AUDIT_PATH}" +elif [ -n "${MASK_ROOT}" ]; then + CMD+=" --mask-root ${MASK_ROOT}" +else + echo "FATAL: Set either AUDIT_PATH or MASK_ROOT" + exit 1 +fi + +[ "${DRY_RUN}" = "true" ] && CMD+=" --dry-run" +[ -n "${CASE_IDS}" ] && CMD+=" --case-ids ${CASE_IDS}" + +echo "Command: ${CMD}" +eval ${CMD} +EXIT_CODE=$? +echo "Finished: $(date) Exit: ${EXIT_CODE}" +exit ${EXIT_CODE} diff --git a/itrialspace/infra/slurm/trials/mode10_multi_nodule_realism.sub b/itrialspace/infra/slurm/trials/mode10_multi_nodule_realism.sub new file mode 100644 index 0000000000000000000000000000000000000000..2fcd771f3b18c4a4bd38a84d23e57fdadc4fdd94 --- /dev/null +++ b/itrialspace/infra/slurm/trials/mode10_multi_nodule_realism.sub @@ -0,0 +1,46 @@ +#!/bin/bash + +#SBATCH --job-name=iTS_M10_MultiNod +#SBATCH --mail-type=END,FAIL +#SBATCH -p defq +#SBATCH --ntasks=1 +#SBATCH --gpus=0 +#SBATCH --cpus-per-task=4 +#SBATCH --output=logs/mode10_multi_nodule_realism.out +#SBATCH --error=logs/mode10_multi_nodule_realism.err + +echo "=== iTrialSpace Trial Mode 10: Multi-Nodule Realism Study ===" +echo "Job ID: $SLURM_JOB_ID" +echo "Started: $(date)" + +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" +itrialspace_activate_conda + +# ── Configuration ────────────────────────────────────────────────────────── +RUNNER="${PROJ_DIR}/src/itrialspace/trials/run_trial.py" +OUTPUT_DIR="${ITRIALSPACE_OUTPUT_DIR}/manifests/mode10_multi_nodule_realism" + +# ── Trial Parameters ────────────────────────────────────────────────────── +# Multi-nodule realism study — creates two sub-cohorts: +# 1. Single-nodule cases (75%) +# 2. Multi-nodule cases with companions (25%) +# +# In NLST, ~25% of screened patients have multiple nodules. +# N_CASES=500 # real run (commented for 5-case smoke test) +N_CASES=5 +MULTI_NODULE_FRACTION=0.25 +COMPANION_STRATEGY="all_companions" +TEMPLATE="NLST" +SEED=42 + +# ── Run ──────────────────────────────────────────────────────────────────── +python3 "$RUNNER" \ + --mode multi_nodule \ + --output-dir "$OUTPUT_DIR" \ + --n-cases $N_CASES \ + --multi-nodule-fraction $MULTI_NODULE_FRACTION \ + --companion-strategy "$COMPANION_STRATEGY" \ + --template "$TEMPLATE" \ + --seed $SEED + +echo "Finished: $(date)" diff --git a/itrialspace/infra/slurm/trials/mode11_digital_twin_isolation.sub b/itrialspace/infra/slurm/trials/mode11_digital_twin_isolation.sub new file mode 100644 index 0000000000000000000000000000000000000000..0873069ea9ed10652f671ac5588da7bc6aad6f60 --- /dev/null +++ b/itrialspace/infra/slurm/trials/mode11_digital_twin_isolation.sub @@ -0,0 +1,52 @@ +#!/bin/bash + +#SBATCH --job-name=iTS_M11_DTiso +#SBATCH --mail-type=END,FAIL +#SBATCH -p defq +#SBATCH --ntasks=1 +#SBATCH --gpus=0 +#SBATCH --cpus-per-task=4 +#SBATCH --output=logs/mode11_digital_twin_isolation.out +#SBATCH --error=logs/mode11_digital_twin_isolation.err + +echo "=== iTrialSpace Trial Mode 11: Digital Twin Isolation ===" +echo "Job ID: $SLURM_JOB_ID" +echo "Started: $(date)" + +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" +itrialspace_activate_conda + +# ── Configuration ────────────────────────────────────────────────────────── +RUNNER="${PROJ_DIR}/src/itrialspace/trials/run_trial.py" +OUTPUT_BASE="${ITRIALSPACE_OUTPUT_DIR}/manifests/mode11_digital_twin_isolation" + +# ── Trial Parameters ────────────────────────────────────────────────────── +# Digital twin isolation — one isolation case per native nodule per CT scan. +# Matching is at the CT-scan level: each nodule is paired only with its own CT. +# Patients with multiple CT scans (e.g. LUNA25) produce separate cases per CT. +# Runs --all-patients for every dataset so every profiled nodule is covered. +SEED=42 + +# DATASETS=("DLCS24" "LUNA25" "LUNA16" "LUNGx" "LNDbv4" "NSCLCR" "IMDCT") # real run +DATASETS=("DLCS24") # sample + +# ── Run ──────────────────────────────────────────────────────────────────── +for DS in "${DATASETS[@]}"; do + echo "" + echo "──────────────────────────────────────────────────────────────" + echo " Dataset: ${DS}" + echo "──────────────────────────────────────────────────────────────" + + python3 "$RUNNER" \ + --mode digital_twin_isolation \ + --output-dir "${OUTPUT_BASE}/${DS}" \ + --dataset "$DS" \ + --max-patients 5 \ + --max-nodules-per-patient 1 \ + --seed $SEED + + echo " ${DS} done: $(date)" +done + +echo "" +echo "All datasets finished: $(date)" diff --git a/itrialspace/infra/slurm/trials/mode12_digital_twin_complete.sub b/itrialspace/infra/slurm/trials/mode12_digital_twin_complete.sub new file mode 100644 index 0000000000000000000000000000000000000000..55f02738972a2d34063b19ab966a1a3576425c04 --- /dev/null +++ b/itrialspace/infra/slurm/trials/mode12_digital_twin_complete.sub @@ -0,0 +1,51 @@ +#!/bin/bash + +#SBATCH --job-name=iTS_M12_DTcomp +#SBATCH --mail-type=END,FAIL +#SBATCH -p defq +#SBATCH --ntasks=1 +#SBATCH --gpus=0 +#SBATCH --cpus-per-task=4 +#SBATCH --output=logs/mode12_digital_twin_complete.out +#SBATCH --error=logs/mode12_digital_twin_complete.err + +echo "=== iTrialSpace Trial Mode 12: Digital Twin Complete ===" +echo "Job ID: $SLURM_JOB_ID" +echo "Started: $(date)" + +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" +itrialspace_activate_conda + +# ── Configuration ────────────────────────────────────────────────────────── +RUNNER="${PROJ_DIR}/src/itrialspace/trials/run_trial.py" +OUTPUT_BASE="${ITRIALSPACE_OUTPUT_DIR}/manifests/mode12_digital_twin_complete" + +# ── Trial Parameters ────────────────────────────────────────────────────── +# Digital twin complete — one case per CT scan containing ALL native nodules +# from that CT. Matching is at the CT-scan level: patients with multiple CT +# scans (e.g. LUNA25) produce one case per CT, not one case per patient. +# Runs --all-patients for every dataset. +SEED=42 + +# DATASETS=("DLCS24" "LUNA25" "LUNA16" "LUNGx" "LNDbv4" "NSCLCR" "IMDCT") # real run +DATASETS=("DLCS24") # sample + +# ── Run ──────────────────────────────────────────────────────────────────── +for DS in "${DATASETS[@]}"; do + echo "" + echo "──────────────────────────────────────────────────────────────" + echo " Dataset: ${DS}" + echo "──────────────────────────────────────────────────────────────" + + python3 "$RUNNER" \ + --mode digital_twin_complete \ + --output-dir "${OUTPUT_BASE}/${DS}" \ + --dataset "$DS" \ + --max-patients 5 \ + --seed $SEED + + echo " ${DS} done: $(date)" +done + +echo "" +echo "All datasets finished: $(date)" diff --git a/itrialspace/infra/slurm/trials/mode13_digital_twin_cross.sub b/itrialspace/infra/slurm/trials/mode13_digital_twin_cross.sub new file mode 100644 index 0000000000000000000000000000000000000000..8d01b9ace25309684512cc5c44deb75adfbc14f4 --- /dev/null +++ b/itrialspace/infra/slurm/trials/mode13_digital_twin_cross.sub @@ -0,0 +1,76 @@ +#!/bin/bash + +#SBATCH --job-name=iTS_M13_DTcross +#SBATCH --mail-type=END,FAIL +#SBATCH -p defq +#SBATCH --ntasks=1 +#SBATCH --gpus=0 +#SBATCH --cpus-per-task=4 +#SBATCH --output=logs/mode13_digital_twin_cross.out +#SBATCH --error=logs/mode13_digital_twin_cross.err + +echo "=== iTrialSpace Trial Mode 13: Digital Twin Cross ===" +echo "Job ID: $SLURM_JOB_ID" +echo "Started: $(date)" + +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" +itrialspace_activate_conda + +# ── Configuration ────────────────────────────────────────────────────────── +RUNNER="${PROJ_DIR}/src/itrialspace/trials/run_trial.py" +OUTPUT_BASE="${ITRIALSPACE_OUTPUT_DIR}/manifests/mode13_digital_twin_cross" + +# ── Trial Parameters ────────────────────────────────────────────────────── +# Digital twin cross — donor nodules from one patient inserted into a +# different patient's anatomy. Each host×donor dataset pair produces a +# separate manifest. +SEED=42 + +# Host datasets provide anatomy; donor datasets provide nodules. +# Adjust these arrays for your experimental design. +# HOST_DATASETS=("DLCS24" "LUNA25" "LUNA16" "LUNGx" "LNDbv4" "NSCLCR" "IMDCT") # real run +HOST_DATASETS=("DLCS24") # sample +# DONOR_DATASETS=("DLCS24" "LUNA25" "LUNA16" "LUNGx" "LNDbv4" "NSCLCR" "IMDCT") # real run +DONOR_DATASETS=("LUNA25") # sample + +# Pairing configuration (override with env vars if needed) +DONOR_TRANSFER_MODE="${DONOR_TRANSFER_MODE:-single}" +PAIRING_POLICY="${PAIRING_POLICY:-one_to_one}" +PLACEMENT_STRATEGY="${PLACEMENT_STRATEGY:-profile_faithful_transfer}" + +# Cap donor nodules per cross-pair to ~250 for a ~10k total budget. +# LUNGx has only 83 donors so it uses all of them; others cap at 250. +MAX_DONOR_NODULES="${MAX_DONOR_NODULES:-5}" # sample (real: 250) + +# ── Run ──────────────────────────────────────────────────────────────────── +for HOST_DS in "${HOST_DATASETS[@]}"; do + for DONOR_DS in "${DONOR_DATASETS[@]}"; do + # Skip same-dataset pairs (that's what modes 11/12 are for) + if [ "$HOST_DS" = "$DONOR_DS" ]; then + echo " Skipping same-dataset pair: ${HOST_DS} × ${DONOR_DS}" + continue + fi + + echo "" + echo "──────────────────────────────────────────────────────────────" + echo " Host: ${HOST_DS} × Donor: ${DONOR_DS}" + echo "──────────────────────────────────────────────────────────────" + + python3 "$RUNNER" \ + --mode digital_twin_cross \ + --output-dir "${OUTPUT_BASE}/${HOST_DS}_x_${DONOR_DS}" \ + --host-dataset "$HOST_DS" \ + --donor-dataset "$DONOR_DS" \ + --max-host-patients 5 \ + --max-donor-nodules "$MAX_DONOR_NODULES" \ + --donor-transfer-mode "$DONOR_TRANSFER_MODE" \ + --pairing-policy "$PAIRING_POLICY" \ + --placement-strategy "$PLACEMENT_STRATEGY" \ + --seed $SEED + + echo " ${HOST_DS} × ${DONOR_DS} done: $(date)" + done +done + +echo "" +echo "All dataset pairs finished: $(date)" diff --git a/itrialspace/infra/slurm/trials/mode1_controlled_prevalence.sub b/itrialspace/infra/slurm/trials/mode1_controlled_prevalence.sub new file mode 100644 index 0000000000000000000000000000000000000000..0ad5fa2f309cc7635fead3a6d1f7e72e2f7ad4e9 --- /dev/null +++ b/itrialspace/infra/slurm/trials/mode1_controlled_prevalence.sub @@ -0,0 +1,38 @@ +#!/bin/bash + +#SBATCH --job-name=iTS_M1_Prevalence +#SBATCH --mail-type=END,FAIL +#SBATCH -p defq +#SBATCH --ntasks=1 +#SBATCH --gpus=0 +#SBATCH --cpus-per-task=4 +#SBATCH --output=logs/mode1_controlled_prevalence.out +#SBATCH --error=logs/mode1_controlled_prevalence.err + +echo "=== iTrialSpace Trial Mode 1: Controlled Prevalence Study ===" +echo "Job ID: $SLURM_JOB_ID" +echo "Started: $(date)" + +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh"; itrialspace_activate_conda + +# ── Configuration ────────────────────────────────────────────────────────── +RUNNER="${PROJ_DIR}/src/itrialspace/trials/run_trial.py" +OUTPUT_DIR="${ITRIALSPACE_OUTPUT_DIR}/manifests/mode1_controlled_prevalence" + +# ── Trial Parameters ────────────────────────────────────────────────────── +# N_CASES=1000 # paper run (commented for 5-case demo) +N_CASES=5 # Total cases in the cohort +PREVALENCE=0.05 # 5% malignancy prevalence (typical NLST-like) +TEMPLATE="NLST" # Trial template for demographics/size distribution +SEED=42 # Random seed for reproducibility + +# ── Run ──────────────────────────────────────────────────────────────────── +python3 "$RUNNER" \ + --mode controlled_prevalence \ + --output-dir "$OUTPUT_DIR" \ + --n-cases $N_CASES \ + --prevalence $PREVALENCE \ + --template "$TEMPLATE" \ + --seed $SEED + +echo "Finished: $(date)" diff --git a/itrialspace/infra/slurm/trials/mode2_size_detection_curve.sub b/itrialspace/infra/slurm/trials/mode2_size_detection_curve.sub new file mode 100644 index 0000000000000000000000000000000000000000..9be10bfd735f8a34636d10bbbadfdedd5c432582 --- /dev/null +++ b/itrialspace/infra/slurm/trials/mode2_size_detection_curve.sub @@ -0,0 +1,39 @@ +#!/bin/bash + +#SBATCH --job-name=iTS_M2_SizeCurve +#SBATCH --mail-type=END,FAIL +#SBATCH -p defq +#SBATCH --ntasks=1 +#SBATCH --gpus=0 +#SBATCH --cpus-per-task=4 +#SBATCH --output=logs/mode2_size_detection_curve.out +#SBATCH --error=logs/mode2_size_detection_curve.err + +echo "=== iTrialSpace Trial Mode 2: Size Detection Curve ===" +echo "Job ID: $SLURM_JOB_ID" +echo "Started: $(date)" + +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh"; itrialspace_activate_conda + +# ── Configuration ────────────────────────────────────────────────────────── +RUNNER="${PROJ_DIR}/src/itrialspace/trials/run_trial.py" +OUTPUT_DIR="${ITRIALSPACE_OUTPUT_DIR}/manifests/mode2_size_detection_curve" + +# ── Trial Parameters ────────────────────────────────────────────────────── +# Produces 6 manifests (one per size bucket: <5mm, 5-10mm, 10-15mm, 15-20mm, 20-30mm, >30mm) +# N_PER_BUCKET=100 # Cases per size bucket # real run (commented for 5-case smoke test) +N_PER_BUCKET=5 # Cases per size bucket +LABEL=1 # 1=malignant nodules (for FROC detection curves) +TEMPLATE="NLST" # Trial template +SEED=42 + +# ── Run ──────────────────────────────────────────────────────────────────── +python3 "$RUNNER" \ + --mode size_detection_curve \ + --output-dir "$OUTPUT_DIR" \ + --n-per-bucket $N_PER_BUCKET \ + --label $LABEL \ + --template "$TEMPLATE" \ + --seed $SEED + +echo "Finished: $(date)" diff --git a/itrialspace/infra/slurm/trials/mode3_location_sensitivity.sub b/itrialspace/infra/slurm/trials/mode3_location_sensitivity.sub new file mode 100644 index 0000000000000000000000000000000000000000..8f6c9ff34db686ab15c6cd263168d61476e516eb --- /dev/null +++ b/itrialspace/infra/slurm/trials/mode3_location_sensitivity.sub @@ -0,0 +1,44 @@ +#!/bin/bash + +#SBATCH --job-name=iTS_M3_Location +#SBATCH --mail-type=END,FAIL +#SBATCH -p defq +#SBATCH --ntasks=1 +#SBATCH --gpus=0 +#SBATCH --cpus-per-task=4 +#SBATCH --output=logs/mode3_location_sensitivity.out +#SBATCH --error=logs/mode3_location_sensitivity.err + +echo "=== iTrialSpace Trial Mode 3: Location Sensitivity ===" +echo "Job ID: $SLURM_JOB_ID" +echo "Started: $(date)" + +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh"; itrialspace_activate_conda + +# ── Configuration ────────────────────────────────────────────────────────── +RUNNER="${PROJ_DIR}/src/itrialspace/trials/run_trial.py" +OUTPUT_DIR="${ITRIALSPACE_OUTPUT_DIR}/manifests/mode3_location_sensitivity" + +# ── Trial Parameters ────────────────────────────────────────────────────── +# Produces 5 manifests (one per lobe: RUL, RML, RLL, LUL, LLL) +# Same nodule size range, varies only anatomical location +# N_PER_LOBE=100 # Cases per lobe # real run (commented for 5-case smoke test) +N_PER_LOBE=5 # Cases per lobe +LABEL=1 # 1=malignant +DIAM_MIN=6.0 # Minimum diameter (mm) +DIAM_MAX=15.0 # Maximum diameter (mm) +TEMPLATE="NLST" +SEED=42 + +# ── Run ──────────────────────────────────────────────────────────────────── +python3 "$RUNNER" \ + --mode location_sensitivity \ + --output-dir "$OUTPUT_DIR" \ + --n-per-lobe $N_PER_LOBE \ + --label $LABEL \ + --diam-min $DIAM_MIN \ + --diam-max $DIAM_MAX \ + --template "$TEMPLATE" \ + --seed $SEED + +echo "Finished: $(date)" diff --git a/itrialspace/infra/slurm/trials/mode4_demographic_stratification.sub b/itrialspace/infra/slurm/trials/mode4_demographic_stratification.sub new file mode 100644 index 0000000000000000000000000000000000000000..ac203e42935cbfefb2988f11e58e0007a80dece6 --- /dev/null +++ b/itrialspace/infra/slurm/trials/mode4_demographic_stratification.sub @@ -0,0 +1,41 @@ +#!/bin/bash + +#SBATCH --job-name=iTS_M4_DemoStrat +#SBATCH --mail-type=END,FAIL +#SBATCH -p defq +#SBATCH --ntasks=1 +#SBATCH --gpus=0 +#SBATCH --cpus-per-task=4 +#SBATCH --output=logs/mode4_demographic_stratification.out +#SBATCH --error=logs/mode4_demographic_stratification.err + +echo "=== iTrialSpace Trial Mode 4: Demographic Stratification ===" +echo "Job ID: $SLURM_JOB_ID" +echo "Started: $(date)" + +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh"; itrialspace_activate_conda + +# ── Configuration ────────────────────────────────────────────────────────── +RUNNER="${PROJ_DIR}/src/itrialspace/trials/run_trial.py" +OUTPUT_DIR="${ITRIALSPACE_OUTPUT_DIR}/manifests/mode4_demographic_stratification" + +# ── Trial Parameters ────────────────────────────────────────────────────── +# Produces 4 manifests (default strata): +# Stratum 0: Male, 55-65 +# Stratum 1: Male, 65-75 +# Stratum 2: Female, 55-65 +# Stratum 3: Female, 65-75 +# N_PER_STRATUM=200 # Cases per demographic stratum # real run (commented for 5-case smoke test) +N_PER_STRATUM=5 # Cases per demographic stratum +TEMPLATE="NLST" # Trial template for base parameters +SEED=42 + +# ── Run ──────────────────────────────────────────────────────────────────── +python3 "$RUNNER" \ + --mode demographic_strat \ + --output-dir "$OUTPUT_DIR" \ + --n-per-stratum $N_PER_STRATUM \ + --template "$TEMPLATE" \ + --seed $SEED + +echo "Finished: $(date)" diff --git a/itrialspace/infra/slurm/trials/mode5_counterfactual.sub b/itrialspace/infra/slurm/trials/mode5_counterfactual.sub new file mode 100644 index 0000000000000000000000000000000000000000..28484e342eeed968030285469fd15e6d4d780cb3 --- /dev/null +++ b/itrialspace/infra/slurm/trials/mode5_counterfactual.sub @@ -0,0 +1,42 @@ +#!/bin/bash + +#SBATCH --job-name=iTS_M5_Counterfact +#SBATCH --mail-type=END,FAIL +#SBATCH -p defq +#SBATCH --ntasks=1 +#SBATCH --gpus=0 +#SBATCH --cpus-per-task=4 +#SBATCH --output=logs/mode5_counterfactual.out +#SBATCH --error=logs/mode5_counterfactual.err + +echo "=== iTrialSpace Trial Mode 5: Counterfactual Cohort ===" +echo "Job ID: $SLURM_JOB_ID" +echo "Started: $(date)" + +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh"; itrialspace_activate_conda + +# ── Configuration ────────────────────────────────────────────────────────── +RUNNER="${PROJ_DIR}/src/itrialspace/trials/run_trial.py" +OUTPUT_DIR="${ITRIALSPACE_OUTPUT_DIR}/manifests/mode5_counterfactual" + +# ── Trial Parameters ────────────────────────────────────────────────────── +# Same base cohort with one parameter varied across values +# Measures the effect of a single variable on algorithm performance +# N_CASES=500 # Cases per variant # real run (commented for 5-case smoke test) +N_CASES=5 # Cases per variant +TEMPLATE="NLST" +VARY_PARAM="malignancy_prevalence" +VALUES="0.01,0.02,0.05,0.10,0.20" # 5 variants +SEED=42 # Same seed → same base cohort structure + +# ── Run ──────────────────────────────────────────────────────────────────── +python3 "$RUNNER" \ + --mode counterfactual \ + --output-dir "$OUTPUT_DIR" \ + --n-cases $N_CASES \ + --template "$TEMPLATE" \ + --vary-param "$VARY_PARAM" \ + --values "$VALUES" \ + --seed $SEED + +echo "Finished: $(date)" diff --git a/itrialspace/infra/slurm/trials/mode6_cross_dataset.sub b/itrialspace/infra/slurm/trials/mode6_cross_dataset.sub new file mode 100644 index 0000000000000000000000000000000000000000..9ffc4943ae483f13f1c00655108e1c39bf2d8ffb --- /dev/null +++ b/itrialspace/infra/slurm/trials/mode6_cross_dataset.sub @@ -0,0 +1,38 @@ +#!/bin/bash + +#SBATCH --job-name=iTS_M6_CrossDS +#SBATCH --mail-type=END,FAIL +#SBATCH -p defq +#SBATCH --ntasks=1 +#SBATCH --gpus=0 +#SBATCH --cpus-per-task=4 +#SBATCH --output=logs/mode6_cross_dataset.out +#SBATCH --error=logs/mode6_cross_dataset.err + +echo "=== iTrialSpace Trial Mode 6: Cross-Dataset Generalization ===" +echo "Job ID: $SLURM_JOB_ID" +echo "Started: $(date)" + +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh"; itrialspace_activate_conda + +# ── Configuration ────────────────────────────────────────────────────────── +RUNNER="${PROJ_DIR}/src/itrialspace/trials/run_trial.py" +OUTPUT_DIR="${ITRIALSPACE_OUTPUT_DIR}/manifests/mode6_cross_dataset" + +# ── Trial Parameters ────────────────────────────────────────────────────── +# One manifest per dataset as sole nodule donor +# Tests whether algorithm performance varies by data source +# N_CASES=300 # real run (commented for 5-case smoke test) +N_CASES=5 +DATASETS="DLCS24,LUNA25,LNDbv4,IMDCT,LUNGx" # 5 datasets +SEED=42 + +# ── Run ──────────────────────────────────────────────────────────────────── +python3 "$RUNNER" \ + --mode cross_dataset \ + --output-dir "$OUTPUT_DIR" \ + --n-cases $N_CASES \ + --datasets "$DATASETS" \ + --seed $SEED + +echo "Finished: $(date)" diff --git a/itrialspace/infra/slurm/trials/mode7_bootstrap_confidence.sub b/itrialspace/infra/slurm/trials/mode7_bootstrap_confidence.sub new file mode 100644 index 0000000000000000000000000000000000000000..fab3a95c289afa1047e00c4e93c00e19332f3d84 --- /dev/null +++ b/itrialspace/infra/slurm/trials/mode7_bootstrap_confidence.sub @@ -0,0 +1,44 @@ +#!/bin/bash + +#SBATCH --job-name=iTS_M7_Bootstrap +#SBATCH --mail-type=END,FAIL +#SBATCH -p defq +#SBATCH --ntasks=1 +#SBATCH --gpus=0 +#SBATCH --cpus-per-task=4 +#SBATCH --output=logs/mode7_bootstrap_confidence.out +#SBATCH --error=logs/mode7_bootstrap_confidence.err + +echo "=== iTrialSpace Trial Mode 7: Bootstrap Confidence Intervals ===" +echo "Job ID: $SLURM_JOB_ID" +echo "Started: $(date)" + +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh"; itrialspace_activate_conda + +# ── Configuration ────────────────────────────────────────────────────────── +RUNNER="${PROJ_DIR}/src/itrialspace/trials/run_trial.py" +OUTPUT_DIR="${ITRIALSPACE_OUTPUT_DIR}/manifests/mode7_bootstrap_confidence" + +# ── Trial Parameters ────────────────────────────────────────────────────── +# N independent bootstrap replicates of a base cohort +# Use to compute confidence intervals on algorithm performance metrics +# N_CASES=200 # Cases per replicate # real run (commented for 5-case smoke test) +N_CASES=5 # Cases per replicate +PREVALENCE=0.05 # Base prevalence +# N_BOOTSTRAP=20 # Number of bootstrap replicates # real run (commented for 5-case smoke test) +N_BOOTSTRAP=3 # Number of bootstrap replicates +TEMPLATE="NLST" +SEED=42 + +# ── Run ──────────────────────────────────────────────────────────────────── +python3 "$RUNNER" \ + --mode bootstrap_confidence \ + --output-dir "$OUTPUT_DIR" \ + --n-cases $N_CASES \ + --prevalence $PREVALENCE \ + --n-bootstrap $N_BOOTSTRAP \ + --template "$TEMPLATE" \ + --seed $SEED \ + --no-verify-paths # Skip path check for 100 replicates (too slow) + +echo "Finished: $(date)" diff --git a/itrialspace/infra/slurm/trials/mode8_algorithm_comparison.sub b/itrialspace/infra/slurm/trials/mode8_algorithm_comparison.sub new file mode 100644 index 0000000000000000000000000000000000000000..2f84fc082db3cc8fac47d1f68fcf9c4b491ee009 --- /dev/null +++ b/itrialspace/infra/slurm/trials/mode8_algorithm_comparison.sub @@ -0,0 +1,39 @@ +#!/bin/bash + +#SBATCH --job-name=iTS_M8_AlgoComp +#SBATCH --mail-type=END,FAIL +#SBATCH -p defq +#SBATCH --ntasks=1 +#SBATCH --gpus=0 +#SBATCH --cpus-per-task=4 +#SBATCH --output=logs/mode8_algorithm_comparison.out +#SBATCH --error=logs/mode8_algorithm_comparison.err + +echo "=== iTrialSpace Trial Mode 8: Algorithm Comparison ===" +echo "Job ID: $SLURM_JOB_ID" +echo "Started: $(date)" + +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh"; itrialspace_activate_conda + +# ── Configuration ────────────────────────────────────────────────────────── +RUNNER="${PROJ_DIR}/src/itrialspace/trials/run_trial.py" +OUTPUT_DIR="${ITRIALSPACE_OUTPUT_DIR}/manifests/mode8_algorithm_comparison" + +# ── Trial Parameters ────────────────────────────────────────────────────── +# Single standardised cohort for head-to-head algorithm comparison +# Fixed seed ensures identical manifest on every run +# Use the same manifest to evaluate multiple CADe/CADx models +# N_CASES=500 # real run (commented for 5-case smoke test) +N_CASES=5 +TEMPLATE="NLST" +SEED=42 + +# ── Run ──────────────────────────────────────────────────────────────────── +python3 "$RUNNER" \ + --mode algorithm_comparison \ + --output-dir "$OUTPUT_DIR" \ + --n-cases $N_CASES \ + --template "$TEMPLATE" \ + --seed $SEED + +echo "Finished: $(date)" diff --git a/itrialspace/infra/slurm/trials/mode9_screening_simulation.sub b/itrialspace/infra/slurm/trials/mode9_screening_simulation.sub new file mode 100644 index 0000000000000000000000000000000000000000..3592848d006e5726f7b12502924dffdc65037320 --- /dev/null +++ b/itrialspace/infra/slurm/trials/mode9_screening_simulation.sub @@ -0,0 +1,48 @@ +#!/bin/bash + +#SBATCH --job-name=iTS_M9_Screening +#SBATCH --mail-type=END,FAIL +#SBATCH -p defq +#SBATCH --ntasks=1 +#SBATCH --gpus=0 +#SBATCH --cpus-per-task=4 +#SBATCH --output=logs/mode9_screening_simulation.out +#SBATCH --error=logs/mode9_screening_simulation.err + +echo "=== iTrialSpace Trial Mode 9: Screening Protocol Simulation ===" +echo "Job ID: $SLURM_JOB_ID" +echo "Started: $(date)" + +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh"; itrialspace_activate_conda + +# ── Configuration ────────────────────────────────────────────────────────── +RUNNER="${PROJ_DIR}/src/itrialspace/trials/run_trial.py" +OUTPUT_DIR="${ITRIALSPACE_OUTPUT_DIR}/manifests/mode9_screening_simulation" + +# ── Trial Parameters ────────────────────────────────────────────────────── +# Multi-round screening protocol simulation +# Each round has decreasing malignancy prevalence (cancers caught in +# earlier rounds are removed from later rounds) +# +# With NLST baseline prevalence=0.04 and decay=0.7: +# Round 1: prev=0.040 +# Round 2: prev=0.028 +# Round 3: prev=0.020 +N_ROUNDS=3 +# N_CASES_PER_ROUND=500 # real run (commented for 5-case smoke test) +N_CASES_PER_ROUND=5 +PREVALENCE_DECAY=0.7 # Multiplicative decay per round +TEMPLATE="NLST" +SEED=42 + +# ── Run ──────────────────────────────────────────────────────────────────── +python3 "$RUNNER" \ + --mode screening_simulation \ + --output-dir "$OUTPUT_DIR" \ + --n-rounds $N_ROUNDS \ + --n-cases-per-round $N_CASES_PER_ROUND \ + --prevalence-decay $PREVALENCE_DECAY \ + --template "$TEMPLATE" \ + --seed $SEED + +echo "Finished: $(date)" diff --git a/itrialspace/infra/slurm/trials/submit_all.sh b/itrialspace/infra/slurm/trials/submit_all.sh new file mode 100644 index 0000000000000000000000000000000000000000..b29bf7d1f89f1e6b65a44c9f4895fac3802311f1 --- /dev/null +++ b/itrialspace/infra/slurm/trials/submit_all.sh @@ -0,0 +1,56 @@ +#!/bin/bash +# Submit all iTrialSpace trial mode jobs to SLURM +# +# Usage: +# ./submit_all.sh # submit all modes +# ./submit_all.sh 1 3 8 # submit only modes 1, 3, 8 +# +# Each mode runs independently — no dependencies between jobs. + +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd "$SCRIPT_DIR" + +# Ensure logs directory exists +mkdir -p logs + +MODES=( + "mode1_controlled_prevalence" + "mode2_size_detection_curve" + "mode3_location_sensitivity" + "mode4_demographic_stratification" + "mode5_counterfactual" + "mode6_cross_dataset" + "mode7_bootstrap_confidence" + "mode8_algorithm_comparison" + "mode9_screening_simulation" + "mode10_multi_nodule_realism" + "mode11_digital_twin_isolation" + "mode12_digital_twin_complete" + "mode13_digital_twin_cross" +) + +if [ $# -eq 0 ]; then + # Submit all + echo "Submitting all ${#MODES[@]} trial modes..." + for mode in "${MODES[@]}"; do + echo -n " $mode: " + sbatch "${mode}.sub" + done +else + # Submit selected modes + echo "Submitting selected trial modes..." + for num in "$@"; do + idx=$((num - 1)) + if [ $idx -ge 0 ] && [ $idx -lt ${#MODES[@]} ]; then + mode="${MODES[$idx]}" + echo -n " $mode: " + sbatch "${mode}.sub" + else + echo " Invalid mode number: $num (valid: 1-${#MODES[@]})" + fi + done +fi + +echo "" +echo "Check status with: squeue -u $USER" +echo "Check logs in: $SCRIPT_DIR/logs/" diff --git a/itrialspace/infra/slurm/vlm_eval/README.md b/itrialspace/infra/slurm/vlm_eval/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f437fcadc4c3bd1a13c8c2710617dab535f026fe --- /dev/null +++ b/itrialspace/infra/slurm/vlm_eval/README.md @@ -0,0 +1,105 @@ +# VLM evaluation — SLURM jobs + +Three env-driven jobs cover the whole VLM evaluation, in order: + +| Step | Job | Partition | What it does | +|------|-----|-----------|--------------| +| 1 | `build_dataset.sub` | CPU (`defq`) | Build the 2-D eval dataset (slices + overlays + ground truth) | +| 2 | `run_vlm.sub` | GPU (`vram48`) | Run one model across all 4 conditions × 3 tasks | +| 3 | `analyze.sub` | CPU (`defq`) | Tables, figures, stats, `report.md` (the `eval_analysis` engine) | + +All jobs source `infra/slurm/env.sh` (so `PROJ_DIR`, `ITRIALSPACE_DATA_DIR`, +`ITRIALSPACE_OUTPUT_DIR`, conda, partitions, and `.env` are resolved automatically) and are +configured entirely through environment variables — **no editing**. Submit from the repo root. + +Models and profiles: **BiomedCLIP** and **LLaVA-Med** use the `lung_axial` eval set; +**MedGemma** uses `lung_axial_medgemma` (3-channel CT). Build both profiles to evaluate all three. + +--- + +## Quickstart — the small DEMO (defaults) + +Uses the demo data under `$ITRIALSPACE_OUTPUT_DIR` (e.g. +`/scratch/railabs/ft42/VLST_Project/Data/outputs_iTrialSpace`). Everything below is copy-paste. + +```bash +cd + +# 1) Build demo eval sets (synthetic modes 1–3, both profiles; + a small real set) +sbatch infra/slurm/vlm_eval/build_dataset.sub # synthetic · lung_axial +PROFILE=lung_axial_medgemma sbatch infra/slurm/vlm_eval/build_dataset.sub # synthetic · medgemma +VLM_SET=real sbatch infra/slurm/vlm_eval/build_dataset.sub # real · lung_axial +VLM_SET=real PROFILE=lung_axial_medgemma sbatch infra/slurm/vlm_eval/build_dataset.sub + +# 2) Run the three models on the synthetic demo +B=$ITRIALSPACE_OUTPUT_DIR/vlm_eval_demo +MODEL=biomedclip EVAL_DIR=$B/lung_axial sbatch infra/slurm/vlm_eval/run_vlm.sub +MODEL=llava_med EVAL_DIR=$B/lung_axial sbatch infra/slurm/vlm_eval/run_vlm.sub +MODEL=medgemma EVAL_DIR=$B/lung_axial_medgemma sbatch infra/slurm/vlm_eval/run_vlm.sub + +# 3) Analyse everything found under the demo output +sbatch infra/slurm/vlm_eval/analyze.sub # → $B/eval_analysis/report.md +``` + +Chain steps with SLURM dependencies if you want one submission: +```bash +J=$(sbatch --parsable infra/slurm/vlm_eval/build_dataset.sub) +R=$(MODEL=biomedclip sbatch --parsable --dependency=afterok:$J infra/slurm/vlm_eval/run_vlm.sub) +sbatch --dependency=afterok:$R infra/slurm/vlm_eval/analyze.sub +``` + +--- + +## Scaling to the full / curated dataset + +The released dataset already ships the **built** eval sets and **frozen splits** under +`$ITRIALSPACE_DATA_DIR/vlm_dataset/{synthetic,real}//` and +`…/vlm_dataset/splits/` — so on the shared data you usually **skip step 1** and go straight to +step 2, scoring a fixed split: + +```bash +B=$ITRIALSPACE_DATA_DIR/vlm_dataset/synthetic +S=$ITRIALSPACE_DATA_DIR/vlm_dataset/splits/release_v1_full.synthetic.txt +MODEL=biomedclip CASE_IDS=$S EVAL_DIR=$B/lung_axial sbatch infra/slurm/vlm_eval/run_vlm.sub +MODEL=llava_med CASE_IDS=$S EVAL_DIR=$B/lung_axial sbatch infra/slurm/vlm_eval/run_vlm.sub +MODEL=medgemma CASE_IDS=$S EVAL_DIR=$B/lung_axial_medgemma sbatch infra/slurm/vlm_eval/run_vlm.sub +# (same for the real set under …/vlm_dataset/real with release_v1_full.real.txt) + +RESULTS=$ITRIALSPACE_DATA_DIR/vlm_dataset SPLIT=release_v1_full \ + sbatch infra/slurm/vlm_eval/analyze.sub +``` + +To **regenerate** the full eval sets from scratch (step 1 on all data): +```bash +# synthetic, all 13 modes, both profiles +VLM_MODES="1 2 3 4 5 6 7 8 9 10 11 12 13" \ + EVAL_DIR=$ITRIALSPACE_DATA_DIR/vlm_dataset/synthetic/lung_axial \ + sbatch infra/slurm/vlm_eval/build_dataset.sub +VLM_MODES="1 2 3 4 5 6 7 8 9 10 11 12 13" PROFILE=lung_axial_medgemma \ + EVAL_DIR=$ITRIALSPACE_DATA_DIR/vlm_dataset/synthetic/lung_axial_medgemma \ + sbatch infra/slurm/vlm_eval/build_dataset.sub +# real, all 7 datasets, ALL cases (VLM_MAX="") +VLM_SET=real VLM_MAX="" VLM_DATASETS="DLCS24 LUNA25 LUNA16 LUNGx LNDbv4 NSCLCR IMDCT" \ + EVAL_DIR=$ITRIALSPACE_DATA_DIR/vlm_dataset/real/lung_axial \ + sbatch infra/slurm/vlm_eval/build_dataset.sub +# (+ the lung_axial_medgemma profile for real) +``` + +## Transferring to another cluster + +Set these (in `.env` or the submit environment) and nothing else changes: +`ITRIALSPACE_DATA_DIR`, `ITRIALSPACE_OUTPUT_DIR`, `ITRIALSPACE_CONDA_ENV`, and the partitions +`SLURM_PARTITION_GPU` / `SLURM_PARTITION_CPU`. The `#SBATCH --partition` defaults here are +`vram48` (GPU) / `defq` (CPU); override per submit with `sbatch -p …`. Gated models +(MedGemma) read `HF_TOKEN` from `.env` (see `.env.example`). + +## Env knobs (summary) + +| Job | Knobs | +|-----|-------| +| `build_dataset.sub` | `VLM_SET` · `PROFILE` · `EVAL_DIR` · synthetic: `VLM_MODES`, `OUT_BASE` · real: `VLM_DATASETS`, `VLM_MAX`, `DATA_BASE` | +| `run_vlm.sub` | `MODEL` · `EVAL_DIR` · `CASE_IDS` · `CONDITIONS` | +| `analyze.sub` | `RESULTS` · `SPLIT` · `OUT` · `NBOOT` | + +See [docs/vlm_eval.md](../../../docs/vlm_eval.md) for the full guide and +[docs/vlm_eval_implementation.md](../../../docs/vlm_eval_implementation.md) for the architecture. diff --git a/itrialspace/infra/slurm/vlm_eval/analyze.sub b/itrialspace/infra/slurm/vlm_eval/analyze.sub new file mode 100644 index 0000000000000000000000000000000000000000..86878249e45beb9c546ba3073db0c10321d168b6 --- /dev/null +++ b/itrialspace/infra/slurm/vlm_eval/analyze.sub @@ -0,0 +1,56 @@ +#!/usr/bin/env bash +#SBATCH --job-name=vlm_analyze +#SBATCH --partition=defq +#SBATCH --ntasks=1 +#SBATCH --cpus-per-task=4 +#SBATCH --mem=24G +#SBATCH --time=2:00:00 +#SBATCH --output=logs/vlm_analyze-%j.out +#SBATCH --error=logs/vlm_analyze-%j.err + +# =========================================================================== +# STEP 3/3 — Analyse results: accuracy, Δ-vs-plain, breakdowns, confusion, +# bootstrap CIs, McNemar significance, publication figures, and report.md. +# CPU-only. Runs the eval_analysis engine (auto-discovers what's present). +# +# Env knobs: +# RESULTS result root to analyse +# (default: $ITRIALSPACE_OUTPUT_DIR/vlm_eval_demo — the demo) +# SPLIT split name under /splits or a file path; "" = all cases +# (default: "" for the demo; use release_v1_full on the full dataset) +# OUT output dir (default: /eval_analysis) +# NBOOT bootstrap resamples (default: 1000; 0 to skip) +# +# DEMO: sbatch infra/slurm/vlm_eval/analyze.sub +# FULL: RESULTS=$ITRIALSPACE_DATA_DIR/vlm_dataset SPLIT=release_v1_full \ +# sbatch infra/slurm/vlm_eval/analyze.sub +# =========================================================================== + +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" +itrialspace_activate_conda +set -uo pipefail + +RESULTS="${RESULTS:-${ITRIALSPACE_OUTPUT_DIR}/vlm_eval_demo}" +SPLIT="${SPLIT-}" # default empty = all cases (note: '-' not ':-') +NBOOT="${NBOOT:-1000}" +OUT="${OUT:-${RESULTS}/eval_analysis}" + +cd "${PROJ_DIR}" +mkdir -p logs + +echo "=== analyse — results=${RESULTS} split=${SPLIT:-} out=${OUT} ===" + +SPLIT_ARG=() +[ -n "${SPLIT}" ] && SPLIT_ARG=(--split "${SPLIT}") + +python -m itrialspace.evaluation.vlm_eval.eval_analysis \ + --results "${RESULTS}" \ + "${SPLIT_ARG[@]}" \ + --out "${OUT}" \ + --n-boot "${NBOOT}" +rc=$? + +if [ "${rc}" -ne 0 ]; then + echo "[$(date +%T)] FAILED (exit ${rc}). See the .err log."; exit "${rc}" +fi +echo "[$(date +%T)] Done. Report: ${OUT}/report.md" diff --git a/itrialspace/infra/slurm/vlm_eval/build_dataset.sub b/itrialspace/infra/slurm/vlm_eval/build_dataset.sub new file mode 100644 index 0000000000000000000000000000000000000000..a3ae0bf129124fe0543c6dd5fda75bb9da8a8c72 --- /dev/null +++ b/itrialspace/infra/slurm/vlm_eval/build_dataset.sub @@ -0,0 +1,104 @@ +#!/usr/bin/env bash +#SBATCH --job-name=vlm_build +#SBATCH --partition=defq +#SBATCH --ntasks=1 +#SBATCH --cpus-per-task=8 +#SBATCH --mem=32G +#SBATCH --time=8:00:00 +#SBATCH --output=logs/vlm_build-%j.out +#SBATCH --error=logs/vlm_build-%j.err + +# =========================================================================== +# STEP 1/3 — Build a VLM eval dataset (2-D slices + overlays + ground truth). +# CPU-only. Writes /{eval_dataset.csv, slices/…}. +# +# Env knobs (all optional — defaults = the small DEMO): +# VLM_SET synthetic | real (default: synthetic) +# PROFILE lung_axial | lung_axial_medgemma (default: lung_axial) +# → BiomedCLIP/LLaVA-Med use lung_axial; MedGemma uses lung_axial_medgemma. +# Build BOTH profiles to evaluate all three models. +# EVAL_DIR output dir (default: $ITRIALSPACE_OUTPUT_DIR/vlm_eval_demo[_real]/$PROFILE) +# synthetic: VLM_MODES trial modes to include (default "1 2 3"; full: "1 2 … 13") +# OUT_BASE holds generated_cts/manifests/inserted_masks +# (default $ITRIALSPACE_OUTPUT_DIR) +# real: VLM_DATASETS (default "DLCS24 LUNA25"; full: all 7) +# VLM_MAX max cases/dataset (default 40; set "" for ALL = full) +# DATA_BASE holds raw_ct/ profiles/ masks/ (default $ITRIALSPACE_DATA_DIR) +# +# DEMO (default): sbatch infra/slurm/vlm_eval/build_dataset.sub +# DEMO real: VLM_SET=real sbatch infra/slurm/vlm_eval/build_dataset.sub +# MedGemma profile: PROFILE=lung_axial_medgemma sbatch … (repeat for real) +# FULL synthetic: VLM_MODES="1 2 3 4 5 6 7 8 9 10 11 12 13" \ +# EVAL_DIR=$ITRIALSPACE_DATA_DIR/vlm_dataset/synthetic/lung_axial \ +# sbatch infra/slurm/vlm_eval/build_dataset.sub +# FULL real: VLM_SET=real VLM_DATASETS="DLCS24 LUNA25 LUNA16 LUNGx LNDbv4 NSCLCR IMDCT" \ +# VLM_MAX="" EVAL_DIR=$ITRIALSPACE_DATA_DIR/vlm_dataset/real/lung_axial \ +# sbatch infra/slurm/vlm_eval/build_dataset.sub +# (The released dataset already ships these built — see docs/vlm_eval.md.) +# =========================================================================== + +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" +itrialspace_activate_conda +set -uo pipefail + +VLM_SET="${VLM_SET:-synthetic}" +PROFILE="${PROFILE:-lung_axial}" +OUT_BASE="${OUT_BASE:-${ITRIALSPACE_OUTPUT_DIR}}" +DATA_BASE="${DATA_BASE:-${ITRIALSPACE_DATA_DIR}}" + +cd "${PROJ_DIR}" +mkdir -p logs + +if [ "${VLM_SET}" = "synthetic" ]; then + MODES="${VLM_MODES:-1 2 3}" + EVAL_DIR="${EVAL_DIR:-${OUT_BASE}/vlm_eval_demo/${PROFILE}}" + mkdir -p "${EVAL_DIR}" + echo "=== build (synthetic) — modes [${MODES}], profile ${PROFILE} → ${EVAL_DIR} ===" + + MANIFESTS=() + for m in ${MODES}; do + while IFS= read -r f; do MANIFESTS+=("$f"); done \ + < <(find "${OUT_BASE}/manifests/mode${m}_"* -name '*.csv' 2>/dev/null) + done + if [ "${#MANIFESTS[@]}" -eq 0 ]; then + echo "ERROR: no manifests for modes [${MODES}] under ${OUT_BASE}/manifests."; exit 1 + fi + echo " manifests: ${#MANIFESTS[@]}" + + python -m itrialspace.evaluation.vlm_eval.build_dataset \ + --manifest "${MANIFESTS[@]}" \ + --output-dir "${EVAL_DIR}" \ + --ct-base "${OUT_BASE}/generated_cts" \ + --mask-base "${OUT_BASE}/inserted_masks" \ + --profile "${PROFILE}" \ + --overlays \ + --workers 8 + +elif [ "${VLM_SET}" = "real" ]; then + DATASETS="${VLM_DATASETS:-DLCS24 LUNA25}" + EVAL_DIR="${EVAL_DIR:-${OUT_BASE}/vlm_eval_demo_real/${PROFILE}}" + mkdir -p "${EVAL_DIR}" + MAX_ARG=() + # VLM_MAX unset → demo 40; VLM_MAX="" → ALL cases (full run) + if [ -z "${VLM_MAX+x}" ]; then MAX_ARG=(--max-cases 40) + elif [ -n "${VLM_MAX}" ]; then MAX_ARG=(--max-cases "${VLM_MAX}"); fi + echo "=== build (real) — datasets [${DATASETS}], profile ${PROFILE} → ${EVAL_DIR} ===" + echo " data base: ${DATA_BASE} max: ${VLM_MAX-40}" + + python -m itrialspace.evaluation.vlm_eval.build_real_dataset \ + --data-base "${DATA_BASE}" \ + --output-dir "${EVAL_DIR}" \ + --datasets ${DATASETS} \ + --profile "${PROFILE}" \ + "${MAX_ARG[@]}" \ + --overlays +else + echo "ERROR: VLM_SET must be 'synthetic' or 'real' (got '${VLM_SET}')."; exit 1 +fi +rc=$? + +if [ "${rc}" -ne 0 ]; then + echo "[$(date +%T)] FAILED (exit ${rc}). See the .err log."; exit "${rc}" +fi +echo "[$(date +%T)] Done. Eval dataset: ${EVAL_DIR}/eval_dataset.csv" +echo "Next: MODEL=biomedclip EVAL_DIR=${EVAL_DIR} sbatch infra/slurm/vlm_eval/run_vlm.sub" diff --git a/itrialspace/infra/slurm/vlm_eval/run_vlm.sub b/itrialspace/infra/slurm/vlm_eval/run_vlm.sub new file mode 100644 index 0000000000000000000000000000000000000000..3da0a79dd74b80548ff310a4d5fc3669f455bac1 --- /dev/null +++ b/itrialspace/infra/slurm/vlm_eval/run_vlm.sub @@ -0,0 +1,84 @@ +#!/usr/bin/env bash +#SBATCH --job-name=vlm_run +#SBATCH --partition=vram48 +#SBATCH --ntasks=1 +#SBATCH --gpus=1 +#SBATCH --cpus-per-task=8 +#SBATCH --mem=32G +#SBATCH --time=24:00:00 +#SBATCH --output=logs/vlm_run-%j.out +#SBATCH --error=logs/vlm_run-%j.err + +# =========================================================================== +# STEP 2/3 — Run ONE VLM across all 4 conditions × 3 tasks on a built eval set. +# GPU. Writes ///_results.csv. +# +# Env knobs: +# MODEL biomedclip | llava_med | medgemma (default: biomedclip) +# EVAL_DIR dir holding eval_dataset.csv for this model's profile +# (default: $ITRIALSPACE_OUTPUT_DIR/vlm_eval_demo/) +# NOTE: MedGemma needs the lung_axial_medgemma eval set; BiomedCLIP +# and LLaVA-Med need lung_axial. Point EVAL_DIR at the matching profile. +# CASE_IDS optional frozen split file → score only those cases (--case-ids) +# CONDITIONS optional subset, e.g. "plain bbox" (default: all 4) +# +# Run all three models on the DEMO synthetic set: +# B=$ITRIALSPACE_OUTPUT_DIR/vlm_eval_demo +# MODEL=biomedclip EVAL_DIR=$B/lung_axial sbatch infra/slurm/vlm_eval/run_vlm.sub +# MODEL=llava_med EVAL_DIR=$B/lung_axial sbatch infra/slurm/vlm_eval/run_vlm.sub +# MODEL=medgemma EVAL_DIR=$B/lung_axial_medgemma sbatch infra/slurm/vlm_eval/run_vlm.sub +# +# Run on the FULL released dataset (synthetic) on a fixed split: +# B=$ITRIALSPACE_DATA_DIR/vlm_dataset/synthetic +# CASE_IDS=$ITRIALSPACE_DATA_DIR/vlm_dataset/splits/release_v1_full.synthetic.txt \ +# MODEL=biomedclip EVAL_DIR=$B/lung_axial sbatch infra/slurm/vlm_eval/run_vlm.sub +# =========================================================================== + +ITS_ENV="${SLURM_SUBMIT_DIR:-$PWD}"; while [ "$ITS_ENV" != "/" ] && [ ! -f "$ITS_ENV/infra/slurm/env.sh" ]; do ITS_ENV="$(dirname "$ITS_ENV")"; done; source "$ITS_ENV/infra/slurm/env.sh" +itrialspace_activate_conda +set -uo pipefail + +MODEL="${MODEL:-biomedclip}" +case "${MODEL}" in + biomedclip|llava_med) DEF_PROFILE="lung_axial" ;; + medgemma) DEF_PROFILE="lung_axial_medgemma" ;; + *) echo "ERROR: MODEL must be biomedclip|llava_med|medgemma (got '${MODEL}')."; exit 1 ;; +esac +EVAL_DIR="${EVAL_DIR:-${ITRIALSPACE_OUTPUT_DIR}/vlm_eval_demo/${DEF_PROFILE}}" +DATASET_CSV="${EVAL_DIR}/eval_dataset.csv" +OUTPUT_DIR="${EVAL_DIR}/${MODEL}" + +cd "${PROJ_DIR}" +mkdir -p logs + +if [ ! -f "${DATASET_CSV}" ]; then + echo "ERROR: ${DATASET_CSV} not found. Build it first (build_dataset.sub)."; exit 1 +fi + +# MedGemma (torch 2.6) needs the conda cuDNN 9 on LD_LIBRARY_PATH. +if [ "${MODEL}" = "medgemma" ]; then + export LD_LIBRARY_PATH="$(python -c 'import os,nvidia.cudnn;print(os.path.dirname(nvidia.cudnn.__file__)+"/lib")' 2>/dev/null):${LD_LIBRARY_PATH:-}" +fi + +EXTRA=() +[ -n "${CASE_IDS:-}" ] && EXTRA+=(--case-ids "${CASE_IDS}") +if [ -n "${CONDITIONS:-}" ]; then EXTRA+=(--image-condition ${CONDITIONS}); else EXTRA+=(--run-all-conditions); fi + +echo "=== run ${MODEL} — all conditions × {presence,lobe,size} ===" +echo " dataset : ${DATASET_CSV}" +echo " output : ${OUTPUT_DIR}" +echo " GPU : $(nvidia-smi --query-gpu=name --format=csv,noheader 2>/dev/null || echo N/A)" +[ -n "${CASE_IDS:-}" ] && echo " split : ${CASE_IDS}" + +python -m itrialspace.evaluation.vlm_eval.runners.run_conditions \ + --model "${MODEL}" \ + --dataset-csv "${DATASET_CSV}" \ + --output-dir "${OUTPUT_DIR}" \ + --tasks presence lobe size \ + "${EXTRA[@]}" +rc=$? + +if [ "${rc}" -ne 0 ]; then + echo "[$(date +%T)] FAILED (exit ${rc}). See the .err log."; exit "${rc}" +fi +echo "[$(date +%T)] Done. Results: ${OUTPUT_DIR}" diff --git a/itrialspace/nodmaisi_synth/models/Experiments_NoMAISI_512xy_256z_771p25m_finetune_500epoch_best.pt b/itrialspace/nodmaisi_synth/models/Experiments_NoMAISI_512xy_256z_771p25m_finetune_500epoch_best.pt new file mode 100644 index 0000000000000000000000000000000000000000..c5dfa7beb748dbacda8f7ca08f452dac2640c074 --- /dev/null +++ b/itrialspace/nodmaisi_synth/models/Experiments_NoMAISI_512xy_256z_771p25m_finetune_500epoch_best.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e11ebc532c433316a13d30e97ab72bff42ad9f1dd841d36e7181a6d83986c71c +size 288268713 diff --git a/itrialspace/nodmaisi_synth/models/autoencoder.pt b/itrialspace/nodmaisi_synth/models/autoencoder.pt new file mode 100644 index 0000000000000000000000000000000000000000..4956b34b62543d2ecac67f9350ff058e52fc7b3b --- /dev/null +++ b/itrialspace/nodmaisi_synth/models/autoencoder.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1f8a7a056d0ebc00486edc43c26768bf1c12eaa6df9dd172e34598003be95eb3 +size 83831868 diff --git a/itrialspace/nodmaisi_synth/models/diffusion_unet.pt b/itrialspace/nodmaisi_synth/models/diffusion_unet.pt new file mode 100644 index 0000000000000000000000000000000000000000..883c65af4c3cdcdb57c8c1ff93660e96dca53853 --- /dev/null +++ b/itrialspace/nodmaisi_synth/models/diffusion_unet.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cfc1ec59782f5ac7c0d22dd501654732109a971b93cbaa6607c4106a7f29066f +size 2166600232 diff --git a/itrialspace/pyproject.toml b/itrialspace/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..7977bfb32416c541e514a993c71784eba2a4c5b7 --- /dev/null +++ b/itrialspace/pyproject.toml @@ -0,0 +1,140 @@ +[build-system] +requires = ["setuptools>=68.0", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "itrialspace" +version = "0.1.0" +description = "iTrialSpace — Synthetic Imaging Clinical Trial Engine for lung CT AI evaluation" +readme = "README.md" +requires-python = ">=3.10" +# TODO: confirm license before public release (Apache-2.0 / MIT / BSD-3-Clause) +license = {text = "LicenseRef-TODO"} +authors = [{ name = "iTrialSpace contributors" }] +keywords = ["medical-imaging", "lung-ct", "synthetic-data", "clinical-trial", "VLM"] +classifiers = [ + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Intended Audience :: Science/Research", + "Topic :: Scientific/Engineering :: Medical Science Apps.", + "Operating System :: POSIX :: Linux", +] + +# Core dependencies — enough to build the nodule index, query, and plan trials. +dependencies = [ + "pandas>=1.5", + "numpy>=1.23", + "pyyaml>=6.0", +] + +[project.optional-dependencies] +# Mask insertion + NIfTI handling +imaging = ["nibabel>=5.0", "scipy>=1.10", "SimpleITK>=2.2"] + +# Interactive exploration apps: NoduleMap (FastAPI + sigma.js) and Retriever (FastAPI + Streamlit) +apps = [ + "fastapi>=0.104", + "uvicorn[standard]>=0.24", + "pydantic>=2.0", + "streamlit>=1.28", + "nibabel>=5.0", + "Pillow>=10.0", + "matplotlib>=3.5", + "requests>=2.28", + "scikit-learn>=1.2", + "umap-learn>=0.5", + "faiss-cpu>=1.7", + "pyarrow>=10.0", +] +# Backward-compatible alias for the previous name. +web = ["itrialspace[apps]"] + +# CT synthesis (NodMAISI). Heavy; torch/monai install is platform-specific — see docs/installation.md. +synthesis = [ + "monai>=1.3", + "nibabel>=5.0", + "scipy>=1.10", + "matplotlib>=3.5", + "scikit-image>=0.21", + "fire>=0.5", + "tqdm>=4.60", + "einops>=0.6", +] + +# Vision-Language Model evaluation. Model backends pulled separately — see docs/installation.md. +vlm = [ + "transformers>=4.40", + "accelerate>=0.26", + "open_clip_torch>=2.24", + "nibabel>=5.0", + "Pillow>=10.0", + "matplotlib>=3.5", + "seaborn>=0.12", +] + + +# Developer tooling +dev = [ + "pytest>=7.0", + "ruff>=0.4", + "black>=24.0", + "pre-commit>=3.5", +] + +all = [ + "itrialspace[imaging,apps,vlm,dev]", +] + +[project.scripts] +its = "itrialspace.cli:main" +its-insert = "itrialspace.mask_inserter.cli:main" +its-trials = "itrialspace.trials.run_trial:main" +its-nodulemap = "itrialspace.apps.nodulemap.cli.cli:main" +its-retriever = "itrialspace.apps.retriever.cli:main" + +[tool.setuptools.packages.find] +where = ["src"] +include = ["itrialspace*"] + +[tool.setuptools.package-data] +itrialspace = [ + "config/*.yaml", + "site/config/*.yaml", + "apps/nodulemap/configs/*.yaml", + "apps/nodulemap/frontend/static/*", + "synthesis/configs/*.json", +] + +[tool.ruff] +line-length = 100 +target-version = "py310" +extend-exclude = ["docs", "infra"] + +[tool.ruff.lint] +select = ["E", "F", "I", "W"] +ignore = [ + "E501", # line length handled by black + "E402", # module-level import not at top (needed for src-path bootstrap / lazy config) + "E741", # ambiguous variable names (research code uses l/I occasionally) + "E711", # `== None` — kept where pandas/None semantics are intentional + "E712", # `== True/False` — idiomatic in pandas boolean masks here + "F841", # unused locals — common in research code; not a correctness risk +] + +[tool.ruff.lint.per-file-ignores] +# __init__.py intentionally re-exports the public API. +"**/__init__.py" = ["F401"] +# Tests use fixtures/imports that linters misread as unused. +"tests/**" = ["F401", "F811", "E731"] +# Vendored MAISI inference code (run as scripts) — keep upstream style as-is. +"src/itrialspace/synthesis/scripts/**" = ["F401", "F403", "F405", "F841", "E711", "E712", "E721", "E722"] + +[tool.black] +line-length = 100 +target-version = ["py310", "py311"] + +[tool.pytest.ini_options] +markers = [ + "full_volume: tests that require real CT data (env-gated, skipped in CI)", +] +testpaths = ["tests"] diff --git a/itrialspace/requirements.lock.txt b/itrialspace/requirements.lock.txt new file mode 100644 index 0000000000000000000000000000000000000000..cded37e207297d2a535a378f6b72b142c090943c --- /dev/null +++ b/itrialspace/requirements.lock.txt @@ -0,0 +1,149 @@ +# Reproducible lock — exact freeze of the verified iTrialSpace environment. +# Python 3.10, linux-64, CUDA 12.1. Generated 2026-06-04. +# python3.10 -m venv .venv && . .venv/bin/activate +# pip install -r requirements.lock.txt && pip install -e . +# torch = cu121 build; MONAI = git-pinned dev commit. Full pipeline (incl. GPU +# synthesis) verified across modes 1-10 in this env. +--extra-index-url https://download.pytorch.org/whl/cu121 + +altair==6.1.0 +annotated-doc==0.0.4 +annotated-types==0.7.0 +anyio==4.13.0 +attrs==26.1.0 +black==26.5.1 +blinker==1.9.0 +cachetools==7.1.4 +certifi==2026.5.20 +cfgv==3.5.0 +charset-normalizer==3.4.7 +click==8.4.1 +contourpy==1.3.2 +cuda-bindings==13.3.1 +cuda-pathfinder==1.5.5 +cuda-toolkit==13.0.2 +cycler==0.12.1 +distlib==0.4.1 +einops==0.8.2 +exceptiongroup==1.3.1 +faiss-cpu==1.14.2 +fastapi==0.136.3 +filelock==3.29.0 +fire==0.7.1 +fonttools==4.63.0 +fsspec==2026.4.0 +ftfy==6.3.1 +gitdb==4.0.12 +GitPython==3.1.50 +h11==0.16.0 +hf-xet==1.5.0 +httpcore==1.0.9 +httptools==0.8.0 +httpx==0.28.1 +huggingface_hub==0.36.2 +identify==2.6.19 +idna==3.18 +ImageIO==2.37.3 +importlib_resources==7.1.0 +iniconfig==2.3.0 +itsdangerous==2.2.0 +Jinja2==3.1.6 +joblib==1.5.3 +jsonschema-specifications==2025.9.1 +jsonschema==4.26.0 +kiwisolver==1.5.0 +lazy-loader==0.5 +llvmlite==0.47.0 +markdown-it-py==4.2.0 +MarkupSafe==3.0.3 +matplotlib==3.10.9 +mdurl==0.1.2 +monai @ git+https://github.com/Project-MONAI/MONAI.git@c3a317d2bcb486199f40bda0d722a41e3869712a +mpmath==1.3.0 +mypy_extensions==1.1.0 +narwhals==2.22.0 +networkx==3.4.2 +nibabel==5.4.2 +nodeenv==1.10.0 +numba==0.65.1 +numpy==1.26.4 +nvidia-cublas-cu12==12.1.3.1 +nvidia-cuda-cupti-cu12==12.1.105 +nvidia-cuda-nvrtc-cu12==12.1.105 +nvidia-cuda-runtime-cu12==12.1.105 +nvidia-cudnn-cu12==9.1.0.70 +nvidia-cufft-cu12==11.0.2.54 +nvidia-curand-cu12==10.3.2.106 +nvidia-cusolver-cu12==11.4.5.107 +nvidia-cusparse-cu12==12.1.0.106 +nvidia-nccl-cu12==2.20.5 +nvidia-nvjitlink-cu12==12.1.105 +nvidia-nvtx-cu12==12.1.105 +open_clip_torch==2.32.0 +packaging==26.0 +pandas==2.3.3 +pathspec==1.1.1 +pillow==12.2.0 +platformdirs==4.10.0 +pluggy==1.6.0 +pre_commit==4.6.0 +protobuf==6.33.6 +pyarrow==24.0.0 +pydantic==2.13.4 +pydantic_core==2.46.4 +pydeck==0.9.2 +Pygments==2.20.0 +pynndescent==0.6.0 +pyparsing==3.3.2 +pytest==9.0.3 +python-dateutil==2.9.0.post0 +python-discovery==1.4.0 +python-dotenv==1.2.2 +python-multipart==0.0.30 +pytokens==0.4.1 +pytz==2026.2 +PyYAML==6.0.3 +referencing==0.37.0 +regex==2026.5.9 +requests==2.34.2 +rich==15.0.0 +rpds-py==0.30.0 +ruff==0.15.15 +safetensors==0.7.0 +scikit-image==0.25.2 +scikit-learn==1.7.2 +scipy==1.15.3 +seaborn==0.13.2 +shellingham==1.5.4 +simpleitk==2.5.5 +six==1.17.0 +smmap==5.0.3 +starlette==1.2.1 +streamlit==1.58.0 +sympy==1.14.0 +tenacity==9.1.4 +termcolor==3.3.0 +threadpoolctl==3.6.0 +tifffile==2025.5.10 +timm==1.0.27 +tokenizers==0.21.4 +toml==0.10.2 +tomli==2.4.1 +torch==2.4.1+cu121 +torchvision==0.19.1+cu121 +tqdm==4.67.3 +transformers==4.51.3 +triton==3.0.0 +typer==0.25.1 +typing-inspection==0.4.2 +typing_extensions==4.15.0 +tzdata==2026.2 +umap-learn==0.5.12 +urllib3==2.7.0 +uvicorn==0.49.0 +uvloop==0.22.1 +virtualenv==21.4.2 +watchdog==6.0.0 +watchfiles==1.2.0 +wcwidth==0.7.0 +websockets==16.0 diff --git a/itrialspace/src/itrialspace.egg-info/PKG-INFO b/itrialspace/src/itrialspace.egg-info/PKG-INFO new file mode 100644 index 0000000000000000000000000000000000000000..5dc26fdd06f4cdd4685bc2e8ee3953f6370f9c06 --- /dev/null +++ b/itrialspace/src/itrialspace.egg-info/PKG-INFO @@ -0,0 +1,168 @@ +Metadata-Version: 2.4 +Name: itrialspace +Version: 0.1.0 +Summary: iTrialSpace — Synthetic Imaging Clinical Trial Engine for lung CT AI evaluation +Author: iTrialSpace contributors +License: LicenseRef-TODO +Keywords: medical-imaging,lung-ct,synthetic-data,clinical-trial,CADe,CADx,VLM +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Intended Audience :: Science/Research +Classifier: Topic :: Scientific/Engineering :: Medical Science Apps. +Classifier: Operating System :: POSIX :: Linux +Requires-Python: >=3.10 +Description-Content-Type: text/markdown +License-File: LICENSE +Requires-Dist: pandas>=1.5 +Requires-Dist: numpy>=1.23 +Requires-Dist: pyyaml>=6.0 +Provides-Extra: imaging +Requires-Dist: nibabel>=5.0; extra == "imaging" +Requires-Dist: scipy>=1.10; extra == "imaging" +Requires-Dist: SimpleITK>=2.2; extra == "imaging" +Provides-Extra: apps +Requires-Dist: fastapi>=0.104; extra == "apps" +Requires-Dist: uvicorn[standard]>=0.24; extra == "apps" +Requires-Dist: pydantic>=2.0; extra == "apps" +Requires-Dist: streamlit>=1.28; extra == "apps" +Requires-Dist: nibabel>=5.0; extra == "apps" +Requires-Dist: Pillow>=10.0; extra == "apps" +Requires-Dist: matplotlib>=3.5; extra == "apps" +Requires-Dist: requests>=2.28; extra == "apps" +Requires-Dist: scikit-learn>=1.2; extra == "apps" +Requires-Dist: umap-learn>=0.5; extra == "apps" +Requires-Dist: faiss-cpu>=1.7; extra == "apps" +Requires-Dist: pyarrow>=10.0; extra == "apps" +Provides-Extra: web +Requires-Dist: itrialspace[apps]; extra == "web" +Provides-Extra: synthesis +Requires-Dist: monai>=1.3; extra == "synthesis" +Requires-Dist: nibabel>=5.0; extra == "synthesis" +Requires-Dist: scipy>=1.10; extra == "synthesis" +Requires-Dist: matplotlib>=3.5; extra == "synthesis" +Requires-Dist: scikit-image>=0.21; extra == "synthesis" +Requires-Dist: fire>=0.5; extra == "synthesis" +Requires-Dist: tqdm>=4.60; extra == "synthesis" +Requires-Dist: einops>=0.6; extra == "synthesis" +Provides-Extra: vlm +Requires-Dist: transformers>=4.40; extra == "vlm" +Requires-Dist: open_clip_torch>=2.24; extra == "vlm" +Requires-Dist: nibabel>=5.0; extra == "vlm" +Requires-Dist: Pillow>=10.0; extra == "vlm" +Requires-Dist: matplotlib>=3.5; extra == "vlm" +Requires-Dist: seaborn>=0.12; extra == "vlm" +Provides-Extra: eval +Requires-Dist: monai>=1.3; extra == "eval" +Requires-Dist: nibabel>=5.0; extra == "eval" +Requires-Dist: scipy>=1.10; extra == "eval" +Requires-Dist: scikit-learn>=1.2; extra == "eval" +Provides-Extra: dev +Requires-Dist: pytest>=7.0; extra == "dev" +Requires-Dist: ruff>=0.4; extra == "dev" +Requires-Dist: black>=24.0; extra == "dev" +Requires-Dist: pre-commit>=3.5; extra == "dev" +Provides-Extra: all +Requires-Dist: itrialspace[apps,dev,imaging,vlm]; extra == "all" +Dynamic: license-file + +# iTrialSpace + +**Synthetic Imaging Clinical Trial Engine for lung CT AI evaluation.** + +> ⚠️ License is not yet finalized — see [`LICENSE`](LICENSE). Do not redistribute until confirmed. + +iTrialSpace turns medical-imaging AI evaluation from *"find more data"* into *"specify the +data you need."* It harmonizes **13,140 nodule profiles** from **7 public lung CT datasets**, +generates virtual clinical-trial cohorts across **13 trial modes**, inserts donor nodule masks +into real host anatomy, synthesizes CT volumes with a ControlNet-conditioned rectified-flow +diffusion model (**NodMAISI**), and evaluates **CADe/CADx** detectors and **vision-language +models** under systematically controlled conditions. + +## Why + +Public lung-screening datasets are narrow (NLST = heavy smokers, LUNA16 has no malignancy +labels, NSCLC-Radiomics = only large cancers), so AI models get tested on data that +under-represents where they fail. iTrialSpace lets you declare a cohort by its *statistical +properties* (prevalence, size distribution, lobe distribution, demographics) and manufactures +anatomically grounded synthetic CTs to match — enabling controlled, one-variable-at-a-time +experiments impossible with fixed retrospective datasets. + +## Architecture + +``` +itrialspace → trials → mask_inserter → synthesis → evaluation +(nodule index) (manifests) (mask paste) (NodMAISI CT) (CADe/CADx/VLM) + │ + ├─ nodulemap (graph viz) + └─ retriever (faceted search) +``` + +See [docs/architecture.md](docs/architecture.md) for the full component map. + +## Quickstart + +```bash +# 1. Environment +conda env create -f environment.yml && conda activate itrialspace + +# 2. Install (pick the extras you need — see Install matrix below) +pip install -e ".[imaging,web]" + +# 3. Configure paths +cp .env.example .env # edit ITRIALSPACE_DATA_DIR etc. + +# 4. Run unit tests (no external data required) +pytest -m "not full_volume" + +# 5. Build the nodule index and print stats (requires profile CSVs — see docs/data.md) +its index stats +``` + +## Install matrix + +| Extra | Installs | For | +|-------|----------|-----| +| *(base)* | pandas, numpy, pyyaml | Index, query, trial planning | +| `imaging` | nibabel, scipy, SimpleITK | Mask insertion, NIfTI handling | +| `web` | fastapi, streamlit, faiss, umap | NoduleMap + Retriever UIs | +| `synthesis` | monai, (torch) | NodMAISI CT synthesis* | +| `vlm` | transformers, open_clip | VLM evaluation* | +| `eval` | monai, scikit-learn | CADe/CADx evaluation** | +| `dev` | pytest, ruff, black, pre-commit | Development | +| `all` | imaging + web + vlm + dev | Everything bundled | + +\* torch is platform-specific — see [docs/installation.md](docs/installation.md). +\*\* also needs **external** models/repos — see [docs/evaluation_external_dependencies.md](docs/evaluation_external_dependencies.md). + +## Console commands + +| Command | Does | +|---------|------| +| `its` | Umbrella CLI (index, query, info) | +| `its-insert` | Insert nodule masks from a cohort manifest | +| `its-trials` | Generate cohort manifests for the 13 trial modes | +| `its-nodulemap` | Launch the NoduleMap graph-visualization server | +| `its-retriever` | Launch the Retriever search API + UI | + +## Documentation + +- [Installation](docs/installation.md) · [Quickstart](docs/quickstart.md) · [Configuration](docs/configuration.md) +- [Architecture](docs/architecture.md) · [Pipeline](docs/pipeline.md) · [Trial modes](docs/trial_modes.md) +- [Data preparation](docs/data.md) · [Reproducibility](docs/reproducibility.md) +- [SKILL.md](SKILL.md) — exhaustive machine-readable reference for AI coding assistants + +## Data & models + +This repository contains **code only**. Source CT datasets and trained model weights are +**not** redistributed here (they carry their own licenses and are large). See +[docs/data.md](docs/data.md) and [docs/installation.md](docs/installation.md) for how to obtain +and lay them out. + +## Citation + +See [CITATION.cff](CITATION.cff). + +## Contributing + +See [CONTRIBUTING.md](CONTRIBUTING.md). All contributions run through CI (lint + tests + +portability gate). diff --git a/itrialspace/src/itrialspace.egg-info/SOURCES.txt b/itrialspace/src/itrialspace.egg-info/SOURCES.txt new file mode 100644 index 0000000000000000000000000000000000000000..ec60619fa428258f4619f566e28bdde5674f0504 --- /dev/null +++ b/itrialspace/src/itrialspace.egg-info/SOURCES.txt @@ -0,0 +1,156 @@ +LICENSE +README.md +pyproject.toml +src/itrialspace/__init__.py +src/itrialspace/cli.py +src/itrialspace.egg-info/PKG-INFO +src/itrialspace.egg-info/SOURCES.txt +src/itrialspace.egg-info/dependency_links.txt +src/itrialspace.egg-info/entry_points.txt +src/itrialspace.egg-info/requires.txt +src/itrialspace.egg-info/top_level.txt +src/itrialspace/apps/__init__.py +src/itrialspace/apps/nodulemap/__init__.py +src/itrialspace/apps/nodulemap/__main__.py +src/itrialspace/apps/nodulemap/backend/__init__.py +src/itrialspace/apps/nodulemap/backend/app.py +src/itrialspace/apps/nodulemap/backend/data_store.py +src/itrialspace/apps/nodulemap/backend/export.py +src/itrialspace/apps/nodulemap/cli/__init__.py +src/itrialspace/apps/nodulemap/cli/cli.py +src/itrialspace/apps/nodulemap/client/__init__.py +src/itrialspace/apps/nodulemap/client/notebook_client.py +src/itrialspace/apps/nodulemap/configs/features.yaml +src/itrialspace/apps/nodulemap/embeddings/__init__.py +src/itrialspace/apps/nodulemap/embeddings/build_embeddings.py +src/itrialspace/apps/nodulemap/frontend/__init__.py +src/itrialspace/apps/nodulemap/frontend/static/index.html +src/itrialspace/apps/nodulemap/neighbors/__init__.py +src/itrialspace/apps/nodulemap/neighbors/build_edges.py +src/itrialspace/apps/nodulemap/tools/__init__.py +src/itrialspace/apps/nodulemap/tools/rebuild_artifacts.py +src/itrialspace/apps/nodulemap/tools/verify_purge.py +src/itrialspace/apps/retriever/__init__.py +src/itrialspace/apps/retriever/__main__.py +src/itrialspace/apps/retriever/cli.py +src/itrialspace/apps/retriever/engine.py +src/itrialspace/apps/retriever/notebook.py +src/itrialspace/apps/retriever/search.py +src/itrialspace/apps/retriever/similarity.py +src/itrialspace/apps/retriever/slicer.py +src/itrialspace/apps/retriever/api/__init__.py +src/itrialspace/apps/retriever/api/app.py +src/itrialspace/apps/retriever/api/models.py +src/itrialspace/apps/retriever/ui/__init__.py +src/itrialspace/apps/retriever/ui/app.py +src/itrialspace/config/__init__.py +src/itrialspace/config/datasets.yaml +src/itrialspace/config/settings.py +src/itrialspace/core/__init__.py +src/itrialspace/core/label.py +src/itrialspace/core/profile.py +src/itrialspace/core/schema.py +src/itrialspace/evaluation/__init__.py +src/itrialspace/evaluation/cade/__init__.py +src/itrialspace/evaluation/cade/chunk_csv.py +src/itrialspace/evaluation/cade/inference_CADe_at_locations.py +src/itrialspace/evaluation/cadx/__init__.py +src/itrialspace/evaluation/cadx/build_synthetic_candidate_csv.py +src/itrialspace/evaluation/cadx/check_csv.py +src/itrialspace/evaluation/vlm_eval/__init__.py +src/itrialspace/evaluation/vlm_eval/biomedclip_model.py +src/itrialspace/evaluation/vlm_eval/build_dataset.py +src/itrialspace/evaluation/vlm_eval/build_negative_dataset.py +src/itrialspace/evaluation/vlm_eval/build_real_dataset.py +src/itrialspace/evaluation/vlm_eval/comparison.py +src/itrialspace/evaluation/vlm_eval/cross_model_comparison.py +src/itrialspace/evaluation/vlm_eval/inference_cache.py +src/itrialspace/evaluation/vlm_eval/metrics.py +src/itrialspace/evaluation/vlm_eval/overlay.py +src/itrialspace/evaluation/vlm_eval/parsers.py +src/itrialspace/evaluation/vlm_eval/plots.py +src/itrialspace/evaluation/vlm_eval/preprocess_profiles.py +src/itrialspace/evaluation/vlm_eval/prompt_templates.py +src/itrialspace/evaluation/vlm_eval/run_all.py +src/itrialspace/evaluation/vlm_eval/run_biomedclip.py +src/itrialspace/evaluation/vlm_eval/slice_extractor.py +src/itrialspace/evaluation/vlm_eval/models/__init__.py +src/itrialspace/evaluation/vlm_eval/models/llava_med.py +src/itrialspace/evaluation/vlm_eval/models/medgemma.py +src/itrialspace/evaluation/vlm_eval/runners/__init__.py +src/itrialspace/evaluation/vlm_eval/runners/run_conditions.py +src/itrialspace/evaluation/vlm_eval/runners/run_llava_med.py +src/itrialspace/evaluation/vlm_eval/runners/run_medgemma.py +src/itrialspace/index/__init__.py +src/itrialspace/index/nodule_index.py +src/itrialspace/io/__init__.py +src/itrialspace/io/loader.py +src/itrialspace/io/registry.py +src/itrialspace/io/adapters/__init__.py +src/itrialspace/io/adapters/adapters.py +src/itrialspace/mask_inserter/__init__.py +src/itrialspace/mask_inserter/__main__.py +src/itrialspace/mask_inserter/cli.py +src/itrialspace/mask_inserter/inserter.py +src/itrialspace/mask_inserter/placement.py +src/itrialspace/mask_inserter/resample.py +src/itrialspace/mask_inserter/resolver_bridge.py +src/itrialspace/mask_inserter/tools/__init__.py +src/itrialspace/mask_inserter/tools/list_manifests.py +src/itrialspace/mask_inserter/tools/make_test_manifest.py +src/itrialspace/query/__init__.py +src/itrialspace/query/matcher.py +src/itrialspace/query/query_api.py +src/itrialspace/site/__init__.py +src/itrialspace/site/cohort_builder.py +src/itrialspace/site/insertion_planner.py +src/itrialspace/site/knowledge_base.py +src/itrialspace/site/manifest.py +src/itrialspace/site/path_resolver.py +src/itrialspace/site/sampling.py +src/itrialspace/site/spec.py +src/itrialspace/site/trial_modes.py +src/itrialspace/site/validation.py +src/itrialspace/site/config/paths.yaml +src/itrialspace/site/config/trials.yaml +src/itrialspace/synthesis/__init__.py +src/itrialspace/synthesis/configs/config_maisi3d-rflow.json +src/itrialspace/synthesis/configs/infr_config_NoMAISI_controlnet.json +src/itrialspace/synthesis/configs/infr_env_NoMAISI_DLCSD24_demo.json +src/itrialspace/synthesis/scripts/__init__.py +src/itrialspace/synthesis/scripts/augmentation.py +src/itrialspace/synthesis/scripts/compute_fid_2-5d_ct.py +src/itrialspace/synthesis/scripts/diff_model_create_training_data.py +src/itrialspace/synthesis/scripts/diff_model_infer.py +src/itrialspace/synthesis/scripts/diff_model_setting.py +src/itrialspace/synthesis/scripts/diff_model_train.py +src/itrialspace/synthesis/scripts/find_masks.py +src/itrialspace/synthesis/scripts/infer_controlnet.py +src/itrialspace/synthesis/scripts/infer_testV2_controlnet.py +src/itrialspace/synthesis/scripts/infer_test_controlnet.py +src/itrialspace/synthesis/scripts/inference.py +src/itrialspace/synthesis/scripts/quality_check.py +src/itrialspace/synthesis/scripts/rectified_flow.py +src/itrialspace/synthesis/scripts/sample.py +src/itrialspace/synthesis/scripts/scheduler.py +src/itrialspace/synthesis/scripts/train_controlnet.py +src/itrialspace/synthesis/scripts/transforms.py +src/itrialspace/synthesis/scripts/utils.py +src/itrialspace/synthesis/scripts/utils_plot.py +src/itrialspace/synthesis/scripts/schedulers/__init__.py +src/itrialspace/synthesis/scripts/schedulers/ddim.py +src/itrialspace/synthesis/scripts/schedulers/ddpm.py +src/itrialspace/synthesis/scripts/schedulers/pndm.py +src/itrialspace/synthesis/scripts/schedulers/rectified_flow.py +src/itrialspace/synthesis/scripts/schedulers/scheduler.py +src/itrialspace/synthesis/tools/__init__.py +src/itrialspace/synthesis/tools/run_itrialspace_to_ct.py +src/itrialspace/trials/__init__.py +src/itrialspace/trials/run_trial.py +src/itrialspace/utils/__init__.py +tests/test_digital_twin_complete.py +tests/test_digital_twin_cross.py +tests/test_digital_twin_isolation.py +tests/test_itrialspace.py +tests/test_p0_fixes.py +tests/test_site.py \ No newline at end of file diff --git a/itrialspace/src/itrialspace.egg-info/dependency_links.txt b/itrialspace/src/itrialspace.egg-info/dependency_links.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/itrialspace/src/itrialspace.egg-info/dependency_links.txt @@ -0,0 +1 @@ + diff --git a/itrialspace/src/itrialspace.egg-info/entry_points.txt b/itrialspace/src/itrialspace.egg-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..19509a3bf1ecad34d3ffbb2e8b76bcc7960343d3 --- /dev/null +++ b/itrialspace/src/itrialspace.egg-info/entry_points.txt @@ -0,0 +1,6 @@ +[console_scripts] +its = itrialspace.cli:main +its-insert = itrialspace.mask_inserter.cli:main +its-nodulemap = itrialspace.apps.nodulemap.cli.cli:main +its-retriever = itrialspace.apps.retriever.cli:main +its-trials = itrialspace.trials.run_trial:main diff --git a/itrialspace/src/itrialspace.egg-info/requires.txt b/itrialspace/src/itrialspace.egg-info/requires.txt new file mode 100644 index 0000000000000000000000000000000000000000..b856850c7d460540e5d27572b9b42aa2363ff6a9 --- /dev/null +++ b/itrialspace/src/itrialspace.egg-info/requires.txt @@ -0,0 +1,58 @@ +pandas>=1.5 +numpy>=1.23 +pyyaml>=6.0 + +[all] +itrialspace[apps,dev,imaging,vlm] + +[apps] +fastapi>=0.104 +uvicorn[standard]>=0.24 +pydantic>=2.0 +streamlit>=1.28 +nibabel>=5.0 +Pillow>=10.0 +matplotlib>=3.5 +requests>=2.28 +scikit-learn>=1.2 +umap-learn>=0.5 +faiss-cpu>=1.7 +pyarrow>=10.0 + +[dev] +pytest>=7.0 +ruff>=0.4 +black>=24.0 +pre-commit>=3.5 + +[eval] +monai>=1.3 +nibabel>=5.0 +scipy>=1.10 +scikit-learn>=1.2 + +[imaging] +nibabel>=5.0 +scipy>=1.10 +SimpleITK>=2.2 + +[synthesis] +monai>=1.3 +nibabel>=5.0 +scipy>=1.10 +matplotlib>=3.5 +scikit-image>=0.21 +fire>=0.5 +tqdm>=4.60 +einops>=0.6 + +[vlm] +transformers>=4.40 +open_clip_torch>=2.24 +nibabel>=5.0 +Pillow>=10.0 +matplotlib>=3.5 +seaborn>=0.12 + +[web] +itrialspace[apps] diff --git a/itrialspace/src/itrialspace.egg-info/top_level.txt b/itrialspace/src/itrialspace.egg-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..daa1bfff281e4b4d0f8d0d3519947972dcf0cbe2 --- /dev/null +++ b/itrialspace/src/itrialspace.egg-info/top_level.txt @@ -0,0 +1 @@ +itrialspace diff --git a/itrialspace/src/itrialspace/__init__.py b/itrialspace/src/itrialspace/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..73b34583d2f9bce8b25e4350462944a9566180df --- /dev/null +++ b/itrialspace/src/itrialspace/__init__.py @@ -0,0 +1,21 @@ +__version__ = "0.1.0" +from itrialspace.core.label import LabelNormaliser +from itrialspace.core.profile import NoduleProfile +from itrialspace.core.schema import ( + CORE_COLS, + DATASET_FLAGS, + DATASET_NAMES, + LOBE_NAMES, + REINSERTION_COLS, + SIDE_NAMES, + ZONE_NAMES, + CentralPeripheral, + Lobe, + Side, + Zone, +) +from itrialspace.index.nodule_index import NoduleIndex +from itrialspace.io.loader import DatasetLoader +from itrialspace.io.registry import DatasetRegistry +from itrialspace.query.matcher import MatchResult, ReinsertionMatcher, ReinsertionTarget +from itrialspace.query.query_api import NoduleQuery diff --git a/itrialspace/src/itrialspace/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..349ad9d9369df37ef920d5b2d7d2a52bad534a7e Binary files /dev/null and b/itrialspace/src/itrialspace/__pycache__/__init__.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/__pycache__/cli.cpython-310.pyc b/itrialspace/src/itrialspace/__pycache__/cli.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7fabeba0a372bf641a423485bcaf308a2a305227 Binary files /dev/null and b/itrialspace/src/itrialspace/__pycache__/cli.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/apps/__init__.py b/itrialspace/src/itrialspace/apps/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a299eed667856f58627e70aed6255396d3b24e2d --- /dev/null +++ b/itrialspace/src/itrialspace/apps/__init__.py @@ -0,0 +1,7 @@ +"""Interactive exploration tools layered on the iTrialSpace core. + +These are optional applications (not part of the generative engine): NoduleMap +(embedding graph visualization) and Retriever (faceted search). They depend on the +core (`itrialspace.core`/`index`/`query`); the core never depends on them. +Install with: ``pip install -e ".[apps]"``. +""" diff --git a/itrialspace/src/itrialspace/apps/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/apps/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bf8c331ebce9f9d92ecaa1d0732cb3e61ac1a344 Binary files /dev/null and b/itrialspace/src/itrialspace/apps/__pycache__/__init__.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/apps/nodulemap/__init__.py b/itrialspace/src/itrialspace/apps/nodulemap/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a12b94c984c2831416725a823a54fe8c84e7de78 --- /dev/null +++ b/itrialspace/src/itrialspace/apps/nodulemap/__init__.py @@ -0,0 +1,14 @@ +# -*- coding: utf-8 -*- +""" +iTrialSpace NoduleMap -- embedding-based interactive nodule similarity explorer. + +Subpackages +----------- +embeddings : Embedding generation pipeline (PCA, UMAP, t-SNE). +neighbors : KNN index + edge list computation (FAISS). +backend : FastAPI server for graph + neighbor queries. +cli : Command-line interface for batch + serve modes. +client : Jupyter notebook helper. +""" + +__version__ = "0.1.0" diff --git a/itrialspace/src/itrialspace/apps/nodulemap/__main__.py b/itrialspace/src/itrialspace/apps/nodulemap/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..b62acde2da672c1685bc76b8f2a782d851a8348e --- /dev/null +++ b/itrialspace/src/itrialspace/apps/nodulemap/__main__.py @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +"""Allow running as `python -m itrialspace.apps.nodulemap`.""" + +from itrialspace.apps.nodulemap.cli.cli import main + +if __name__ == "__main__": + main() diff --git a/itrialspace/src/itrialspace/apps/nodulemap/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/apps/nodulemap/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cb55602b17525c858dead8d28733ccdcd3196252 Binary files /dev/null and b/itrialspace/src/itrialspace/apps/nodulemap/__pycache__/__init__.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/apps/nodulemap/__pycache__/__main__.cpython-310.pyc b/itrialspace/src/itrialspace/apps/nodulemap/__pycache__/__main__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e5f2cebd9ecda5c3f85fcb1f37fecced5fd2bef7 Binary files /dev/null and b/itrialspace/src/itrialspace/apps/nodulemap/__pycache__/__main__.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/apps/nodulemap/backend/__init__.py b/itrialspace/src/itrialspace/apps/nodulemap/backend/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..12cafe069bd462bcd20e267d94d75e69a43adeb9 --- /dev/null +++ b/itrialspace/src/itrialspace/apps/nodulemap/backend/__init__.py @@ -0,0 +1,4 @@ +# -*- coding: utf-8 -*- +""" +nodulemap.backend — FastAPI server + data store + neighbor queries + exports. +""" diff --git a/itrialspace/src/itrialspace/apps/nodulemap/backend/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/apps/nodulemap/backend/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..62dbed3902c57d2b1d0c6d87dcd3f4798fca62ec Binary files /dev/null and b/itrialspace/src/itrialspace/apps/nodulemap/backend/__pycache__/__init__.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/apps/nodulemap/backend/__pycache__/app.cpython-310.pyc b/itrialspace/src/itrialspace/apps/nodulemap/backend/__pycache__/app.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..834e38303664a046982915df8b18af1cdb58ba0b Binary files /dev/null and b/itrialspace/src/itrialspace/apps/nodulemap/backend/__pycache__/app.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/apps/nodulemap/backend/__pycache__/data_store.cpython-310.pyc b/itrialspace/src/itrialspace/apps/nodulemap/backend/__pycache__/data_store.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..10d8c324ac4daeb92fa68da5913167c07abae9c9 Binary files /dev/null and b/itrialspace/src/itrialspace/apps/nodulemap/backend/__pycache__/data_store.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/apps/nodulemap/backend/__pycache__/export.cpython-310.pyc b/itrialspace/src/itrialspace/apps/nodulemap/backend/__pycache__/export.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c0c902ffa95b49715fc4634ac95f3e26c38ea89e Binary files /dev/null and b/itrialspace/src/itrialspace/apps/nodulemap/backend/__pycache__/export.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/apps/nodulemap/backend/app.py b/itrialspace/src/itrialspace/apps/nodulemap/backend/app.py new file mode 100644 index 0000000000000000000000000000000000000000..3cd8f6c7dfd5ed42787b8cafd3ed67440ff4edc4 --- /dev/null +++ b/itrialspace/src/itrialspace/apps/nodulemap/backend/app.py @@ -0,0 +1,482 @@ +# -*- coding: utf-8 -*- +""" +app.py — FastAPI backend for NoduleMap. + +Endpoints: + GET / → serves static frontend + GET /api/models → available embedding models + GET /api/graph → nodes + edges for map view + GET /api/node/{node_id} → full metadata for a node + GET /api/node/{node_id}/neighbors → ranked neighbor list + POST /api/export → export selection to file + GET /api/filters → available filter values + GET /health → health check + +Start: + uvicorn nodulemap.backend.app:create_app --factory --host 0.0.0.0 --port 8422 +""" + +from __future__ import annotations + +import os +from pathlib import Path + +from fastapi import FastAPI, HTTPException +from fastapi.middleware.cors import CORSMiddleware +from fastapi.responses import HTMLResponse +from fastapi.staticfiles import StaticFiles +from pydantic import BaseModel + +from itrialspace.apps.nodulemap.backend.data_store import DataStore +from itrialspace.apps.nodulemap.backend.export import Exporter +from itrialspace.config import settings + +# Artifact directory (configurable via env var; default resolved by settings: +# $NODULEMAP_ARTIFACTS or $ITRIALSPACE_OUTPUT_DIR/nodulemap_artifacts) +_DEFAULT_ARTIFACT_DIR = str(settings.nodulemap_artifacts_dir()) +_EXPORT_DIR = os.environ.get( + "NODULEMAP_EXPORTS", + str(settings.output_dir() / "nodulemap_exports"), +) +_STATIC_DIR = Path(__file__).parent.parent / "frontend" / "static" + + +# ── Pydantic models ────────────────────────────────────────────────────── + + +class GraphRequest(BaseModel): + vis_model: str = "UMAP_2D" + search_model: str = "UMAP_2D" + feature_set: str = "reinsertion_core" + k: int = 5 + mode: str = "closest" + scope: str = "cross_dataset" + color_by: str = "dataset" + filters: dict | None = None + + +class NeighborRequest(BaseModel): + model: str = "UMAP_2D" + feature_set: str = "reinsertion_core" + k: int = 10 + scope: str = "cross_dataset" + datasets: list[str] | None = None + balance_by_dataset: bool = False + + +class ExportRequest(BaseModel): + node_id: str + model: str = "UMAP_2D" + feature_set: str = "reinsertion_core" + k: int = 10 + scope: str = "cross_dataset" + format: str = "csv" # csv | json | donors + + +# ── App factory ────────────────────────────────────────────────────────── + + +def create_app(artifact_dir: str | None = None) -> FastAPI: + """Create the NoduleMap FastAPI app.""" + art_dir = artifact_dir or _DEFAULT_ARTIFACT_DIR + + app = FastAPI( + title="iTrialSpace NoduleMap", + version="0.1.0", + description="Embedding-based interactive nodule similarity explorer", + ) + + app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_methods=["*"], + allow_headers=["*"], + ) + + # Lazy init data store (on first request) + store: dict = {"instance": None} + exporter = Exporter(_EXPORT_DIR) + + def get_store() -> DataStore: + if store["instance"] is None: + print(f"[NoduleMap] Loading artifacts from {art_dir}") + store["instance"] = DataStore(art_dir) + return store["instance"] + + # ── Health ────────────────────────────────────────────────────────── + @app.get("/health") + def health(): + ds = get_store() + return { + "status": "ok", + "version": "0.1.0", + "models": ds.available_models, + "artifact_dir": art_dir, + } + + # ── Models ────────────────────────────────────────────────────────── + @app.get("/api/models") + def list_models(): + ds = get_store() + # Probe readiness: each model has embeddings + metadata + edge files + model_health: list[dict] = [] + for m in ds.available_models: + mn, fs = m["model_name"], m["feature_set"] + ok = True + try: + meta = ds.get_metadata(mn, fs) + emb = ds.get_embeddings(mn, fs) + ok = len(meta) == emb.shape[0] > 0 + except Exception: + ok = False + model_health.append({**m, "ready": ok}) + return { + "models": ds.available_models, + "layout_models": ds.layout_models, + "search_models": ds.search_models, + "health": model_health, + "version": "0.2.0", + } + + # ── Filters ───────────────────────────────────────────────────────── + @app.get("/api/filters") + def get_filters( + model: str = "UMAP_2D", + feature_set: str = "reinsertion_core", + ): + """Return all unique values for filterable columns.""" + ds = get_store() + meta = ds.get_metadata(model, feature_set) + + def unique_list(col): + if col in meta.columns: + return sorted([str(v) for v in meta[col].dropna().unique()]) + return [] + + return { + "datasets": unique_list("dataset"), + "labels": ["benign", "malignant", "unlabelled"], + "lobes": unique_list("reinsertion_lobe"), + "zones": unique_list("reinsertion_lung_zone"), + "sides": unique_list("reinsertion_lung_side"), + "size_buckets": unique_list("size_bucket"), + "label_sources": unique_list("label_source") if "label_source" in meta.columns else [], + "population_types": ( + unique_list("population_type") if "population_type" in meta.columns else [] + ), + "diameter_range": { + "min": ( + float(meta["reinsertion_nodule_diam_mm"].min()) + if "reinsertion_nodule_diam_mm" in meta.columns + else 0 + ), + "max": ( + float(meta["reinsertion_nodule_diam_mm"].max()) + if "reinsertion_nodule_diam_mm" in meta.columns + else 100 + ), + }, + } + + # ── Graph ─────────────────────────────────────────────────────────── + @app.post("/api/graph") + def get_graph(req: GraphRequest): + ds = get_store() + try: + data = ds.get_graph_data( + vis_model=req.vis_model, + search_model=req.search_model, + feature_set=req.feature_set, + k=req.k, + mode=req.mode, + scope=req.scope, + color_by=req.color_by, + filters=req.filters, + ) + return data + except FileNotFoundError as e: + raise HTTPException(status_code=404, detail=str(e)) + + # Also support GET for simpler access + @app.get("/api/graph") + def get_graph_get( + vis_model: str = "UMAP_2D", + search_model: str = "UMAP_2D", + feature_set: str = "reinsertion_core", + k: int = 5, + mode: str = "closest", + scope: str = "cross_dataset", + color_by: str = "dataset", + datasets: str | None = None, + label: str | None = None, + lobe: str | None = None, + zone: str | None = None, + side: str | None = None, + size_bucket: str | None = None, + diameter_min: float | None = None, + diameter_max: float | None = None, + ): + filters = {} + if datasets: + filters["datasets"] = datasets.split(",") + if label: + filters["label"] = label + if lobe: + filters["lobe"] = lobe.split(",") + if zone: + filters["zone"] = zone + if side: + filters["side"] = side + if size_bucket: + filters["size_bucket"] = size_bucket.split(",") + if diameter_min is not None: + filters["diameter_min"] = diameter_min + if diameter_max is not None: + filters["diameter_max"] = diameter_max + + req = GraphRequest( + vis_model=vis_model, + search_model=search_model, + feature_set=feature_set, + k=k, + mode=mode, + scope=scope, + color_by=color_by, + filters=filters if filters else None, + ) + return get_graph(req) + + # ── Node detail ───────────────────────────────────────────────────── + @app.get("/api/node/{node_id}") + def get_node( + node_id: str, + model: str = "UMAP_2D", + feature_set: str = "reinsertion_core", + ): + ds = get_store() + try: + return ds.get_node_detail(node_id, model, feature_set) + except KeyError: + raise HTTPException(status_code=404, detail=f"Node not found: {node_id}") + + # ── Axial thumbnail ──────────────────────────────────────────────── + @app.get("/api/node/{node_id}/axial_thumbnail") + def get_axial_thumbnail( + node_id: str, + model: str = "UMAP_2D", + feature_set: str = "reinsertion_core", + ): + from fastapi.responses import Response + + ds = get_store() + try: + png_bytes = ds.get_axial_thumbnail(node_id, model, feature_set) + except KeyError: + raise HTTPException(status_code=404, detail=f"Node not found: {node_id}") + if png_bytes is None: + raise HTTPException( + status_code=404, detail="Thumbnail unavailable: CT or mask not found" + ) + return Response(content=png_bytes, media_type="image/png") + + # ── Neighbors ─────────────────────────────────────────────────────── + @app.get("/api/node/{node_id}/neighbors") + def get_neighbors( + node_id: str, + model: str = "UMAP_2D", + feature_set: str = "reinsertion_core", + k: int = 10, + scope: str = "cross_dataset", + datasets: str | None = None, + balance_by_dataset: bool = False, + search_backend: str = "weighted", + debug: int = 0, + ): + import time as _time + + ds = get_store() + canon_model = ds._canon(model) + ds_list = datasets.split(",") if datasets else None + t0 = _time.perf_counter() + try: + results = ds.query_neighbors( + node_id=node_id, + model_name=model, + feature_set=feature_set, + k=k, + scope=scope, + datasets=ds_list, + balance_by_dataset=balance_by_dataset, + search_backend=search_backend, + ) + elapsed = _time.perf_counter() - t0 + resp: dict = { + "query_node_id": node_id, + "k": k, + "scope": scope, + "neighbors": results, + } + if debug: + emb = ds.get_embeddings(canon_model, feature_set) + resp["_debug"] = { + "model_requested": model, + "model_canonical": canon_model, + "feature_set": feature_set, + "embedding_dim": int(emb.shape[1]), + "n_embeddings": int(emb.shape[0]), + "elapsed_ms": round(elapsed * 1000, 2), + "n_results": len(results), + } + return resp + except KeyError: + raise HTTPException(status_code=404, detail=f"Node not found: {node_id}") + + # ── Export ────────────────────────────────────────────────────────── + @app.post("/api/export") + def export_data(req: ExportRequest): + ds = get_store() + try: + query_node = ds.get_node(req.node_id, req.model, req.feature_set) + neighbors = ds.query_neighbors( + node_id=req.node_id, + model_name=req.model, + feature_set=req.feature_set, + k=req.k, + scope=req.scope, + ) + + if req.format == "donors": + path = exporter.export_candidate_donors(neighbors) + else: + path = exporter.export_neighbors( + query_node=query_node, + neighbors=neighbors, + model_name=req.model, + feature_set=req.feature_set, + k=req.k, + scope=req.scope, + fmt=req.format, + ) + return {"status": "ok", "path": path} + except KeyError: + raise HTTPException(status_code=404, detail=f"Node not found: {req.node_id}") + + # ── Debug endpoints ─────────────────────────────────────────────── + @app.get("/debug/layout") + def debug_layout( + model: str = "UMAP_2D", + feature_set: str = "reinsertion_core", + limit: int = 5, + ): + """Return first *limit* 2D positions + node_ids for quick sanity-check.""" + ds = get_store() + try: + pos = ds.get_positions(model, feature_set) + meta = ds.get_metadata(model, feature_set) + ids = meta["node_id"].values[:limit].tolist() + coords = pos[:limit].tolist() + return { + "model": model, + "feature_set": feature_set, + "n_total": len(pos), + "samples": [{"node_id": i, "x": c[0], "y": c[1]} for i, c in zip(ids, coords)], + } + except Exception as e: + raise HTTPException(status_code=500, detail=str(e)) + + @app.get("/debug/search") + def debug_search( + node_id: str = "", + model: str = "UMAP_2D", + feature_set: str = "reinsertion_core", + k: int = 3, + ): + """Quick neighbor probe with debug info (embedding dim, index type, timing).""" + import time as _time + + ds = get_store() + if not node_id: + # return first available node_id so the user can try + meta = ds.get_metadata(model, feature_set) + node_id = meta["node_id"].values[0] + try: + emb = ds.get_embeddings(model, feature_set) + t0 = _time.perf_counter() + results = ds.query_neighbors( + node_id=node_id, + model_name=model, + feature_set=feature_set, + k=k, + ) + elapsed = _time.perf_counter() - t0 + return { + "query_node_id": node_id, + "model": model, + "embedding_dim": int(emb.shape[1]), + "n_embeddings": int(emb.shape[0]), + "k": k, + "elapsed_ms": round(elapsed * 1000, 2), + "neighbors": [ + { + "node_id": r["node_id"], + "distance": r["distance"], + "similarity": r["similarity"], + } + for r in results + ], + } + except Exception as e: + raise HTTPException(status_code=500, detail=str(e)) + + @app.get("/debug/alignment") + def debug_alignment(feature_set: str = "reinsertion_core"): + """Check node_id alignment across all models for a given feature set.""" + ds = get_store() + report: dict = {"feature_set": feature_set, "models": {}} + ref_ids = None + ref_name = None + for m in ds.available_models: + if m["feature_set"] != feature_set: + continue + mn = m["model_name"] + try: + meta = ds.get_metadata(mn, feature_set) + ids = meta["node_id"].values + entry = {"n_nodes": len(ids), "first_5": ids[:5].tolist(), "aligned": True} + if ref_ids is None: + ref_ids = ids + ref_name = mn + elif len(ids) != len(ref_ids) or not (ids == ref_ids).all(): + entry["aligned"] = False + entry["ref_model"] = ref_name + report["models"][mn] = entry + except Exception as e: + report["models"][mn] = {"error": str(e)} + return report + + # ── Static frontend ───────────────────────────────────────────────── + if _STATIC_DIR.exists(): + app.mount("/static", StaticFiles(directory=str(_STATIC_DIR)), name="static") + + @app.get("/", response_class=HTMLResponse) + def serve_frontend(): + index = _STATIC_DIR / "index.html" + if index.exists(): + content = index.read_text() + return HTMLResponse( + content=content, + headers={ + "Cache-Control": "no-cache, no-store, must-revalidate", + "Pragma": "no-cache", + "Expires": "0", + }, + ) + return "

NoduleMap frontend not found

" + + else: + + @app.get("/", response_class=HTMLResponse) + def serve_placeholder(): + return "

NoduleMap — frontend not built. Static dir: {}

".format(_STATIC_DIR) + + return app diff --git a/itrialspace/src/itrialspace/apps/nodulemap/backend/data_store.py b/itrialspace/src/itrialspace/apps/nodulemap/backend/data_store.py new file mode 100644 index 0000000000000000000000000000000000000000..811efd1386029bd70c24243618fb4037c22741ac --- /dev/null +++ b/itrialspace/src/itrialspace/apps/nodulemap/backend/data_store.py @@ -0,0 +1,929 @@ +# -*- coding: utf-8 -*- +""" +data_store.py -- Load and serve precomputed artifacts (embeddings, metadata, edges). + +Provides fast in-memory access to: + - Node metadata (parquet -> DataFrame) + - 2D positions (embeddings .npy files) + - Edge lists (parquet) + - KNN index (FAISS / sklearn) for on-demand neighbor queries + - Full node detail with demographics and resolved paths + - Axial slice thumbnails with mask overlay +""" + +from __future__ import annotations + +import os +from pathlib import Path +from typing import Literal, Optional + +import numpy as np +import pandas as pd + +from itrialspace.apps.nodulemap.neighbors import search_space + +try: + import faiss + + _HAS_FAISS = True +except ImportError: + _HAS_FAISS = False + + +# Demographics column mapping per dataset (matches CohortBuilder) +_DEMO_COL_MAP: dict[str, dict[str, str]] = { + "DLCS24": { + "Age": "patient_age", + "Sex": "patient_sex", + "Smoking Status (Current/ Former/ Never/ Unknown)": "smoking_status", + }, + "LUNA25": {"age": "patient_age", "gender": "patient_sex"}, + "NSCLCR": {"age": "patient_age", "gender": "patient_sex"}, + "IMDCT": {"age": "patient_age", "gender": "patient_sex", "smoke": "smoking_status"}, + "LUNGx": {}, + "LNDbv4": {}, + "LUNA16": {}, +} + + +def _extract_demographics(row: pd.Series, dataset: str) -> dict: + """Extract demographics from a full NoduleIndex row (best-effort).""" + col_map = _DEMO_COL_MAP.get(dataset, {}) + result = { + "patient_age": "NA", + "patient_sex": "NA", + "smoking_status": "NA", + "pack_years": "NA", + } + for src_col, tgt in col_map.items(): + val = row.get(src_col) + if val is None or (isinstance(val, float) and pd.isna(val)): + continue + if tgt == "patient_age": + try: + result[tgt] = str(int(float(val))) + except (ValueError, TypeError): + pass + elif tgt == "pack_years": + try: + result[tgt] = str(round(float(val), 1)) + except (ValueError, TypeError): + pass + else: + result[tgt] = str(val) + return result + + +# ── Canonical axial thumbnail renderer ───────────────────────────────────── + +# LRU cache for canonical NIfTI volumes (path -> (data_ras, affine_ras)) +_NIFTI_CANON_CACHE: dict[str, tuple[np.ndarray, np.ndarray]] = {} +_NIFTI_CANON_ORDER: list[str] = [] +_NIFTI_CANON_MAX = 8 + + +def _load_canonical(path: str) -> tuple[np.ndarray, np.ndarray]: + """Load a NIfTI, reorient to RAS+ canonical, return (data, affine).""" + if path in _NIFTI_CANON_CACHE: + return _NIFTI_CANON_CACHE[path] + + import nibabel as nib + + img = nib.load(path) + canon = nib.as_closest_canonical(img) + data = np.asarray(canon.dataobj, dtype=np.float32) + while data.ndim > 3: + data = data[..., 0] + affine = canon.affine.copy() + + # LRU eviction + if len(_NIFTI_CANON_CACHE) >= _NIFTI_CANON_MAX: + evict = _NIFTI_CANON_ORDER.pop(0) + _NIFTI_CANON_CACHE.pop(evict, None) + _NIFTI_CANON_CACHE[path] = (data, affine) + _NIFTI_CANON_ORDER.append(path) + return data, affine + + +def _render_canonical_axial_thumbnail( + ct_path: str, + mask_path: Optional[str], + coord_x: Optional[float], + coord_y: Optional[float], + coord_z: Optional[float], + window_center: float = -600.0, + window_width: float = 1500.0, + overlay_alpha: float = 0.35, +) -> Optional[bytes]: + """Render an axial thumbnail in standard radiology orientation. + + 1. Load CT & mask, reorient both to RAS+ canonical. + 2. Compute axial slice index from world coords (or mask COM fallback). + 3. Extract axial slice [:, :, z] in canonical space. + 4. Transpose + fliplr for radiology display (patient-R on image-left). + 5. Overlay mask, draw crosshair, burn R/L/A/P labels. + 6. Return PNG bytes. + """ + import io + + from PIL import Image, ImageDraw, ImageFont + + # ── Load canonical CT ────────────────────────────────────────────── + ct_data, ct_affine = _load_canonical(ct_path) + ct_shape = ct_data.shape # (X, Y, Z) in RAS+ + + # ── Load canonical mask (if available) ───────────────────────────── + mask_data = None + if mask_path: + m_data, m_affine = _load_canonical(mask_path) + if m_data.shape == ct_shape: + mask_data = (m_data > 0).astype(np.uint8) + else: + # Shape mismatch after canonicalization -- cannot overlay safely + mask_data = None + + # ── Determine axial slice index in canonical space ───────────────── + has_coords = ( + coord_x is not None + and coord_y is not None + and coord_z is not None + and not any(isinstance(c, float) and pd.isna(c) for c in (coord_x, coord_y, coord_z)) + ) + + voxel_i, voxel_j = None, None # for crosshair + + if has_coords: + inv_aff = np.linalg.inv(ct_affine) + world = np.array([float(coord_x), float(coord_y), float(coord_z), 1.0]) + ijk = inv_aff @ world + z_idx = int(round(ijk[2])) + voxel_i = int(round(ijk[0])) + voxel_j = int(round(ijk[1])) + elif mask_data is not None and mask_data.any(): + from scipy import ndimage + + com = ndimage.center_of_mass(mask_data) + z_idx = int(round(com[2])) + voxel_i = int(round(com[0])) + voxel_j = int(round(com[1])) + else: + z_idx = ct_shape[2] // 2 + + z_idx = max(0, min(z_idx, ct_shape[2] - 1)) + + # ── Extract axial slices ─────────────────────────────────────────── + ct_slice = ct_data[:, :, z_idx] # shape (X_ras, Y_ras) + mask_slice = mask_data[:, :, z_idx] if mask_data is not None else None + + # ── Radiology display transform ──────────────────────────────────── + # In RAS+ canonical: axis-0=R->L (X), axis-1=A->P (Y), axis-2=I->S (Z) + # Transpose so rows=Y (A->P), cols=X (R->L), then fliplr so + # patient-Right is on image-Left (radiological convention). + ct_disp = np.fliplr(ct_slice.T) # shape (Y, X), radiology view + mask_disp = np.fliplr(mask_slice.T) if mask_slice is not None else None + + # ── Compute crosshair in display coords ──────────────────────────── + disp_row, disp_col = None, None + if voxel_i is not None and voxel_j is not None: + disp_row = voxel_j # row = j (Y index) + disp_col = ct_slice.shape[0] - 1 - voxel_i # col = (X-1-i) due to fliplr + + # ── Window CT to uint8 ───────────────────────────────────────────── + lo = window_center - window_width / 2 + hi = window_center + window_width / 2 + img_u8 = np.clip(ct_disp, lo, hi) + img_u8 = ((img_u8 - lo) / (hi - lo) * 255).astype(np.uint8) + + # ── Build RGB with mask overlay ──────────────────────────────────── + rgb = np.stack([img_u8, img_u8, img_u8], axis=-1) + + if mask_disp is not None and mask_disp.any(): + overlay = np.zeros_like(rgb) + overlay[mask_disp > 0] = [255, 50, 50] # red + blended = ( + rgb.astype(float) * (1 - overlay_alpha) + overlay.astype(float) * overlay_alpha + ).astype(np.uint8) + # Only blend where mask is active + rgb[mask_disp > 0] = blended[mask_disp > 0] + + # ── Convert to PIL image (origin="lower" effect via flipud) ──────── + # imshow origin="lower" means row-0 is at bottom. + # In our RAS+ transposed view, row-0 = Anterior, which should be at + # the top in standard radiology. So we flipud to place row-0 at bottom + # (Anterior at top when rendered top-down in PNG). + rgb = np.flipud(rgb) + pil_img = Image.fromarray(rgb) + + # ── Draw crosshair ───────────────────────────────────────────────── + draw = ImageDraw.Draw(pil_img) + h_img, w_img = rgb.shape[0], rgb.shape[1] + + if disp_row is not None and disp_col is not None: + # After flipud: display_row_flipped = (H-1) - disp_row + cr = (h_img - 1) - disp_row + cc = disp_col + cross_color = (0, 255, 0) # green + arm = 8 + draw.line([(cc - arm, cr), (cc + arm, cr)], fill=cross_color, width=1) + draw.line([(cc, cr - arm), (cc, cr + arm)], fill=cross_color, width=1) + + # ── Orientation labels ───────────────────────────────────────────── + try: + font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 14) + except (IOError, OSError): + font = ImageFont.load_default() + + label_color = (255, 255, 0) # yellow + shadow_color = (0, 0, 0) + margin = 4 + + def _draw_label(x, y, text, anchor=None): + # Shadow for readability + draw.text((x + 1, y + 1), text, fill=shadow_color, font=font, anchor=anchor) + draw.text((x, y), text, fill=label_color, font=font, anchor=anchor) + + # R on left (radiological: patient-Right on viewer-Left) + _draw_label(margin, h_img // 2, "R", anchor="lm") + # L on right + _draw_label(w_img - margin, h_img // 2, "L", anchor="rm") + # A at top + _draw_label(w_img // 2, margin, "A", anchor="mt") + # P at bottom + _draw_label(w_img // 2, h_img - margin, "P", anchor="mb") + + # ── Encode PNG ───────────────────────────────────────────────────── + buf = io.BytesIO() + pil_img.save(buf, format="PNG") + return buf.getvalue() + + +class DataStore: + """In-memory store for NoduleMap artifacts.""" + + # ── Model name canonicalization ──────────────────────────────────────── + _NAME_ALIASES: dict[str, str] = { + "tsne_2d": "TSNE_2D", + "t-sne_2d": "TSNE_2D", + "tSNE_2D": "TSNE_2D", + "pca_2d": "PCA_2D", + "pca_32d": "PCA_32", + "pca_32": "PCA_32", + "umap_2d": "UMAP_2D", + "umap_16d": "UMAP_16", + "umap_16": "UMAP_16", + "umap_32d": "UMAP_32", + "umap_32": "UMAP_32", + } + + @classmethod + def _canon(cls, name: str) -> str: + """Canonicalize a model name. E.g. 'tSNE_2D' → 'TSNE_2D'.""" + return cls._NAME_ALIASES.get(name.lower().strip(), name) + + def __init__(self, artifact_dir: str, verbose: bool = True): + self._dir = Path(artifact_dir) + self._verbose = verbose + + # Caches + self._metadata: dict[str, pd.DataFrame] = {} # tag -> metadata df + self._embeddings: dict[str, np.ndarray] = {} # tag -> (n, d) array + self._positions: dict[str, np.ndarray] = {} # tag -> (n, 2) array + self._edges: dict[str, pd.DataFrame] = {} # edge_key -> edge df + self._knn_indices: dict[str, object] = {} # tag -> faiss/sklearn index + self._search_matrices: dict[str, np.ndarray] = {} # (fs,backend,model) -> matrix + self._available_models: list[dict] = [] + + # Lazy-loaded helpers for detail/thumbnail + self._full_index: Optional[pd.DataFrame] = None + self._path_resolver = None # type: ignore + self._slicer = None # type: ignore + + self._scan_artifacts() + + def _log(self, msg: str) -> None: + if self._verbose: + print(f"[DataStore] {msg}") + + def _scan_artifacts(self) -> None: + """Scan artifact directory and catalog available models. + + Classifies each model as *layout* (2D — suitable for ``vis_model``) + or *search* (any D — suitable for ``search_model``). + Also validates that node_id ordering is consistent across all models. + """ + models: dict[tuple[str, str], int] = {} # (fs, model) → n_dims + for f in self._dir.glob("embeddings_*.npy"): + stem = f.stem.replace("embeddings_", "") + parts = stem.split("__") + if len(parts) == 2: + fs, mn = parts + # quick-probe dimensionality without loading full array + arr = np.load(f, mmap_mode="r") + n_dims = arr.shape[1] if arr.ndim == 2 else 0 + models[(fs, mn)] = n_dims + + layout_models: list[dict] = [] + search_models: list[dict] = [] + for (fs, mn), nd in sorted(models.items()): + entry = {"feature_set": fs, "model_name": mn, "n_dims": nd} + if nd == 2: + layout_models.append(entry) + search_models.append(entry) # all models can be used for search + + self._layout_models = layout_models + self._search_models = search_models + self._available_models = [ + {"feature_set": fs, "model_name": mn, "n_dims": nd} + for (fs, mn), nd in sorted(models.items()) + ] + + if self._verbose: + self._log( + f"Found {len(self._available_models)} model(s): " + f"{len(layout_models)} layout, {len(search_models)} search" + ) + + # ── Validate node_id alignment across all models ─────────────── + ref_ids: Optional[np.ndarray] = None + ref_tag: Optional[str] = None + for fs, mn in sorted(models.keys()): + meta_path = self._dir / f"metadata_{fs}__{mn}.parquet" + if not meta_path.exists(): + continue + ids = pd.read_parquet(meta_path, columns=["node_id"])["node_id"].values + if ref_ids is None: + ref_ids = ids + ref_tag = f"{fs}__{mn}" + else: + if len(ids) != len(ref_ids) or not (ids == ref_ids).all(): + self._log( + f"WARNING: node_id mismatch between {ref_tag} and {fs}__{mn}! " + f"len {len(ref_ids)} vs {len(ids)}" + ) + if ref_ids is not None and self._verbose: + self._log(f"node_id alignment OK ({len(ref_ids)} nodes, {len(models)} models)") + + @property + def available_models(self) -> list[dict]: + return self._available_models + + @property + def layout_models(self) -> list[dict]: + """Models with 2D embeddings — suitable as vis_model / position model.""" + return self._layout_models + + @property + def search_models(self) -> list[dict]: + """All models — suitable for similarity search.""" + return self._search_models + + def _tag(self, model_name: str, feature_set: str) -> str: + return f"{feature_set}__{model_name}" + + # ── Loaders (lazy, cached) ───────────────────────────────────────────── + + def get_metadata(self, model_name: str, feature_set: str) -> pd.DataFrame: + """Load node metadata for a specific model+feature_set.""" + model_name = self._canon(model_name) + tag = self._tag(model_name, feature_set) + if tag not in self._metadata: + path = self._dir / f"metadata_{tag}.parquet" + if not path.exists(): + raise FileNotFoundError(f"Metadata not found: {path}") + self._metadata[tag] = pd.read_parquet(path) + self._log(f"Loaded metadata: {len(self._metadata[tag])} nodes") + return self._metadata[tag] + + def get_embeddings(self, model_name: str, feature_set: str) -> np.ndarray: + """Load embedding matrix.""" + model_name = self._canon(model_name) + tag = self._tag(model_name, feature_set) + if tag not in self._embeddings: + path = self._dir / f"embeddings_{tag}.npy" + if not path.exists(): + raise FileNotFoundError(f"Embeddings not found: {path}") + self._embeddings[tag] = np.load(path).astype(np.float32) + self._log(f"Loaded embeddings: {self._embeddings[tag].shape}") + return self._embeddings[tag] + + def get_positions(self, vis_model: str, feature_set: str) -> np.ndarray: + """Load 2D positions for visualization (must be a 2D model).""" + vis_model = self._canon(vis_model) + tag = self._tag(vis_model, feature_set) + if tag not in self._positions: + emb = self.get_embeddings(vis_model, feature_set) + if emb.shape[1] < 2: + raise ValueError(f"Model {vis_model} has <2 dimensions") + self._positions[tag] = emb[:, :2] + return self._positions[tag] + + def get_edges( + self, + model_name: str, + feature_set: str, + k: int = 5, + mode: str = "closest", + scope: str = "cross_dataset", + ) -> pd.DataFrame: + """Load precomputed edge list.""" + model_name = self._canon(model_name) + tag = self._tag(model_name, feature_set) + edge_key = f"{tag}_k{k}_{mode}_{scope}" + if edge_key not in self._edges: + path = self._dir / f"edges_{tag}_k{k}_{mode}_{scope}.parquet" + if not path.exists(): + raise FileNotFoundError( + f"Edge file not found: {path}. " + f"Run: itrialspace-nodulemap edges --model {model_name} " + f"--feature-set {feature_set} --k {k} --mode {mode}" + ) + self._edges[edge_key] = pd.read_parquet(path) + self._log(f"Loaded edges: {len(self._edges[edge_key])} ({edge_key})") + return self._edges[edge_key] + + # ── KNN index (for on-demand queries) ────────────────────────────────── + + def _get_knn_index(self, model_name: str, feature_set: str): + """Build or retrieve a FAISS/sklearn index for on-demand neighbor queries.""" + model_name = self._canon(model_name) + tag = self._tag(model_name, feature_set) + if tag not in self._knn_indices: + emb = self.get_embeddings(model_name, feature_set) + if _HAS_FAISS: + index = faiss.IndexFlatL2(emb.shape[1]) + index.add(emb) + self._knn_indices[tag] = ("faiss", index) + else: + from sklearn.neighbors import NearestNeighbors + + nn = NearestNeighbors( + n_neighbors=min(50, len(emb)), metric="euclidean", algorithm="auto" + ) + nn.fit(emb) + self._knn_indices[tag] = ("sklearn", nn) + self._log(f"Built KNN index for {tag}") + return self._knn_indices[tag] + + def _get_search_matrix(self, model_name: str, feature_set: str, backend: str) -> np.ndarray: + """Build/cache the matrix that similarity SEARCH runs on for a backend.""" + key = f"{feature_set}|{backend}|{model_name if backend == 'embedding' else '-'}" + if key not in self._search_matrices: + meta = self.get_metadata(model_name, feature_set) + self._search_matrices[key] = search_space.build_search_matrix( + backend, self._dir, feature_set, model_name, meta + ) + self._log(f"Built search matrix [{backend}]: {self._search_matrices[key].shape}") + return self._search_matrices[key] + + def query_neighbors( + self, + node_id: str, + model_name: str, + feature_set: str, + k: int = 10, + scope: Literal["cross_dataset", "within_dataset", "selected_datasets"] = "cross_dataset", + datasets: list[str] | None = None, + balance_by_dataset: bool = False, + search_backend: str = "weighted", + ) -> list[dict]: + """ + On-demand neighbor (donor-matching) query for a specific node. + + ``search_backend``: 'weighted' (default, clinical ReinsertionMatcher metric), + 'feature_l2' (standardized full feature space), or 'embedding' (reduced; legacy). + Returns list of dicts with: node_id, distance, similarity, rank, + metadata. + """ + model_name = self._canon(model_name) + meta = self.get_metadata(model_name, feature_set) + matrix = self._get_search_matrix(model_name, feature_set, search_backend) + metric = search_space.metric_for(search_backend) + + # Find query node index + node_mask = meta["node_id"].values == node_id + if not node_mask.any(): + raise KeyError(f"Node not found: {node_id}") + query_idx = int(np.where(node_mask)[0][0]) + query_vec = matrix[query_idx : query_idx + 1] # (1, d) + + # Determine candidate set + if scope == "within_dataset": + query_ds = meta.iloc[query_idx]["dataset"] + candidate_mask = meta["dataset"].values == query_ds + elif scope == "selected_datasets" and datasets: + candidate_mask = meta["dataset"].isin(datasets).values + else: + candidate_mask = np.ones(len(meta), dtype=bool) + + candidate_indices = np.where(candidate_mask)[0] + candidate_mat = matrix[candidate_mask].astype(np.float32) + + # KNN on candidates (true distances) + search_k = min(k + 1, len(candidate_mat)) + dists, inds = search_space.knn(candidate_mat, query_vec, search_k, metric) + + # Build result list + results = [] + rank = 0 + for j in range(inds.shape[1]): + global_idx = candidate_indices[inds[0, j]] + if global_idx == query_idx: + continue + dist = float(max(dists[0, j], 0.0)) + sim = float(np.exp(-dist)) + row = meta.iloc[global_idx].to_dict() + row["distance"] = round(dist, 6) + row["similarity"] = round(sim, 6) + rank += 1 + row["rank"] = rank + results.append(row) + if rank >= k: + break + + # Optional: balance by dataset + if balance_by_dataset and results: + results = self._balance_results(results, k) + + return results + + def _balance_results(self, results: list[dict], k: int) -> list[dict]: + """Re-rank results to ensure balanced dataset representation.""" + from collections import defaultdict + + by_ds = defaultdict(list) + for r in results: + by_ds[r["dataset"]].append(r) + n_ds = len(by_ds) + per_ds = max(1, k // n_ds) + balanced = [] + for ds_results in by_ds.values(): + balanced.extend(ds_results[:per_ds]) + # Fill remaining slots + remaining = k - len(balanced) + if remaining > 0: + used = {r["node_id"] for r in balanced} + for r in results: + if r["node_id"] not in used: + balanced.append(r) + remaining -= 1 + if remaining <= 0: + break + # Re-rank + balanced.sort(key=lambda x: x["distance"]) + for i, r in enumerate(balanced): + r["rank"] = i + 1 + return balanced[:k] + + def get_node(self, node_id: str, model_name: str, feature_set: str) -> dict: + """Get full metadata for a single node.""" + model_name = self._canon(model_name) + meta = self.get_metadata(model_name, feature_set) + row = meta[meta["node_id"] == node_id] + if row.empty: + raise KeyError(f"Node not found: {node_id}") + return row.iloc[0].to_dict() + + # ── Full index / path resolver / slicer (lazy) ───────────────────────── + + def _get_full_index(self) -> pd.DataFrame: + """Load the full NoduleIndex DataFrame (with all extra columns).""" + if self._full_index is None: + try: + from itrialspace.index.nodule_index import NoduleIndex + from itrialspace.io.registry import DatasetRegistry + + # Portable registry resolution via itrialspace.config.settings. + registry = DatasetRegistry.from_yaml() + idx = NoduleIndex.from_registry(registry, verbose=False) + self._full_index = idx.df + self._log( + f"Loaded full NoduleIndex: {len(self._full_index)} rows, " + f"{len(self._full_index.columns)} cols" + ) + except Exception as e: + self._log(f"WARNING: Could not load NoduleIndex: {e}") + self._full_index = pd.DataFrame() + return self._full_index + + def _get_path_resolver(self): + """Load PathResolver for resolving CT/mask paths.""" + if self._path_resolver is None: + try: + from itrialspace.site.path_resolver import PathResolver + + self._path_resolver = PathResolver() + self._log("PathResolver loaded") + except Exception as e: + self._log(f"WARNING: Could not load PathResolver: {e}") + self._path_resolver = False # sentinel: tried, failed + return self._path_resolver if self._path_resolver is not False else None + + def _get_slicer(self): + """Load NIfTISlicer for thumbnail generation.""" + if self._slicer is None: + try: + from itrialspace.apps.retriever.slicer import NIfTISlicer + + self._slicer = NIfTISlicer(cache_size=8) + self._log("NIfTISlicer loaded") + except Exception as e: + self._log(f"WARNING: Could not load NIfTISlicer: {e}") + self._slicer = False # sentinel + return self._slicer if self._slicer is not False else None + + def _resolve_paths_for_row(self, row: pd.Series) -> dict: + """Resolve CT/mask paths for a NoduleIndex row.""" + resolver = self._get_path_resolver() + if resolver is None: + return {} + try: + paths = resolver.resolve_all_paths(row) + # Only return paths that actually exist on disk + result = {} + for key in ("ct_path", "nodule_mask_path", "organ_seg_path"): + p = paths.get(key, "") + result[f"{key}_abs"] = p if p and os.path.isfile(p) else "" + return result + except Exception: + return {} + + def get_node_detail(self, node_id: str, model_name: str, feature_set: str) -> dict: + """Get comprehensive node detail: metadata + demographics + resolved paths.""" + model_name = self._canon(model_name) + # Start with embedding metadata + base = self.get_node(node_id, model_name, feature_set) + + # Look up full index row for demographics and extra fields + full_idx = self._get_full_index() + demographics = { + "patient_age": "NA", + "patient_sex": "NA", + "smoking_status": "NA", + "pack_years": "NA", + } + resolved_paths = {} + + if not full_idx.empty: + # Match by annotation_id (more reliable than node_id) + ann_id = base.get("annotation_id", node_id) + match = full_idx[full_idx["annotation_id"] == ann_id] + if match.empty: + # Try node_id + if "node_id" in full_idx.columns: + match = full_idx[full_idx["node_id"] == node_id] + + if not match.empty: + full_row = match.iloc[0] + dataset = base.get("dataset", full_row.get("dataset", "")) + + # Extract demographics + demographics = _extract_demographics(full_row, dataset) + + # Add patient_id from full index if not already present + if "patient_id" not in base or pd.isna(base.get("patient_id")): + pid = full_row.get("patient_id") + if pid is not None and not (isinstance(pid, float) and pd.isna(pid)): + base["patient_id"] = str(pid) + + # Resolve paths + resolved_paths = self._resolve_paths_for_row(full_row) + + # Ensure key donor fields are present + for col in ( + "annotation_id", + "ct_path", + "coordX", + "coordY", + "coordZ", + "label", + "nodule_mean_diam_mm", + ): + if col not in base or pd.isna(base.get(col)): + val = full_row.get(col) + if val is not None and not (isinstance(val, float) and pd.isna(val)): + base[col] = val + + base["demographics"] = demographics + base.update(resolved_paths) + + # Clean NaN/NaT values for JSON serialization + for k, v in list(base.items()): + if isinstance(v, float) and (pd.isna(v) or np.isinf(v)): + base[k] = None + elif isinstance(v, (np.integer,)): + base[k] = int(v) + elif isinstance(v, (np.floating,)): + base[k] = float(v) if not np.isnan(v) else None + + return base + + def get_axial_thumbnail( + self, node_id: str, model_name: str, feature_set: str + ) -> Optional[bytes]: + """Generate an axial slice thumbnail (PNG) for a nodule. + + Uses canonical (RAS+) reorientation for consistent radiology display. + Returns PNG bytes or None if CT/mask is unavailable. + """ + model_name = self._canon(model_name) + # Get node detail with resolved paths + detail = self.get_node_detail(node_id, model_name, feature_set) + ct_path = detail.get("ct_path_abs", "") + mask_path = detail.get("nodule_mask_path_abs", "") + + if not ct_path or not os.path.isfile(ct_path): + return None + + try: + return _render_canonical_axial_thumbnail( + ct_path=ct_path, + mask_path=mask_path if mask_path and os.path.isfile(mask_path) else None, + coord_x=detail.get("coordX"), + coord_y=detail.get("coordY"), + coord_z=detail.get("coordZ"), + ) + except Exception as e: + self._log(f"Thumbnail error for {node_id}: {e}") + return None + + def get_graph_data( + self, + vis_model: str, + search_model: str, + feature_set: str, + k: int = 5, + mode: str = "closest", + scope: str = "cross_dataset", + color_by: str = "dataset", + filters: dict | None = None, + ) -> dict: + """ + Get nodes + edges for the map view. + + Returns: {"nodes": [...], "edges": [...], "stats": {...}} + """ + vis_model = self._canon(vis_model) + search_model = self._canon(search_model) + meta = self.get_metadata(search_model, feature_set) + pos = self.get_positions(vis_model, feature_set) + + # Apply filters + mask = np.ones(len(meta), dtype=bool) + if filters: + mask = self._apply_filters(meta, filters) + + filtered_meta = meta[mask].copy() + filtered_pos = pos[mask] + filtered_ids = set(filtered_meta["node_id"].values) + + # Load edges and filter to visible nodes + try: + edges_df = self.get_edges(search_model, feature_set, k, mode, scope) + edges_df = edges_df[ + edges_df["src_id"].isin(filtered_ids) & edges_df["dst_id"].isin(filtered_ids) + ] + except FileNotFoundError: + edges_df = pd.DataFrame(columns=["src_id", "dst_id", "distance", "similarity", "rank"]) + + # Build node list + nodes = [] + for i, (_, row) in enumerate(filtered_meta.iterrows()): + node = { + "id": row["node_id"], + "x": float(filtered_pos[i, 0]), + "y": float(filtered_pos[i, 1]), + "dataset": row.get("dataset", ""), + "label_text": row.get("label_text", "unlabelled"), + "size_bucket": row.get("size_bucket", ""), + } + # Add color_by value + if color_by in row.index: + val = row[color_by] + node["color_value"] = str(val) if pd.notna(val) else "unknown" + else: + node["color_value"] = "unknown" + # Add hover tooltip fields + for col in [ + "reinsertion_nodule_diam_mm", + "reinsertion_lobe", + "reinsertion_lung_zone", + "annotation_id", + ]: + if col in row.index: + val = row[col] + node[col] = val if pd.notna(val) else None + nodes.append(node) + + # Build edge list + edges = [] + for _, erow in edges_df.iterrows(): + edges.append( + { + "source": erow["src_id"], + "target": erow["dst_id"], + "similarity": erow.get("similarity", 0), + "distance": erow.get("distance", 0), + } + ) + + return { + "nodes": nodes, + "edges": edges, + "stats": { + "n_nodes": len(nodes), + "n_edges": len(edges), + "n_total": len(meta), + "n_filtered": len(meta) - len(filtered_meta), + }, + } + + def _apply_filters(self, meta: pd.DataFrame, filters: dict) -> np.ndarray: + """Apply filter dict to metadata, return boolean mask.""" + mask = np.ones(len(meta), dtype=bool) + + # Dataset filter + if "datasets" in filters and filters["datasets"]: + mask &= meta["dataset"].isin(filters["datasets"]).values + + # Label filter + if "label" in filters: + lbl = filters["label"] + if lbl == "unlabelled": + mask &= meta["label"].isna().values + elif lbl in ("0", "1"): + mask &= (meta["label"] == int(lbl)).values + elif lbl == "labelled": + mask &= meta["label"].notna().values + + # Label source + if "label_source" in filters and filters["label_source"] != "all": + if "label_source" in meta.columns: + mask &= (meta["label_source"] == filters["label_source"]).values + + # Population type + if "population_type" in filters and filters["population_type"] != "all": + if "population_type" in meta.columns: + mask &= (meta["population_type"] == filters["population_type"]).values + + # Lobe + if "lobe" in filters and filters["lobe"]: + col = "reinsertion_lobe" if "reinsertion_lobe" in meta.columns else "lobe_name" + if col in meta.columns: + if isinstance(filters["lobe"], list): + mask &= meta[col].isin(filters["lobe"]).values + else: + mask &= (meta[col] == filters["lobe"]).values + + # Zone + if "zone" in filters and filters["zone"]: + col = ( + "reinsertion_lung_zone" if "reinsertion_lung_zone" in meta.columns else "lung_zone" + ) + if col in meta.columns: + mask &= (meta[col] == filters["zone"]).values + + # Side + if "side" in filters and filters["side"]: + col = ( + "reinsertion_lung_side" if "reinsertion_lung_side" in meta.columns else "lung_side" + ) + if col in meta.columns: + mask &= (meta[col] == filters["side"]).values + + # Diameter range + diam_col = "reinsertion_nodule_diam_mm" + if diam_col not in meta.columns: + diam_col = "nodule_mean_diam_mm" + if "diameter_min" in filters and filters["diameter_min"] is not None: + mask &= (meta[diam_col] >= filters["diameter_min"]).values + if "diameter_max" in filters and filters["diameter_max"] is not None: + mask &= (meta[diam_col] <= filters["diameter_max"]).values + + # Size bucket + if "size_bucket" in filters and filters["size_bucket"]: + if "size_bucket" in meta.columns: + if isinstance(filters["size_bucket"], list): + mask &= meta["size_bucket"].isin(filters["size_bucket"]).values + else: + mask &= (meta["size_bucket"] == filters["size_bucket"]).values + + # Pleural distance range + if "pleural_min" in filters and filters["pleural_min"] is not None: + col = "reinsertion_pleural_dist_mm" + if col in meta.columns: + mask &= (meta[col] >= filters["pleural_min"]).values + if "pleural_max" in filters and filters["pleural_max"] is not None: + col = "reinsertion_pleural_dist_mm" + if col in meta.columns: + mask &= (meta[col] <= filters["pleural_max"]).values + + # Airway distance range + if "airway_min" in filters and filters["airway_min"] is not None: + col = "reinsertion_airway_dist_mm" + if col in meta.columns: + mask &= (meta[col] >= filters["airway_min"]).values + if "airway_max" in filters and filters["airway_max"] is not None: + col = "reinsertion_airway_dist_mm" + if col in meta.columns: + mask &= (meta[col] <= filters["airway_max"]).values + + return mask diff --git a/itrialspace/src/itrialspace/apps/nodulemap/backend/export.py b/itrialspace/src/itrialspace/apps/nodulemap/backend/export.py new file mode 100644 index 0000000000000000000000000000000000000000..1e51248a831e1381047bac1190415568b2e223c4 --- /dev/null +++ b/itrialspace/src/itrialspace/apps/nodulemap/backend/export.py @@ -0,0 +1,140 @@ +# -*- coding: utf-8 -*- +""" +export.py — export selected nodes / neighbor sets to CSV/JSON. +""" + +from __future__ import annotations + +import json +import time +from pathlib import Path + +import pandas as pd + + +class Exporter: + """Export neighbor sets and selected nodes.""" + + def __init__(self, export_dir: str = "./exports"): + self._dir = Path(export_dir) + self._dir.mkdir(parents=True, exist_ok=True) + + def export_neighbors( + self, + query_node: dict, + neighbors: list[dict], + model_name: str, + feature_set: str, + k: int, + scope: str, + fmt: str = "csv", + ) -> str: + """ + Export a node + its neighbors. + + Returns path to the exported file. + """ + ts = time.strftime("%Y%m%d_%H%M%S") + qid = query_node.get("node_id", "unknown") + + rows = [] + for nb in neighbors: + rows.append( + { + "query_node_id": qid, + "query_dataset": query_node.get("dataset", ""), + "query_annotation_id": query_node.get("annotation_id", ""), + "neighbor_node_id": nb.get("node_id", ""), + "neighbor_dataset": nb.get("dataset", ""), + "neighbor_annotation_id": nb.get("annotation_id", ""), + "distance": nb.get("distance", 0), + "similarity": nb.get("similarity", 0), + "rank": nb.get("rank", 0), + "neighbor_diameter_mm": nb.get("reinsertion_nodule_diam_mm", None), + "neighbor_lobe": nb.get("reinsertion_lobe", ""), + "neighbor_label": nb.get("label_text", ""), + "model": model_name, + "feature_set": feature_set, + "k": k, + "scope": scope, + } + ) + + df = pd.DataFrame(rows) + + if fmt == "json": + out_path = self._dir / f"neighbors_{qid}_{ts}.json" + payload = { + "query": query_node, + "neighbors": neighbors, + "meta": { + "model": model_name, + "feature_set": feature_set, + "k": k, + "scope": scope, + "exported_at": ts, + }, + } + with open(out_path, "w") as f: + json.dump(payload, f, indent=2, default=str) + else: + out_path = self._dir / f"neighbors_{qid}_{ts}.csv" + df.to_csv(out_path, index=False) + + return str(out_path) + + def export_candidate_donors( + self, + neighbors: list[dict], + path_resolver=None, + ) -> str: + """ + Export compatible with iTrialSpace Retriever manifest format. + + Columns: donor_annotation_id, donor_dataset, ct_path, mask_path + """ + ts = time.strftime("%Y%m%d_%H%M%S") + rows = [] + for nb in neighbors: + row = { + "donor_annotation_id": nb.get("annotation_id", ""), + "donor_dataset": nb.get("dataset", ""), + "ct_path": nb.get("ct_path", ""), + } + # Resolve mask path if PathResolver available + if path_resolver and nb.get("annotation_id"): + try: + mask = path_resolver.resolve_nodule_mask_path( + nb["dataset"], nb["annotation_id"] + ) + row["mask_path"] = mask + except Exception: + row["mask_path"] = "" + else: + row["mask_path"] = "" + + rows.append(row) + + df = pd.DataFrame(rows) + out_path = self._dir / f"candidate_donors_{ts}.csv" + df.to_csv(out_path, index=False) + return str(out_path) + + def export_selected_nodes( + self, + node_ids: list[str], + metadata: pd.DataFrame, + fmt: str = "csv", + ) -> str: + """Export metadata for selected nodes.""" + ts = time.strftime("%Y%m%d_%H%M%S") + selected = metadata[metadata["node_id"].isin(node_ids)] + + if fmt == "json": + out_path = self._dir / f"selected_nodes_{ts}.json" + selected.to_json(out_path, orient="records", indent=2) + else: + out_path = self._dir / f"selected_nodes_{ts}.csv" + selected.to_csv(out_path, index=False) + + return str(out_path) diff --git a/itrialspace/src/itrialspace/apps/nodulemap/cli/__init__.py b/itrialspace/src/itrialspace/apps/nodulemap/cli/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5ca6f65cb813d30ab2e730dd8ba99f5d4f472c59 --- /dev/null +++ b/itrialspace/src/itrialspace/apps/nodulemap/cli/__init__.py @@ -0,0 +1,4 @@ +# -*- coding: utf-8 -*- +""" +nodulemap.cli — command-line interface. +""" diff --git a/itrialspace/src/itrialspace/apps/nodulemap/cli/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/apps/nodulemap/cli/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7d8d6c236a2c241fae32612844b6e2c6175aea81 Binary files /dev/null and b/itrialspace/src/itrialspace/apps/nodulemap/cli/__pycache__/__init__.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/apps/nodulemap/cli/__pycache__/cli.cpython-310.pyc b/itrialspace/src/itrialspace/apps/nodulemap/cli/__pycache__/cli.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..79176b4b04dd31ca471fa38b3fd91639169621f3 Binary files /dev/null and b/itrialspace/src/itrialspace/apps/nodulemap/cli/__pycache__/cli.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/apps/nodulemap/cli/cli.py b/itrialspace/src/itrialspace/apps/nodulemap/cli/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..8c2b5fcaf1d819c5f962f6c7d2f301440a90963f --- /dev/null +++ b/itrialspace/src/itrialspace/apps/nodulemap/cli/cli.py @@ -0,0 +1,327 @@ +# -*- coding: utf-8 -*- +""" +cli.py — itrialspace-nodulemap command-line interface. + +Commands: + build — Generate embeddings for a model + feature set + edges — Compute KNN edge lists + serve — Start the FastAPI + frontend server + info — Show available models / feature sets / artifacts + query — Query neighbors for a node (offline, no server) + export — Export neighbors for a node + +Usage: + python -m itrialspace.apps.nodulemap build --model UMAP_2D --feature-set reinsertion_core --outdir ./nodulemap_artifacts + python -m itrialspace.apps.nodulemap edges --model UMAP_2D --feature-set reinsertion_core --k 5 --mode closest --outdir ./nodulemap_artifacts + python -m itrialspace.apps.nodulemap serve --artifact-dir ./nodulemap_artifacts --port 8422 + python -m itrialspace.apps.nodulemap info --artifact-dir ./nodulemap_artifacts + python -m itrialspace.apps.nodulemap query --node DLCS24_DLCS_0001_01 --model UMAP_2D --k 10 --artifact-dir ./nodulemap_artifacts +""" + +from __future__ import annotations + +import argparse +import os +import sys + + +def main(argv: list[str] | None = None) -> None: + parser = argparse.ArgumentParser( + prog="itrialspace-nodulemap", + description="iTrialSpace NoduleMap — embedding-based nodule similarity explorer", + ) + sub = parser.add_subparsers(dest="command", help="Available commands") + + # ── build ────────────────────────────────────────────────────────── + p_build = sub.add_parser("build", help="Generate embeddings") + p_build.add_argument("--model", default="UMAP_2D", help="Model preset name (default: UMAP_2D)") + p_build.add_argument( + "--feature-set", default="reinsertion_core", help="Feature set (default: reinsertion_core)" + ) + p_build.add_argument( + "--outdir", + default=None, + help="Artifacts output dir (default: $NODULEMAP_ARTIFACTS or $ITRIALSPACE_OUTPUT_DIR/nodulemap_artifacts)", + ) + p_build.add_argument("--all-2d", action="store_true", help="Build PCA_2D + UMAP_2D + TSNE_2D") + + # ── edges ────────────────────────────────────────────────────────── + p_edges = sub.add_parser("edges", help="Compute KNN edge lists") + p_edges.add_argument("--model", default="UMAP_2D", help="Model preset (default: UMAP_2D)") + p_edges.add_argument("--feature-set", default="reinsertion_core", help="Feature set") + p_edges.add_argument("--k", type=int, default=5, help="Number of neighbors (default: 5)") + p_edges.add_argument("--mode", choices=["closest", "farthest"], default="closest") + p_edges.add_argument( + "--scope", choices=["cross_dataset", "within_dataset"], default="cross_dataset" + ) + p_edges.add_argument( + "--outdir", + default=None, + help="Artifacts output dir (default: $NODULEMAP_ARTIFACTS or $ITRIALSPACE_OUTPUT_DIR/nodulemap_artifacts)", + ) + p_edges.add_argument("--all-k", action="store_true", help="Build edges for k=3,5,10,25") + p_edges.add_argument( + "--space", + choices=["weighted", "feature_l2", "embedding"], + default="weighted", + help="Search space for edges (default: weighted = clinical ReinsertionMatcher metric)", + ) + + # ── serve ────────────────────────────────────────────────────────── + p_serve = sub.add_parser("serve", help="Start NoduleMap web server") + p_serve.add_argument( + "--artifact-dir", + default=None, + help="Artifacts dir (default: $NODULEMAP_ARTIFACTS or $ITRIALSPACE_OUTPUT_DIR/nodulemap_artifacts)", + ) + p_serve.add_argument("--host", default="0.0.0.0") + p_serve.add_argument("--port", type=int, default=8422) + p_serve.add_argument("--workers", type=int, default=1) + + # ── info ─────────────────────────────────────────────────────────── + p_info = sub.add_parser("info", help="Show available artifacts") + p_info.add_argument( + "--artifact-dir", + default=None, + help="Artifacts dir (default: $NODULEMAP_ARTIFACTS or $ITRIALSPACE_OUTPUT_DIR/nodulemap_artifacts)", + ) + + # ── query ────────────────────────────────────────────────────────── + p_query = sub.add_parser("query", help="Query neighbors offline") + p_query.add_argument("--node", required=True, help="Node ID (e.g. DLCS24_DLCS_0001_01)") + p_query.add_argument("--model", default="UMAP_2D") + p_query.add_argument("--feature-set", default="reinsertion_core") + p_query.add_argument("--k", type=int, default=10) + p_query.add_argument("--scope", default="cross_dataset") + p_query.add_argument( + "--search-backend", + choices=["weighted", "feature_l2", "embedding"], + default="weighted", + help="Similarity backend (default: weighted = clinical ReinsertionMatcher metric)", + ) + p_query.add_argument( + "--artifact-dir", + default=None, + help="Artifacts dir (default: $NODULEMAP_ARTIFACTS or $ITRIALSPACE_OUTPUT_DIR/nodulemap_artifacts)", + ) + p_query.add_argument("--json", action="store_true", help="Output as JSON") + + # ── export ───────────────────────────────────────────────────────── + p_export = sub.add_parser("export", help="Export neighbors for a node") + p_export.add_argument("--node", required=True, help="Node ID") + p_export.add_argument("--model", default="UMAP_2D") + p_export.add_argument("--feature-set", default="reinsertion_core") + p_export.add_argument("--k", type=int, default=10) + p_export.add_argument("--scope", default="cross_dataset") + p_export.add_argument( + "--search-backend", + choices=["weighted", "feature_l2", "embedding"], + default="weighted", + help="Similarity backend (default: weighted = clinical ReinsertionMatcher metric)", + ) + p_export.add_argument("--format", choices=["csv", "json", "donors"], default="csv") + p_export.add_argument( + "--artifact-dir", + default=None, + help="Artifacts dir (default: $NODULEMAP_ARTIFACTS or $ITRIALSPACE_OUTPUT_DIR/nodulemap_artifacts)", + ) + p_export.add_argument("-o", "--output-dir", default="./nodulemap_exports") + + args = parser.parse_args(argv) + + if not args.command: + parser.print_help() + sys.exit(1) + + # Resolve the artifact directory: explicit flag wins, else + # $NODULEMAP_ARTIFACTS, else $ITRIALSPACE_OUTPUT_DIR/nodulemap_artifacts. + from itrialspace.config import settings + + art_default = str(settings.nodulemap_artifacts_dir()) + for attr in ("outdir", "artifact_dir"): + if getattr(args, attr, None) is None: + setattr(args, attr, art_default) + + if args.command == "build": + _cmd_build(args) + elif args.command == "edges": + _cmd_edges(args) + elif args.command == "serve": + _cmd_serve(args) + elif args.command == "info": + _cmd_info(args) + elif args.command == "query": + _cmd_query(args) + elif args.command == "export": + _cmd_export(args) + + +# ── Command implementations ────────────────────────────────────────── + + +def _cmd_build(args): + from itrialspace.apps.nodulemap.embeddings.build_embeddings import EmbeddingBuilder + + builder = EmbeddingBuilder.from_defaults() + + if args.all_2d: + results = builder.build_all_2d(feature_set=args.feature_set, outdir=args.outdir) + for model, res in results.items(): + print(f"\n✓ {model}: {res['embeddings_shape']}") + else: + result = builder.build(args.model, args.feature_set, args.outdir) + print(f"\n✓ {args.model}: {result['embeddings_shape']}") + print(f" Artifacts: {args.outdir}") + + +def _cmd_edges(args): + from itrialspace.apps.nodulemap.neighbors.build_edges import EdgeBuilder + + eb = EdgeBuilder(args.outdir) + + if args.all_k: + paths = eb.build_multiple_k(args.model, args.feature_set, mode=args.mode, space=args.space) + print(f"\n✓ Built edges for k={[3,5,10,25]} (space={args.space})") + else: + path = eb.build( + args.model, + args.feature_set, + k=args.k, + mode=args.mode, + scope=args.scope, + space=args.space, + ) + print(f"\n✓ Edges saved: {path}") + + +def _cmd_serve(args): + import uvicorn + + os.environ["NODULEMAP_ARTIFACTS"] = args.artifact_dir + print(f"Starting NoduleMap server on {args.host}:{args.port}") + print(f" Artifacts: {args.artifact_dir}") + print(f" Open: http://localhost:{args.port}") + uvicorn.run( + "itrialspace.apps.nodulemap.backend.app:create_app", + factory=True, + host=args.host, + port=args.port, + workers=args.workers, + ) + + +def _cmd_info(args): + from pathlib import Path + + art_dir = Path(args.artifact_dir) + if not art_dir.exists(): + print(f"Artifact directory not found: {art_dir}") + sys.exit(1) + + # Find embedding files + emb_files = sorted(art_dir.glob("embeddings_*.npy")) + edge_files = sorted(art_dir.glob("edges_*.parquet")) + meta_files = sorted(art_dir.glob("metadata_*.parquet")) + + print(f"\niTrialSpace NoduleMap — Artifacts in {art_dir}") + print("=" * 60) + + if emb_files: + print(f"\nEmbeddings ({len(emb_files)}):") + for f in emb_files: + import numpy as np + + arr = np.load(f) + name = f.stem.replace("embeddings_", "") + print(f" {name}: {arr.shape[0]} nodes × {arr.shape[1]}D") + else: + print("\nNo embeddings found. Run: itrialspace-nodulemap build") + + if edge_files: + print(f"\nEdge lists ({len(edge_files)}):") + for f in edge_files: + import pandas as pd + + df = pd.read_parquet(f) + name = f.stem.replace("edges_", "") + print(f" {name}: {len(df):,} edges") + else: + print("\nNo edge lists found. Run: itrialspace-nodulemap edges") + + if meta_files: + print(f"\nMetadata ({len(meta_files)}):") + for f in meta_files: + import pandas as pd + + df = pd.read_parquet(f) + name = f.stem.replace("metadata_", "") + ds_counts = df["dataset"].value_counts() + print(f" {name}: {len(df):,} nodes across {len(ds_counts)} datasets") + + print() + + +def _cmd_query(args): + import json as jsonlib + + from itrialspace.apps.nodulemap.backend.data_store import DataStore + + ds = DataStore(args.artifact_dir, verbose=False) + results = ds.query_neighbors( + node_id=args.node, + model_name=args.model, + feature_set=args.feature_set, + k=args.k, + scope=args.scope, + search_backend=args.search_backend, + ) + + if args.json: + print(jsonlib.dumps(results, indent=2, default=str)) + else: + print(f"\nNeighbors for {args.node} (model={args.model}, k={args.k}, scope={args.scope})") + print("-" * 80) + print( + f"{'Rank':>4} {'Node ID':<30} {'Distance':>10} {'Similarity':>10} {'Diam':>6} {'Lobe'}" + ) + for r in results: + lobe = (r.get("reinsertion_lobe") or "—")[:20] + print( + f"{r['rank']:>4} {r['node_id']:<30} {r['distance']:>10.4f} {r['similarity']:>10.4f} {r.get('reinsertion_nodule_diam_mm', 0):>6.1f} {lobe}" + ) + + +def _cmd_export(args): + from itrialspace.apps.nodulemap.backend.data_store import DataStore + from itrialspace.apps.nodulemap.backend.export import Exporter + + ds = DataStore(args.artifact_dir, verbose=False) + exporter = Exporter(args.output_dir) + + query_node = ds.get_node(args.node, args.model, args.feature_set) + neighbors = ds.query_neighbors( + node_id=args.node, + model_name=args.model, + feature_set=args.feature_set, + k=args.k, + scope=args.scope, + search_backend=args.search_backend, + ) + + if args.format == "donors": + path = exporter.export_candidate_donors(neighbors) + else: + path = exporter.export_neighbors( + query_node=query_node, + neighbors=neighbors, + model_name=args.model, + feature_set=args.feature_set, + k=args.k, + scope=args.scope, + fmt=args.format, + ) + print(f"✓ Exported: {path}") + + +if __name__ == "__main__": + main() diff --git a/itrialspace/src/itrialspace/apps/nodulemap/client/__init__.py b/itrialspace/src/itrialspace/apps/nodulemap/client/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..61ac040d1a51b9fe096b3b1ba7c58f8d64c63ef2 --- /dev/null +++ b/itrialspace/src/itrialspace/apps/nodulemap/client/__init__.py @@ -0,0 +1,4 @@ +# -*- coding: utf-8 -*- +""" +nodulemap.client — Jupyter notebook helper for NoduleMap. +""" diff --git a/itrialspace/src/itrialspace/apps/nodulemap/client/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/apps/nodulemap/client/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9c48c68e4e52c4f1c64763ff335044d897b53656 Binary files /dev/null and b/itrialspace/src/itrialspace/apps/nodulemap/client/__pycache__/__init__.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/apps/nodulemap/client/__pycache__/notebook_client.cpython-310.pyc b/itrialspace/src/itrialspace/apps/nodulemap/client/__pycache__/notebook_client.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eb0a55a575ff374175c1a56c7e026fb373bf94f7 Binary files /dev/null and b/itrialspace/src/itrialspace/apps/nodulemap/client/__pycache__/notebook_client.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/apps/nodulemap/client/notebook_client.py b/itrialspace/src/itrialspace/apps/nodulemap/client/notebook_client.py new file mode 100644 index 0000000000000000000000000000000000000000..64f938531700395a3aee6a250b1a1c5b72d40e81 --- /dev/null +++ b/itrialspace/src/itrialspace/apps/nodulemap/client/notebook_client.py @@ -0,0 +1,417 @@ +# -*- coding: utf-8 -*- +""" +notebook_client.py — Jupyter helper for NoduleMap. + +Supports two modes: + A) Direct mode — loads artifacts in-process (no server needed) + B) API mode — queries a running NoduleMap backend + +Usage: + from itrialspace.apps.nodulemap.client.notebook_client import NoduleMapClient + + # Direct mode (load artifacts locally) + client = NoduleMapClient(artifact_dir="./nodulemap_artifacts") + + # API mode + client = NoduleMapClient(api_url="http://localhost:8422") + + # Explore + client.summary() + client.scatter_2d() + client.neighbors("DLCS24_DLCS_0001_01", k=10) + client.scatter_neighbors("DLCS24_DLCS_0001_01", k=10) +""" + +from __future__ import annotations + +import numpy as np +import pandas as pd + + +class NoduleMapClient: + """Jupyter-friendly NoduleMap client.""" + + def __init__( + self, + artifact_dir: str | None = None, + api_url: str | None = None, + feature_set: str = "reinsertion_core", + model: str = "UMAP_2D", + ): + self._api_url = api_url + self._artifact_dir = artifact_dir + self._feature_set = feature_set + self._model = model + self._store = None + + if artifact_dir and not api_url: + from itrialspace.apps.nodulemap.backend.data_store import DataStore + + self._store = DataStore(artifact_dir, verbose=False) + + def _api_get(self, path: str, params: dict | None = None): + """Make GET request to API.""" + import requests + + url = f"{self._api_url}{path}" + resp = requests.get(url, params=params, timeout=30) + resp.raise_for_status() + return resp.json() + + def _api_post(self, path: str, data: dict): + """Make POST request to API.""" + import requests + + url = f"{self._api_url}{path}" + resp = requests.post(url, json=data, timeout=30) + resp.raise_for_status() + return resp.json() + + # ── Summary ────────────────────────────────────────────────────────── + def summary(self) -> pd.DataFrame: + """Show summary of available models and node counts.""" + if self._store: + models = self._store.available_models + rows = [] + for m in models: + meta = self._store.get_metadata(m["model_name"], m["feature_set"]) + emb = self._store.get_embeddings(m["model_name"], m["feature_set"]) + rows.append( + { + "model": m["model_name"], + "feature_set": m["feature_set"], + "n_nodes": len(meta), + "n_dims": emb.shape[1], + "datasets": ", ".join(sorted(meta["dataset"].unique())), + } + ) + return pd.DataFrame(rows) + else: + data = self._api_get("/api/models") + return pd.DataFrame(data["models"]) + + # ── Metadata ────────────────────────────────────────────────────────── + def metadata(self, model: str | None = None, feature_set: str | None = None) -> pd.DataFrame: + """Get the metadata DataFrame.""" + m = model or self._model + fs = feature_set or self._feature_set + if self._store: + return self._store.get_metadata(m, fs) + else: + # API doesn't serve full metadata directly; use graph endpoint + data = self._api_post( + "/api/graph", + { + "vis_model": m, + "search_model": m, + "feature_set": fs, + "k": 0, + "mode": "closest", + }, + ) + return pd.DataFrame(data["nodes"]) + + # ── Node detail ────────────────────────────────────────────────────── + def node(self, node_id: str) -> dict: + """Get full metadata for a node.""" + if self._store: + return self._store.get_node(node_id, self._model, self._feature_set) + else: + return self._api_get( + f"/api/node/{node_id}", {"model": self._model, "feature_set": self._feature_set} + ) + + # ── Neighbors ──────────────────────────────────────────────────────── + def neighbors( + self, + node_id: str, + k: int = 10, + model: str | None = None, + scope: str = "cross_dataset", + datasets: list[str] | None = None, + balance_by_dataset: bool = False, + ) -> pd.DataFrame: + """Query K nearest neighbors, return as DataFrame.""" + m = model or self._model + if self._store: + results = self._store.query_neighbors( + node_id=node_id, + model_name=m, + feature_set=self._feature_set, + k=k, + scope=scope, + datasets=datasets, + balance_by_dataset=balance_by_dataset, + ) + else: + params = { + "model": m, + "feature_set": self._feature_set, + "k": k, + "scope": scope, + "balance_by_dataset": balance_by_dataset, + } + if datasets: + params["datasets"] = ",".join(datasets) + data = self._api_get(f"/api/node/{node_id}/neighbors", params) + results = data["neighbors"] + + if not results: + return pd.DataFrame() + + df = pd.DataFrame(results) + cols = [ + "rank", + "node_id", + "dataset", + "similarity", + "distance", + "reinsertion_nodule_diam_mm", + "reinsertion_lobe", + "label_text", + ] + cols = [c for c in cols if c in df.columns] + return df[cols] + + # ── 2D Scatter Plot ────────────────────────────────────────────────── + def scatter_2d( + self, + color_by: str = "dataset", + model: str | None = None, + figsize: tuple = (12, 8), + alpha: float = 0.5, + s: int = 5, + filters: dict | None = None, + ): + """ + Plot 2D embedding scatter (matplotlib). + + Args: + color_by: Column to color nodes by (dataset, label_text, reinsertion_lobe, etc.) + model: 2D model to use (default: UMAP_2D) + figsize: Figure size + alpha: Point opacity + s: Point size + filters: Optional filter dict + """ + import matplotlib.pyplot as plt + + m = model or self._model + + if self._store: + meta = self._store.get_metadata(m, self._feature_set) + pos = self._store.get_positions(m, self._feature_set) + + if filters: + mask = self._store._apply_filters(meta, filters) + meta = meta[mask].reset_index(drop=True) + pos = pos[mask] + else: + data = self._api_post( + "/api/graph", + { + "vis_model": m, + "search_model": m, + "feature_set": self._feature_set, + "k": 0, + "color_by": color_by, + "filters": filters, + }, + ) + nodes = data["nodes"] + meta = pd.DataFrame(nodes) + pos = np.column_stack([meta["x"].values, meta["y"].values]) + + # Color mapping + PALETTES = { + "dataset": { + "DLCS24": "#4a9eff", + "LUNA25": "#f97316", + "LUNA16": "#10b981", + "LUNGx": "#ef4444", + "LNDbv4": "#a855f7", + "NSCLCR": "#ec4899", + "IMDCT": "#06b6d4", + }, + "label_text": {"malignant": "#ef4444", "benign": "#10b981", "unlabelled": "#888888"}, + } + pal = PALETTES.get(color_by, {}) + + if color_by in meta.columns: + groups = meta[color_by].fillna("unknown").values + else: + groups = np.full(len(meta), "unknown") + + unique_groups = sorted(set(groups)) + cmap = plt.cm.get_cmap("tab20", len(unique_groups)) + + fig, ax = plt.subplots(figsize=figsize, facecolor="#0f1117") + ax.set_facecolor("#0f1117") + + for i, g in enumerate(unique_groups): + mask = groups == g + color = pal.get(g, cmap(i)) + ax.scatter( + pos[mask, 0], + pos[mask, 1], + c=[color], + label=str(g), + s=s, + alpha=alpha, + edgecolors="none", + ) + + ax.legend( + fontsize=8, loc="upper right", framealpha=0.5, labelcolor="white", facecolor="#22262f" + ) + ax.set_title(f"NoduleMap — {m} colored by {color_by}", color="white", fontsize=12) + ax.tick_params(colors="#666") + for spine in ax.spines.values(): + spine.set_color("#333") + plt.tight_layout() + plt.show() + return fig + + # ── Neighbor Scatter ───────────────────────────────────────────────── + def scatter_neighbors( + self, + node_id: str, + k: int = 10, + model: str | None = None, + figsize: tuple = (10, 7), + ): + """Plot a node and its K neighbors on the 2D map.""" + import matplotlib.pyplot as plt + + m = model or self._model + nb_df = self.neighbors(node_id, k=k, model=m) + + if self._store: + meta = self._store.get_metadata(m, self._feature_set) + pos = self._store.get_positions(m, self._feature_set) + else: + data = self._api_post( + "/api/graph", + { + "vis_model": m, + "search_model": m, + "feature_set": self._feature_set, + "k": 0, + }, + ) + nodes = data["nodes"] + meta = pd.DataFrame(nodes) + pos = np.column_stack([meta["x"].values, meta["y"].values]) + + # Find indices + node_ids = meta["node_id"].values if "node_id" in meta.columns else meta["id"].values + query_idx = np.where(node_ids == node_id)[0] + nb_ids = set(nb_df["node_id"].values) if "node_id" in nb_df.columns else set() + nb_mask = np.isin(node_ids, list(nb_ids)) + + fig, ax = plt.subplots(figsize=figsize, facecolor="#0f1117") + ax.set_facecolor("#0f1117") + + # All nodes (faded) + ax.scatter(pos[:, 0], pos[:, 1], c="#333", s=2, alpha=0.2) + # Neighbors (highlighted) + ax.scatter( + pos[nb_mask, 0], + pos[nb_mask, 1], + c="#4a9eff", + s=30, + alpha=0.8, + edgecolors="white", + linewidths=0.5, + zorder=3, + label="Neighbors", + ) + # Query node (star) + if len(query_idx) > 0: + qi = query_idx[0] + ax.scatter( + pos[qi, 0], + pos[qi, 1], + c="#ef4444", + s=100, + marker="*", + edgecolors="white", + linewidths=1, + zorder=4, + label=node_id, + ) + # Draw lines to neighbors + for ni in np.where(nb_mask)[0]: + ax.plot( + [pos[qi, 0], pos[ni, 0]], + [pos[qi, 1], pos[ni, 1]], + c="#4a9eff", + alpha=0.3, + linewidth=0.5, + ) + + ax.legend(fontsize=8, labelcolor="white", facecolor="#22262f", framealpha=0.7) + ax.set_title(f"Neighbors of {node_id} (k={k})", color="white", fontsize=11) + ax.tick_params(colors="#666") + for spine in ax.spines.values(): + spine.set_color("#333") + plt.tight_layout() + plt.show() + return fig + + # ── Filters ────────────────────────────────────────────────────────── + def filters(self) -> dict: + """Get available filter values.""" + if self._api_url: + return self._api_get("/api/filters") + elif self._store: + meta = self._store.get_metadata(self._model, self._feature_set) + return { + "datasets": sorted(meta["dataset"].unique().tolist()), + "lobes": sorted(meta["reinsertion_lobe"].dropna().unique().tolist()), + "zones": sorted(meta["reinsertion_lung_zone"].dropna().unique().tolist()), + "sides": sorted(meta["reinsertion_lung_side"].dropna().unique().tolist()), + } + return {} + + # ── Export ────────────────────────────────────────────────────────── + def export_neighbors( + self, + node_id: str, + k: int = 10, + fmt: str = "csv", + output_dir: str = "./nodulemap_exports", + ) -> str: + """Export a node's neighbors to file.""" + if self._api_url: + data = self._api_post( + "/api/export", + { + "node_id": node_id, + "model": self._model, + "feature_set": self._feature_set, + "k": k, + "format": fmt, + }, + ) + return data.get("path", "") + else: + from itrialspace.apps.nodulemap.backend.export import Exporter + + exporter = Exporter(output_dir) + query_node = self._store.get_node(node_id, self._model, self._feature_set) + nbs = self._store.query_neighbors( + node_id=node_id, + model_name=self._model, + feature_set=self._feature_set, + k=k, + ) + return exporter.export_neighbors( + query_node, + nbs, + self._model, + self._feature_set, + k, + "cross_dataset", + fmt, + ) diff --git a/itrialspace/src/itrialspace/apps/nodulemap/configs/features.yaml b/itrialspace/src/itrialspace/apps/nodulemap/configs/features.yaml new file mode 100644 index 0000000000000000000000000000000000000000..48adfc5a1faed648be9a4374f5fcfdd15455b0e8 --- /dev/null +++ b/itrialspace/src/itrialspace/apps/nodulemap/configs/features.yaml @@ -0,0 +1,111 @@ +# Feature-set definitions for NoduleMap embeddings. +# Each feature set defines the columns used, their types, and preprocessing. + +feature_sets: + + # ── reinsertion_core ────────────────────────────────────────────────────── + # Safe default: uses only reinsertion_* columns (100% complete, no NaNs). + reinsertion_core: + description: "Reinsertion-only features — no NaNs, 12 columns" + numeric: + - reinsertion_lobe_cc_pct + - reinsertion_lobe_ml_pct + - reinsertion_lobe_ap_pct + - reinsertion_lung_cc_pct + - reinsertion_lung_ml_pct + - reinsertion_lung_ap_pct + - reinsertion_pleural_dist_mm + - reinsertion_airway_dist_mm + - reinsertion_nodule_diam_mm + categorical: + - reinsertion_lobe + - reinsertion_lung_side + - reinsertion_lung_zone + scaler: standard # standard | robust + imputer: none # none | median | mean + + # ── core_53 ─────────────────────────────────────────────────────────────── + # Full 53-column profile: anatomy, distances, inter-nodule, reinsertion. + # May contain NaNs in non-reinsertion columns. + core_53: + description: "All 53 core pipeline features — requires imputation" + numeric: + - nodule_mean_diam_mm + - nodule_vol_mm3 + - cranio_caudal_pct + - mediolateral_pct + - anteroposterior_pct + - lobe_cc_pct + - lobe_ml_pct + - lobe_ap_pct + - dist_to_trachea_mm + - dist_to_aorta_mm + - dist_to_heart_mm + - dist_to_esophagus_mm + - dist_to_pulmonary_vein_mm + - dist_to_superior_vena_cava_mm + - pleural_distance_mm + - airway_distance_mm + - n_nodules_in_patient + - nearest_nodule_dist_mm + - nearest_dx_mm + - nearest_dy_mm + - nearest_dz_mm + - reinsertion_lobe_cc_pct + - reinsertion_lobe_ml_pct + - reinsertion_lobe_ap_pct + - reinsertion_lung_cc_pct + - reinsertion_lung_ml_pct + - reinsertion_lung_ap_pct + - reinsertion_pleural_dist_mm + - reinsertion_airway_dist_mm + - reinsertion_nodule_diam_mm + categorical: + - lobe_name + - lung_side + - lung_zone + - central_peripheral + - reinsertion_lobe + - reinsertion_lung_side + - reinsertion_lung_zone + scaler: robust + imputer: median + +# ── Embedding model presets ──────────────────────────────────────────────── +models: + + PCA_2D: + algorithm: pca + n_components: 2 + + PCA_32: + algorithm: pca + n_components: 32 + + UMAP_2D: + algorithm: umap + n_components: 2 + n_neighbors: 30 + min_dist: 0.3 + metric: euclidean + + UMAP_16: + algorithm: umap + n_components: 16 + n_neighbors: 30 + min_dist: 0.1 + metric: euclidean + + UMAP_32: + algorithm: umap + n_components: 32 + n_neighbors: 30 + min_dist: 0.1 + metric: euclidean + + TSNE_2D: + algorithm: tsne + n_components: 2 + perplexity: 30 + learning_rate: auto + n_iter: 1000 diff --git a/itrialspace/src/itrialspace/apps/nodulemap/embeddings/__init__.py b/itrialspace/src/itrialspace/apps/nodulemap/embeddings/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c4c9bac00efc7b7a201e4ec4fb070019d49af48b --- /dev/null +++ b/itrialspace/src/itrialspace/apps/nodulemap/embeddings/__init__.py @@ -0,0 +1,10 @@ +# -*- coding: utf-8 -*- +""" +nodulemap.embeddings — feature preprocessing + embedding generation. + +Supports: + - Feature-set selection (reinsertion_core / core_53) + - Preprocessing (scaling + one-hot + imputation) + - Multiple embedding algorithms (PCA, UMAP, t-SNE) + - Artifact persistence (embeddings, 2D positions, metadata) +""" diff --git a/itrialspace/src/itrialspace/apps/nodulemap/embeddings/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/apps/nodulemap/embeddings/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b0e5acb75163dca493eebd5493c190d7ea0008cd Binary files /dev/null and b/itrialspace/src/itrialspace/apps/nodulemap/embeddings/__pycache__/__init__.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/apps/nodulemap/embeddings/__pycache__/build_embeddings.cpython-310.pyc b/itrialspace/src/itrialspace/apps/nodulemap/embeddings/__pycache__/build_embeddings.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8fa40a704eca6fe3ac8a6720de416e2ac3ddd7c5 Binary files /dev/null and b/itrialspace/src/itrialspace/apps/nodulemap/embeddings/__pycache__/build_embeddings.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/apps/nodulemap/embeddings/build_embeddings.py b/itrialspace/src/itrialspace/apps/nodulemap/embeddings/build_embeddings.py new file mode 100644 index 0000000000000000000000000000000000000000..1f90e329352ac515e174bead2fe3e4325535b20b --- /dev/null +++ b/itrialspace/src/itrialspace/apps/nodulemap/embeddings/build_embeddings.py @@ -0,0 +1,390 @@ +# -*- coding: utf-8 -*- +""" +build_embeddings.py — generate embeddings from nodule profile features. + +Usage (CLI): + itrialspace-nodulemap build --model UMAP_2D --feature-set reinsertion_core --outdir ./artifacts + +Programmatic: + from itrialspace.apps.nodulemap.embeddings.build_embeddings import EmbeddingBuilder + builder = EmbeddingBuilder.from_defaults() + builder.build("UMAP_2D", "reinsertion_core", outdir="./artifacts") +""" + +from __future__ import annotations + +import pickle +import time +from pathlib import Path +from typing import Optional + +import numpy as np +import pandas as pd +import yaml +from sklearn.compose import ColumnTransformer +from sklearn.impute import SimpleImputer +from sklearn.pipeline import Pipeline +from sklearn.preprocessing import OneHotEncoder, RobustScaler, StandardScaler + +_CONFIG_DIR = Path(__file__).parent.parent / "configs" + + +def _load_config() -> dict: + """Load features.yaml config.""" + cfg_path = _CONFIG_DIR / "features.yaml" + with open(cfg_path) as f: + return yaml.safe_load(f) + + +class FeaturePreprocessor: + """Preprocesses raw profile DataFrame into a numeric feature matrix.""" + + def __init__( + self, + numeric_cols: list[str], + categorical_cols: list[str], + scaler_type: str = "standard", + imputer_strategy: str = "none", + ): + self.numeric_cols = numeric_cols + self.categorical_cols = categorical_cols + self.scaler_type = scaler_type + self.imputer_strategy = imputer_strategy + self._pipeline: Optional[ColumnTransformer] = None + self._feature_names: list[str] = [] + + def fit_transform(self, df: pd.DataFrame) -> np.ndarray: + """Fit preprocessor and transform data. Returns (n_samples, n_features).""" + # Build numeric sub-pipeline + num_steps = [] + if self.imputer_strategy != "none": + num_steps.append(("impute", SimpleImputer(strategy=self.imputer_strategy))) + if self.scaler_type == "robust": + num_steps.append(("scale", RobustScaler())) + else: + num_steps.append(("scale", StandardScaler())) + num_pipe = Pipeline(num_steps) if num_steps else "passthrough" + + # Build categorical sub-pipeline + cat_pipe = ( + OneHotEncoder(sparse_output=False, handle_unknown="ignore", drop=None) + if self.categorical_cols + else "passthrough" + ) + + transformers = [] + if self.numeric_cols: + transformers.append(("num", num_pipe, self.numeric_cols)) + if self.categorical_cols: + transformers.append(("cat", cat_pipe, self.categorical_cols)) + + self._pipeline = ColumnTransformer(transformers, remainder="drop") + + # Replace inf values with NaN for imputation + sub = df[self.numeric_cols + self.categorical_cols].copy() + for c in self.numeric_cols: + sub[c] = pd.to_numeric(sub[c], errors="coerce") + sub[c] = sub[c].replace([np.inf, -np.inf], np.nan) + + X = self._pipeline.fit_transform(sub) + + # Store feature names + self._feature_names = self._get_feature_names() + return X.astype(np.float32) + + def transform(self, df: pd.DataFrame) -> np.ndarray: + """Transform new data with fitted preprocessor.""" + if self._pipeline is None: + raise RuntimeError("Preprocessor not fitted. Call fit_transform first.") + sub = df[self.numeric_cols + self.categorical_cols].copy() + for c in self.numeric_cols: + sub[c] = pd.to_numeric(sub[c], errors="coerce") + sub[c] = sub[c].replace([np.inf, -np.inf], np.nan) + return self._pipeline.transform(sub).astype(np.float32) + + def _get_feature_names(self) -> list[str]: + """Extract feature names after fit.""" + names = [] + if self._pipeline is None: + return names + for name, trans, cols in self._pipeline.transformers_: + if name == "num": + names.extend(self.numeric_cols) + elif name == "cat": + if hasattr(trans, "get_feature_names_out"): + names.extend(trans.get_feature_names_out(self.categorical_cols).tolist()) + else: + names.extend(self.categorical_cols) + return names + + @property + def feature_names(self) -> list[str]: + return self._feature_names + + +class EmbeddingBuilder: + """Orchestrates embedding generation from NoduleIndex.""" + + def __init__(self, df: pd.DataFrame, verbose: bool = True): + self._df = df + self._verbose = verbose + self._config = _load_config() + + @classmethod + def from_defaults(cls, verbose: bool = True) -> "EmbeddingBuilder": + """Load NoduleIndex from default registry.""" + from itrialspace.index.nodule_index import NoduleIndex + from itrialspace.io.registry import DatasetRegistry + + # Resolve the dataset registry portably via itrialspace.config.settings + # (local configs/datasets.yaml → shipped datasets.example.yaml → package default). + registry = DatasetRegistry.from_yaml() + if verbose: + print("Loading NoduleIndex …") + idx = NoduleIndex.from_registry(registry, verbose=verbose) + return cls(idx.df, verbose=verbose) + + def _log(self, msg: str) -> None: + if self._verbose: + print(f" [{time.strftime('%H:%M:%S')}] {msg}") + + def list_feature_sets(self) -> list[str]: + return list(self._config.get("feature_sets", {}).keys()) + + def list_models(self) -> list[str]: + return list(self._config.get("models", {}).keys()) + + def build( + self, + model_name: str, + feature_set: str = "reinsertion_core", + outdir: str = "./nodulemap_artifacts", + random_state: int = 42, + ) -> dict: + """ + Build embeddings and save artifacts. + + Returns dict with keys: embeddings, positions_2d (if 2D), metadata_path, etc. + """ + outdir = Path(outdir) + outdir.mkdir(parents=True, exist_ok=True) + + # ── Load feature set config ───────────────────────────────────────── + fs_cfg = self._config["feature_sets"].get(feature_set) + if fs_cfg is None: + raise ValueError( + f"Unknown feature_set '{feature_set}'. Available: {self.list_feature_sets()}" + ) + + model_cfg = self._config["models"].get(model_name) + if model_cfg is None: + raise ValueError(f"Unknown model '{model_name}'. Available: {self.list_models()}") + + self._log(f"Feature set: {feature_set} ({fs_cfg['description']})") + self._log(f"Model: {model_name} ({model_cfg['algorithm']}, {model_cfg['n_components']}D)") + + # ── Preprocess ────────────────────────────────────────────────────── + self._log("Preprocessing features …") + preprocessor = FeaturePreprocessor( + numeric_cols=fs_cfg["numeric"], + categorical_cols=fs_cfg.get("categorical", []), + scaler_type=fs_cfg.get("scaler", "standard"), + imputer_strategy=fs_cfg.get("imputer", "none"), + ) + X = preprocessor.fit_transform(self._df) + self._log(f"Feature matrix: {X.shape}") + + # Handle remaining NaNs (safety net) + nan_mask = np.isnan(X).any(axis=1) + if nan_mask.any(): + n_bad = nan_mask.sum() + self._log(f"WARNING: {n_bad} rows have NaN after preprocessing — filling with 0") + X = np.nan_to_num(X, nan=0.0) + + # ── Build embedding ───────────────────────────────────────────────── + algo = model_cfg["algorithm"] + n_comp = model_cfg["n_components"] + self._log(f"Computing {algo.upper()} embedding …") + t0 = time.time() + + if algo == "pca": + from sklearn.decomposition import PCA + + actual_comp = min(n_comp, X.shape[1], X.shape[0]) + if actual_comp < n_comp: + self._log( + f"NOTE: capping PCA n_components {n_comp} → {actual_comp} " + f"(input has {X.shape[1]} features)" + ) + reducer = PCA(n_components=actual_comp, random_state=random_state) + embeddings = reducer.fit_transform(X) + + elif algo == "umap": + import umap + + reducer = umap.UMAP( + n_components=n_comp, + n_neighbors=model_cfg.get("n_neighbors", 30), + min_dist=model_cfg.get("min_dist", 0.3), + metric=model_cfg.get("metric", "euclidean"), + random_state=random_state, + verbose=self._verbose, + ) + embeddings = reducer.fit_transform(X) + + elif algo == "tsne": + import inspect + + from sklearn.manifold import TSNE + + tsne_params = inspect.signature(TSNE.__init__).parameters + # sklearn >= 1.6 renamed n_iter → max_iter + iter_key = "max_iter" if "max_iter" in tsne_params else "n_iter" + tsne_kwargs = dict( + n_components=n_comp, + perplexity=model_cfg.get("perplexity", 30), + learning_rate=model_cfg.get("learning_rate", "auto"), + random_state=random_state, + verbose=1 if self._verbose else 0, + ) + tsne_kwargs[iter_key] = model_cfg.get("n_iter", 1000) + reducer = TSNE(**tsne_kwargs) + embeddings = reducer.fit_transform(X) + + else: + raise ValueError(f"Unknown algorithm: {algo}") + + elapsed = time.time() - t0 + self._log(f"Embedding shape: {embeddings.shape} ({elapsed:.1f}s)") + + # ── Save artifacts ────────────────────────────────────────────────── + tag = f"{feature_set}__{model_name}" + + # 1) Embeddings matrix + emb_path = outdir / f"embeddings_{tag}.npy" + np.save(emb_path, embeddings.astype(np.float32)) + self._log(f"Saved embeddings → {emb_path}") + + # 1b) Standardized feature matrix (per feature_set, reduced-free) — this is the + # faithful space for similarity SEARCH (see neighbors/search_space.py). It is the + # same across all models of a feature_set, so it is written once per feature_set. + feat_path = outdir / f"features_{feature_set}.npy" + np.save(feat_path, X.astype(np.float32)) + self._log(f"Saved feature matrix → {feat_path} {X.shape}") + + # 2) Node metadata table (parquet) + meta_cols = [ + "dataset", + "annotation_id", + "patient_id", + "label", + "nodule_mean_diam_mm", + "reinsertion_lobe", + "reinsertion_lung_side", + "reinsertion_lung_zone", + "reinsertion_pleural_dist_mm", + "reinsertion_airway_dist_mm", + "reinsertion_nodule_diam_mm", + "reinsertion_lobe_cc_pct", + "reinsertion_lobe_ml_pct", + "reinsertion_lobe_ap_pct", + "reinsertion_lung_cc_pct", + "reinsertion_lung_ml_pct", + "reinsertion_lung_ap_pct", + "ct_path", + "coordX", + "coordY", + "coordZ", + ] + # Add optional columns that may exist + optional = [ + "n_nodules_in_patient", + "lobe_name", + "lung_side", + "lung_zone", + "central_peripheral", + "pleural_distance_mm", + "airway_distance_mm", + ] + for c in optional: + if c in self._df.columns and c not in meta_cols: + meta_cols.append(c) + + # Add label metadata if present + for c in ["label_source", "population_type"]: + if c in self._df.columns: + meta_cols.append(c) + + available_cols = [c for c in meta_cols if c in self._df.columns] + meta_df = self._df[available_cols].copy().reset_index(drop=True) + + # Generate unique node ID: {dataset}_{annotation_id} + meta_df.insert( + 0, "node_id", meta_df["dataset"] + "_" + meta_df["annotation_id"].astype(str) + ) + + # Add size bucket + bins = [0, 5, 10, 15, 20, 30, 1000] + labels = ["<5mm", "5-10mm", "10-15mm", "15-20mm", "20-30mm", ">30mm"] + diam_col = ( + "reinsertion_nodule_diam_mm" + if "reinsertion_nodule_diam_mm" in meta_df.columns + else "nodule_mean_diam_mm" + ) + meta_df["size_bucket"] = pd.cut( + meta_df[diam_col].fillna(0), bins=bins, labels=labels + ).astype(str) + + # Add label text + meta_df["label_text"] = ( + meta_df["label"].map({0: "benign", 1: "malignant"}).fillna("unlabelled") + ) + + meta_path = outdir / f"metadata_{tag}.parquet" + meta_df.to_parquet(meta_path, index=False) + self._log(f"Saved metadata → {meta_path} ({len(meta_df)} rows)") + + # 3) Preprocessor pickle + prep_path = outdir / f"preprocessor_{tag}.pkl" + with open(prep_path, "wb") as f: + pickle.dump(preprocessor, f) + self._log(f"Saved preprocessor → {prep_path}") + + # 4) Model config record + info = { + "model_name": model_name, + "feature_set": feature_set, + "algorithm": algo, + "n_components": n_comp, + "n_samples": len(meta_df), + "n_input_features": X.shape[1], + "elapsed_seconds": round(elapsed, 2), + "feature_names": preprocessor.feature_names, + "model_config": model_cfg, + "feature_set_config": fs_cfg, + } + info_path = outdir / f"info_{tag}.yaml" + with open(info_path, "w") as f: + yaml.safe_dump(info, f, sort_keys=False) + self._log(f"Saved info → {info_path}") + + return { + "embeddings_path": str(emb_path), + "metadata_path": str(meta_path), + "preprocessor_path": str(prep_path), + "info_path": str(info_path), + "embeddings_shape": embeddings.shape, + "n_nodes": len(meta_df), + } + + def build_all_2d( + self, + feature_set: str = "reinsertion_core", + outdir: str = "./nodulemap_artifacts", + ) -> dict: + """Build PCA_2D + UMAP_2D + TSNE_2D for a given feature set.""" + results = {} + for model in ["PCA_2D", "UMAP_2D", "TSNE_2D"]: + self._log(f"\n{'='*60}\nBuilding {model} …\n{'='*60}") + results[model] = self.build(model, feature_set, outdir) + return results diff --git a/itrialspace/src/itrialspace/apps/nodulemap/frontend/__init__.py b/itrialspace/src/itrialspace/apps/nodulemap/frontend/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6ece2ae8f8be7fddb90f5daccf6a92df1c0d9b7a --- /dev/null +++ b/itrialspace/src/itrialspace/apps/nodulemap/frontend/__init__.py @@ -0,0 +1,2 @@ +# -*- coding: utf-8 -*- +"""Allow `from itrialspace.apps.nodulemap.frontend import *` — no-op package.""" diff --git a/itrialspace/src/itrialspace/apps/nodulemap/frontend/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/apps/nodulemap/frontend/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..74fd2abaec31aa832bf42b22b016d2adf7474623 Binary files /dev/null and b/itrialspace/src/itrialspace/apps/nodulemap/frontend/__pycache__/__init__.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/apps/nodulemap/frontend/static/index.html b/itrialspace/src/itrialspace/apps/nodulemap/frontend/static/index.html new file mode 100644 index 0000000000000000000000000000000000000000..95e2ef45e575c53204e6e7e0d47732a3bf50e322 --- /dev/null +++ b/itrialspace/src/itrialspace/apps/nodulemap/frontend/static/index.html @@ -0,0 +1,1280 @@ + + + + + +iTrialSpace · NoduleMap + + + + + + + +
+
+
Loading NoduleMap …
+
+ + +
+
+ +
+
iTrialSpace·NoduleMap
+
Anonymized Lab · Dept. of [Anonymized] · [Anonymized Institution]
+
+
+
Donor nodule explorer & reinsertion matching
+
+
+ + v0.1.0 + About +
+
+ + +
+ + + + + +
+
+ + + + + + +
+
Loading…
+
+
+
+
+
+
+
+
+ + + + +
+ + +
+ ⚠ For research use only — not for clinical use. +
+ + +
+
+

iTrialSpace · NoduleMap

+
Anonymized Lab · Dept. of [Anonymized] · [Anonymized Institution]
+

An interactive explorer for the iTrialSpace donor nodule library. Each point is a + lung nodule placed by a 2-D embedding of its anatomy-aware reinsertion features; click a + node to see its CT thumbnail, full metadata, and the best-matching donor nodules for + reinsertion.

+
+
13,140nodules
+
7datasets
+
L1weighted donor metric
+
+

Similarity: donor ranking uses the clinical ReinsertionMatcher metric + (lobe + craniocaudal position + pleural distance + diameter) on the full feature space — + the 2-D map is for layout only.

+

Repository: [Repository link removed for blinded review]

+

Citation: see CITATION.cff in the iTrialSpace repository. +

+
⚠ Research use only. NoduleMap and the synthetic data it + explores are for research and method development. Not for clinical use and not a + medical device.
+
+ +
+
+
+ + + + + + + + + + + diff --git a/itrialspace/src/itrialspace/apps/nodulemap/neighbors/__init__.py b/itrialspace/src/itrialspace/apps/nodulemap/neighbors/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f7eb7ec58c8f7b83db7132a764bdec2018b54477 --- /dev/null +++ b/itrialspace/src/itrialspace/apps/nodulemap/neighbors/__init__.py @@ -0,0 +1,4 @@ +# -*- coding: utf-8 -*- +""" +nodulemap.neighbors — KNN index + edge list computation. +""" diff --git a/itrialspace/src/itrialspace/apps/nodulemap/neighbors/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/apps/nodulemap/neighbors/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b74ba2a63da33f36d137e83bab6e2c12378b91e Binary files /dev/null and b/itrialspace/src/itrialspace/apps/nodulemap/neighbors/__pycache__/__init__.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/apps/nodulemap/neighbors/__pycache__/build_edges.cpython-310.pyc b/itrialspace/src/itrialspace/apps/nodulemap/neighbors/__pycache__/build_edges.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1d99ff9e929e346a4da0837f75137d87fe9bc007 Binary files /dev/null and b/itrialspace/src/itrialspace/apps/nodulemap/neighbors/__pycache__/build_edges.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/apps/nodulemap/neighbors/__pycache__/search_space.cpython-310.pyc b/itrialspace/src/itrialspace/apps/nodulemap/neighbors/__pycache__/search_space.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..874e0f62a5f83fd2836c7bc3ec04f7151b4868fc Binary files /dev/null and b/itrialspace/src/itrialspace/apps/nodulemap/neighbors/__pycache__/search_space.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/apps/nodulemap/neighbors/build_edges.py b/itrialspace/src/itrialspace/apps/nodulemap/neighbors/build_edges.py new file mode 100644 index 0000000000000000000000000000000000000000..09d51d443d86ce6e4a0361db7e1b12e526b6bb08 --- /dev/null +++ b/itrialspace/src/itrialspace/apps/nodulemap/neighbors/build_edges.py @@ -0,0 +1,167 @@ +# -*- coding: utf-8 -*- +""" +build_edges.py — compute KNN edge lists for the NoduleMap graph. + +Edges encode *similarity in the SEARCH space*, not the 2D layout. The space is selectable +(see neighbors/search_space.py): + + - ``weighted`` (default) clinical donor-matching metric (L1), matches ReinsertionMatcher + - ``feature_l2`` exact L2 on the standardized full feature vector + - ``embedding`` L2 on the reduced embedding (legacy; comparison only) + +Edge files keep the per-(feature_set, model) name the DataStore expects; only their *content* +changes with ``--space``. Uses FAISS (exact) or sklearn fallback. + +Usage (CLI): + itrialspace-nodulemap edges --model UMAP_2D --feature-set reinsertion_core \\ + --k 5 --space weighted --outdir ./nodulemap_artifacts +""" + +from __future__ import annotations + +import time +from pathlib import Path +from typing import Literal + +import numpy as np +import pandas as pd + +from itrialspace.apps.nodulemap.neighbors import search_space + + +class EdgeBuilder: + """Build KNN edge lists from saved artifacts, in a selectable search space.""" + + def __init__(self, artifact_dir: str, verbose: bool = True): + self._dir = Path(artifact_dir) + self._verbose = verbose + + def _log(self, msg: str) -> None: + if self._verbose: + print(f" [{time.strftime('%H:%M:%S')}] {msg}") + + def build( + self, + model_name: str, + feature_set: str = "reinsertion_core", + k: int = 5, + mode: Literal["closest", "farthest"] = "closest", + scope: Literal["cross_dataset", "within_dataset"] = "cross_dataset", + space: str = "weighted", + ) -> str: + """Build edge list and save to parquet. Returns output path.""" + tag = f"{feature_set}__{model_name}" + + # Metadata (node_id, dataset + reinsertion_* needed by the weighted space) + meta_path = self._dir / f"metadata_{tag}.parquet" + if not meta_path.exists(): + raise FileNotFoundError(f"Metadata not found: {meta_path}") + meta = pd.read_parquet(meta_path) + + matrix = search_space.build_search_matrix(space, self._dir, feature_set, model_name, meta) + metric = search_space.metric_for(space) + assert len(meta) == matrix.shape[0], "Metadata/matrix length mismatch" + self._log(f"Search space '{space}' (metric={metric}) matrix: {matrix.shape}") + + if scope == "within_dataset": + edges = self._build_within_dataset(matrix, meta, k, mode, metric) + else: + edges = self._build_cross_dataset(matrix, meta, k, mode, metric) + + out_name = f"edges_{tag}_k{k}_{mode}_{scope}.parquet" + out_path = self._dir / out_name + edges.to_parquet(out_path, index=False) + self._log(f"Saved {len(edges)} edges → {out_path}") + return str(out_path) + + def _build_cross_dataset(self, matrix, meta, k, mode, metric) -> pd.DataFrame: + """All-vs-all KNN search.""" + n = matrix.shape[0] + actual_k = min(k + 1, n) # +1 because the query includes self + self._log(f"Cross-dataset KNN (k={k}, mode={mode}, n={n}) …") + t0 = time.time() + if mode == "farthest": + distances, indices = self._farthest_neighbors_brute(matrix, actual_k, metric) + else: + distances, indices = search_space.knn(matrix, matrix, actual_k, metric) + self._log(f"KNN search done in {time.time() - t0:.1f}s") + return self._to_edge_df(meta, indices, distances, k, mode) + + def _build_within_dataset(self, matrix, meta, k, mode, metric) -> pd.DataFrame: + """Per-dataset KNN search.""" + all_edges = [] + for ds in meta["dataset"].unique(): + mask = meta["dataset"].values == ds + idx_map = np.where(mask)[0] + sub = matrix[mask] + n = len(sub) + if n <= 1: + continue + actual_k = min(k + 1, n) + self._log(f" {ds}: {n} nodes, k={min(k, n - 1)}") + if mode == "farthest": + dists, inds = self._farthest_neighbors_brute(sub, actual_k, metric) + else: + dists, inds = search_space.knn(sub, sub, actual_k, metric) + sub_meta = meta.iloc[idx_map].reset_index(drop=True) + all_edges.append(self._to_edge_df(sub_meta, inds, dists, min(k, n - 1), mode)) + if not all_edges: + return pd.DataFrame(columns=["src_id", "dst_id", "distance", "similarity", "rank"]) + return pd.concat(all_edges, ignore_index=True) + + def _farthest_neighbors_brute(self, matrix, k, metric): + """Brute-force farthest-neighbor search (true distances).""" + from sklearn.metrics import pairwise_distances + + skm = "manhattan" if metric == "l1" else "euclidean" + n = matrix.shape[0] + batch = 2000 + all_d = np.zeros((n, k), dtype=np.float32) + all_i = np.zeros((n, k), dtype=np.int64) + for s in range(0, n, batch): + e = min(s + batch, n) + D = pairwise_distances(matrix[s:e], matrix, metric=skm) + top_k = np.argpartition(-D, min(k, D.shape[1] - 1), axis=1)[:, :k] + for i in range(e - s): + order = top_k[i][np.argsort(-D[i, top_k[i]])] + all_i[s + i] = order + all_d[s + i] = D[i, order] + return all_d, all_i + + def _to_edge_df(self, meta, indices, distances, k, mode) -> pd.DataFrame: + """Convert KNN output (true distances) to an edge DataFrame.""" + rows = [] + node_ids = meta["node_id"].values + for i in range(len(meta)): + rank = 0 + for j in range(indices.shape[1]): + nb = indices[i, j] + if nb == i: + continue + dist = float(max(distances[i, j], 0.0)) + rank += 1 + rows.append( + { + "src_id": node_ids[i], + "dst_id": node_ids[nb], + "distance": round(dist, 6), + "similarity": round(float(np.exp(-dist)), 6), + "rank": rank, + } + ) + if rank >= k: + break + return pd.DataFrame(rows) + + def build_multiple_k( + self, + model_name: str, + feature_set: str = "reinsertion_core", + k_values: list[int] | None = None, + mode: str = "closest", + space: str = "weighted", + ) -> list[str]: + """Build edges for multiple K values.""" + if k_values is None: + k_values = [3, 5, 10, 25] + return [self.build(model_name, feature_set, k=k, mode=mode, space=space) for k in k_values] diff --git a/itrialspace/src/itrialspace/apps/nodulemap/neighbors/search_space.py b/itrialspace/src/itrialspace/apps/nodulemap/neighbors/search_space.py new file mode 100644 index 0000000000000000000000000000000000000000..f1af5a9b2e703642c4f7bbd35d8bf9f918acc896 --- /dev/null +++ b/itrialspace/src/itrialspace/apps/nodulemap/neighbors/search_space.py @@ -0,0 +1,130 @@ +# -*- coding: utf-8 -*- +""" +search_space.py — similarity/search backends for NoduleMap. + +The map's *layout* (2D embeddings) and its *search* (donor ranking / k-NN) are +deliberately decoupled. Search must run on a faithful, reduced-free space — never on a +2D/16D embedding. Three backends are provided: + + - ``weighted`` (default) — reproduces the clinical donor-matching metric of + :class:`itrialspace.query.matcher.ReinsertionMatcher` *exactly* as an + L1 (Manhattan) distance on a weighted feature matrix, so NoduleMap's + "similar donors" agree with the reinsertion pipeline. + - ``feature_l2`` — exact L2 on the standardized full feature vector + (``features_.npy``). + - ``embedding`` — L2 on the reduced embedding (legacy; kept for comparison only). + +Why L1 for ``weighted``: the matcher score is +``w_cc·|Δcc|/100 + w_pleural·|Δpleural|/max_p + w_diam·|Δdiam|/max_d + lobe_penalty·𝟙[lobe≠]`` +— a weighted sum of absolute differences plus a lobe indicator. Encoding each numeric as a +scaled column and the lobe as a one-hot scaled by ``lobe_penalty/2`` makes the **L1 distance +between two rows equal the matcher score** (a one-hot lobe mismatch differs in two positions +→ ``2·(lobe_penalty/2) = lobe_penalty``). +""" + +from __future__ import annotations + +from pathlib import Path + +import numpy as np +import pandas as pd + +from itrialspace.query.matcher import ReinsertionMatcher + +DEFAULT_WEIGHTS = dict(ReinsertionMatcher.DEFAULT_WEIGHTS) +BACKENDS = ("weighted", "feature_l2", "embedding") + + +def metric_for(backend: str) -> str: + """Distance metric a backend uses: 'l1' for weighted, 'l2' otherwise.""" + return "l1" if backend == "weighted" else "l2" + + +def weighted_matrix(meta: pd.DataFrame, weights: dict | None = None) -> np.ndarray: + """Build the weighted feature matrix whose L1 distance == ReinsertionMatcher score. + + Uses the reinsertion_* columns present in NoduleMap metadata. ``max_p``/``max_d`` are + taken over the whole set (matching the matcher's normalisation). + """ + w = {**DEFAULT_WEIGHTS, **(weights or {})} + + cc = pd.to_numeric(meta["reinsertion_lobe_cc_pct"], errors="coerce").to_numpy(float) + pl = pd.to_numeric(meta["reinsertion_pleural_dist_mm"], errors="coerce").to_numpy(float) + dm = pd.to_numeric(meta["reinsertion_nodule_diam_mm"], errors="coerce").to_numpy(float) + + finite_p = pl[np.isfinite(pl)] + finite_d = dm[np.isfinite(dm)] + max_p = max(float(finite_p.max()) if finite_p.size else 1.0, 1.0) + max_d = max(float(finite_d.max()) if finite_d.size else 1.0, 1.0) + + cc_fill = float(np.nanmedian(cc)) if np.isfinite(np.nanmedian(cc)) else 0.0 + cc = np.nan_to_num(cc, nan=cc_fill) + pl = np.nan_to_num(pl, nan=max_p) + dm = np.nan_to_num(dm, nan=0.0) + + cols = [ + (w["w_cc"] / 100.0) * cc, + (w["w_pleural"] / max_p) * pl, + (w["w_diam"] / max_d) * dm, + ] + lobe = pd.get_dummies(meta["reinsertion_lobe"].astype(str)) + lobe_mat = lobe.to_numpy(float) * (w["lobe_penalty"] / 2.0) + + return np.column_stack(cols + [lobe_mat]).astype(np.float32) + + +def build_search_matrix( + backend: str, + artifact_dir: str | Path, + feature_set: str, + model_name: str, + meta: pd.DataFrame, + weights: dict | None = None, +) -> np.ndarray: + """Return the (n, d) matrix to run k-NN on for the given backend.""" + artifact_dir = Path(artifact_dir) + if backend == "weighted": + return weighted_matrix(meta, weights) + if backend in ("feature_l2", "features"): + p = artifact_dir / f"features_{feature_set}.npy" + if not p.exists(): + raise FileNotFoundError( + f"Feature matrix not found: {p}. Rebuild embeddings to generate it " + f"(its-nodulemap build ...)." + ) + return np.load(p).astype(np.float32) + if backend == "embedding": + p = artifact_dir / f"embeddings_{feature_set}__{model_name}.npy" + if not p.exists(): + raise FileNotFoundError(f"Embeddings not found: {p}") + return np.load(p).astype(np.float32) + raise ValueError(f"Unknown search backend '{backend}'. Choose from {BACKENDS}.") + + +def knn(base: np.ndarray, queries: np.ndarray, k: int, metric: str = "l2"): + """k-NN of ``queries`` against ``base``. Returns (true_distances, indices), (m, k). + + Uses FAISS when available (exact IndexFlat), else sklearn. Distances are returned as + true (non-squared) distances in both cases. + """ + base = np.ascontiguousarray(base, dtype=np.float32) + queries = np.ascontiguousarray(queries, dtype=np.float32) + k = int(min(k, base.shape[0])) + try: + import faiss + + d = base.shape[1] + index = faiss.IndexFlat(d, faiss.METRIC_L1) if metric == "l1" else faiss.IndexFlatL2(d) + index.add(base) + dists, inds = index.search(queries, k) + if metric != "l1": + dists = np.sqrt(np.maximum(dists, 0.0)) + return dists, inds + except ImportError: + from sklearn.neighbors import NearestNeighbors + + nn = NearestNeighbors( + n_neighbors=k, metric=("manhattan" if metric == "l1" else "euclidean") + ) + nn.fit(base) + return nn.kneighbors(queries) diff --git a/itrialspace/src/itrialspace/apps/nodulemap/tools/__init__.py b/itrialspace/src/itrialspace/apps/nodulemap/tools/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/itrialspace/src/itrialspace/apps/nodulemap/tools/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/apps/nodulemap/tools/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..abc5b794be69a01ad6065b5a761c2b35f258cfd3 Binary files /dev/null and b/itrialspace/src/itrialspace/apps/nodulemap/tools/__pycache__/__init__.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/apps/nodulemap/tools/__pycache__/rebuild_artifacts.cpython-310.pyc b/itrialspace/src/itrialspace/apps/nodulemap/tools/__pycache__/rebuild_artifacts.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aca038694940c9f7541d5e67a64fc9023b860d66 Binary files /dev/null and b/itrialspace/src/itrialspace/apps/nodulemap/tools/__pycache__/rebuild_artifacts.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/apps/nodulemap/tools/__pycache__/similarity_report.cpython-310.pyc b/itrialspace/src/itrialspace/apps/nodulemap/tools/__pycache__/similarity_report.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2a8e246ab79f8b2abe46de8ea0c495d355faed5a Binary files /dev/null and b/itrialspace/src/itrialspace/apps/nodulemap/tools/__pycache__/similarity_report.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/apps/nodulemap/tools/__pycache__/verify_purge.cpython-310.pyc b/itrialspace/src/itrialspace/apps/nodulemap/tools/__pycache__/verify_purge.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..102479d5a3ee0bb690156e4588ca2daa657994d1 Binary files /dev/null and b/itrialspace/src/itrialspace/apps/nodulemap/tools/__pycache__/verify_purge.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/apps/nodulemap/tools/rebuild_artifacts.py b/itrialspace/src/itrialspace/apps/nodulemap/tools/rebuild_artifacts.py new file mode 100644 index 0000000000000000000000000000000000000000..26e7a731775cb07dc2f5f7a0e7ac18f102de7cb1 --- /dev/null +++ b/itrialspace/src/itrialspace/apps/nodulemap/tools/rebuild_artifacts.py @@ -0,0 +1,186 @@ +#!/usr/bin/env python3 +""" +rebuild_artifacts.py -- delete stale NoduleMap artifacts and rebuild from scratch. + +This ensures no NLST3D data remains in embeddings, metadata, or edge lists. + +Usage: + python -m itrialspace.apps.nodulemap.tools.rebuild_artifacts --clean + python -m itrialspace.apps.nodulemap.tools.rebuild_artifacts --clean --outdir ./nodulemap_artifacts + python -m itrialspace.apps.nodulemap.tools.rebuild_artifacts --clean --models PCA_2D UMAP_2D + python -m itrialspace.apps.nodulemap.tools.rebuild_artifacts --clean --skip-edges # faster: only embeddings +""" + +from __future__ import annotations + +import argparse +import glob +import os +import sys +import time +from pathlib import Path + +# Ensure project root is importable +PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent +sys.path.insert(0, str(PROJECT_ROOT)) + +DEFAULT_ARTIFACT_DIR = str(PROJECT_ROOT / "nodulemap_artifacts") + +ARTIFACT_PATTERNS = [ + "embeddings_*.npy", + "features_*.npy", + "metadata_*.parquet", + "edges_*.parquet", + "preprocessor_*.pkl", + "info_*.yaml", + "id_map*", + "positions_*", + "*.faiss", + "*.duckdb", + "*.duckdb.wal", +] + + +def clean_artifacts(artifact_dir: str) -> int: + """Delete all existing artifacts. Returns count of files deleted.""" + deleted = 0 + for pattern in ARTIFACT_PATTERNS: + for f in glob.glob(os.path.join(artifact_dir, pattern)): + os.remove(f) + deleted += 1 + return deleted + + +def rebuild( + artifact_dir: str, + models: list[str] | None = None, + feature_set: str = "reinsertion_core", + skip_edges: bool = False, + space: str = "weighted", + verbose: bool = True, +) -> dict: + """Rebuild all artifacts from scratch.""" + from itrialspace.apps.nodulemap.embeddings.build_embeddings import EmbeddingBuilder + from itrialspace.apps.nodulemap.neighbors.build_edges import EdgeBuilder + + if verbose: + print(f"\n{'=' * 60}") + print(" NoduleMap Artifact Rebuild") + print(f"{'=' * 60}\n") + + # Build NoduleIndex + builder = EmbeddingBuilder.from_defaults(verbose=verbose) + + # Check NLST3D is absent + datasets = sorted(builder._df["dataset"].unique().tolist()) + if "NLST3D" in datasets: + print("FATAL: NLST3D is still present in NoduleIndex!") + print("Fix datasets.yaml and profile CSVs before rebuilding.") + sys.exit(1) + + if verbose: + print(f"\n Datasets in index: {datasets}") + print(f" Total nodules: {len(builder._df):,}") + print() + + if models is None: + models = builder.list_models() + + results = {} + for model in models: + if verbose: + print(f"\n{'=' * 60}\n Building {model} ...\n{'=' * 60}") + t0 = time.time() + result = builder.build(model, feature_set, artifact_dir) + elapsed = time.time() - t0 + results[model] = result + if verbose: + print(f" {model}: {result['embeddings_shape']} ({elapsed:.1f}s)") + + # Build edges + if not skip_edges: + eb = EdgeBuilder(artifact_dir, verbose=verbose) + for model in models: + if verbose: + print(f"\n Building edges for {model} (space={space}) ...") + eb.build_multiple_k(model, feature_set, space=space) + + # Print dataset inventory from rebuilt metadata + if verbose: + print(f"\n{'=' * 60}") + print(" Post-Rebuild Dataset Inventory") + print(f"{'=' * 60}\n") + + import pandas as pd + + # Use any metadata file + meta_path = os.path.join(artifact_dir, f"metadata_{feature_set}__{models[0]}.parquet") + if os.path.exists(meta_path): + meta = pd.read_parquet(meta_path) + print(f" Total nodes: {len(meta):,}") + print(f" Datasets: {sorted(meta['dataset'].unique().tolist())}") + print() + print(f" {'Dataset':<10} {'Count':>8}") + print(" " + "-" * 20) + for ds, cnt in meta["dataset"].value_counts().sort_index().items(): + print(f" {ds:<10} {cnt:>8,}") + print() + if "NLST3D" in meta["dataset"].values: + print(" FAIL: NLST3D found in rebuilt artifacts!") + sys.exit(1) + else: + print(" NLST3D absent: CONFIRMED") + + return results + + +def main(): + parser = argparse.ArgumentParser(description="Rebuild NoduleMap artifacts") + parser.add_argument( + "--clean", + action="store_true", + required=True, + help="Delete existing artifacts before rebuild (required)", + ) + parser.add_argument( + "--outdir", + default=DEFAULT_ARTIFACT_DIR, + help=f"Artifact directory (default: {DEFAULT_ARTIFACT_DIR})", + ) + parser.add_argument( + "--models", nargs="*", default=None, help="Model names to build (default: all)" + ) + parser.add_argument( + "--feature-set", default="reinsertion_core", help="Feature set (default: reinsertion_core)" + ) + parser.add_argument( + "--skip-edges", action="store_true", help="Skip edge list computation (faster)" + ) + parser.add_argument( + "--space", + choices=["weighted", "feature_l2", "embedding"], + default="weighted", + help="Search space for edges (default: weighted = clinical ReinsertionMatcher metric)", + ) + args = parser.parse_args() + + artifact_dir = args.outdir + os.makedirs(artifact_dir, exist_ok=True) + + if args.clean: + n = clean_artifacts(artifact_dir) + print(f"Cleaned {n} stale artifact files from {artifact_dir}") + + rebuild( + artifact_dir=artifact_dir, + models=args.models, + feature_set=args.feature_set, + skip_edges=args.skip_edges, + space=args.space, + ) + + print("\nDone.") + + +if __name__ == "__main__": + main() diff --git a/itrialspace/src/itrialspace/apps/nodulemap/tools/similarity_report.py b/itrialspace/src/itrialspace/apps/nodulemap/tools/similarity_report.py new file mode 100644 index 0000000000000000000000000000000000000000..c91df919e45298127bf70ddc6f29b70212251b33 --- /dev/null +++ b/itrialspace/src/itrialspace/apps/nodulemap/tools/similarity_report.py @@ -0,0 +1,173 @@ +# -*- coding: utf-8 -*- +""" +similarity_report.py — measure NoduleMap search quality across backends. + +Quantifies two things so design choices are *measured*, not asserted: + +1. **k-NN concordance** — for a random sample of query nodes, the average fraction of the + top-k neighbours that share the query's lobe / size-bucket / side / (known) malignancy + label. Higher = more anatomically/clinically coherent neighbourhoods. Compared across + search backends: ``weighted`` (clinical metric) vs ``feature_l2`` (full feature space) + vs ``embedding`` (the reduced 2D/16D space — what was used before). +2. **Layout trustworthiness** — sklearn trustworthiness of each 2D embedding w.r.t. the full + feature space (are *displayed* neighbourhoods faithful?). + +Usage: + python -m itrialspace.apps.nodulemap.tools.similarity_report \\ + --artifact-dir "$NODULEMAP_ARTIFACTS" --k 10 --sample 1000 +""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import numpy as np +import pandas as pd + +from itrialspace.apps.nodulemap.neighbors import search_space + +_CONCORDANCE_COLS = { + "lobe": "reinsertion_lobe", + "size_bucket": "size_bucket", + "side": "reinsertion_lung_side", +} + + +def _list_models(artifact_dir: Path, feature_set: str) -> list[tuple[str, int]]: + out = [] + for f in sorted(artifact_dir.glob(f"embeddings_{feature_set}__*.npy")): + model = f.stem.replace(f"embeddings_{feature_set}__", "") + nd = np.load(f, mmap_mode="r").shape[1] + out.append((model, nd)) + return out + + +def _concordance(meta: pd.DataFrame, matrix: np.ndarray, metric: str, sample_idx, k: int) -> dict: + queries = matrix[sample_idx] + dists, inds = search_space.knn(matrix, queries, k + 1, metric) + scores = {key: [] for key in _CONCORDANCE_COLS} + scores["label"] = [] + for qi, row_inds in zip(sample_idx, inds): + nbrs = [j for j in row_inds if j != qi][:k] + if not nbrs: + continue + for key, col in _CONCORDANCE_COLS.items(): + if col in meta.columns: + qv = meta.iloc[qi][col] + share = np.mean([meta.iloc[j][col] == qv for j in nbrs]) + scores[key].append(float(share)) + # malignancy concordance only over labelled query+neighbours + if "label" in meta.columns: + ql = meta.iloc[qi]["label"] + if pd.notna(ql): + lab = [meta.iloc[j]["label"] for j in nbrs if pd.notna(meta.iloc[j]["label"])] + if lab: + scores["label"].append(float(np.mean([v == ql for v in lab]))) + return {key: (round(float(np.mean(v)), 4) if v else None) for key, v in scores.items()} + + +def main(): + ap = argparse.ArgumentParser(description="NoduleMap search-quality report") + ap.add_argument("--artifact-dir", default=None) + ap.add_argument("--feature-set", default="reinsertion_core") + ap.add_argument("--k", type=int, default=10) + ap.add_argument("--sample", type=int, default=1000, help="query nodes for concordance") + ap.add_argument("--trust-sample", type=int, default=2000, help="nodes for trustworthiness") + ap.add_argument("--seed", type=int, default=42) + args = ap.parse_args() + + from itrialspace.config import settings + + art = Path(args.artifact_dir or settings.nodulemap_artifacts_dir()) + fs = args.feature_set + models = _list_models(art, fs) + if not models: + raise SystemExit(f"No embeddings found in {art} for feature_set '{fs}'.") + + # Metadata is identical across models; use the first. + meta = pd.read_parquet(art / f"metadata_{fs}__{models[0][0]}.parquet") + n = len(meta) + rng = np.random.default_rng(args.seed) + sample_idx = rng.choice(n, size=min(args.sample, n), replace=False) + + # ── k-NN concordance per backend ─────────────────────────────────── + rows = [] + # model-independent backends + for backend in ("weighted", "feature_l2"): + M = search_space.build_search_matrix(backend, art, fs, models[0][0], meta) + c = _concordance(meta, M, search_space.metric_for(backend), sample_idx, args.k) + rows.append({"backend": backend, "space": backend, **c}) + # embedding backend — per model (this is the "search in reduced space" being replaced) + for model, nd in models: + M = search_space.build_search_matrix("embedding", art, fs, model, meta) + c = _concordance(meta, M, "l2", sample_idx, args.k) + rows.append({"backend": "embedding", "space": f"{model}({nd}D)", **c}) + conc = pd.DataFrame(rows) + + # ── Layout trustworthiness (2D models vs full feature space) ──────── + from sklearn.manifold import trustworthiness + + feat = np.load(art / f"features_{fs}.npy").astype(np.float32) + t_idx = rng.choice(n, size=min(args.trust_sample, n), replace=False) + trust = [] + for model, nd in models: + if nd != 2: + continue + emb = np.load(art / f"embeddings_{fs}__{model}.npy").astype(np.float32) + tw = trustworthiness(feat[t_idx], emb[t_idx, :2], n_neighbors=args.k) + trust.append({"model": model, "trustworthiness": round(float(tw), 4)}) + + # ── Emit ──────────────────────────────────────────────────────────── + report = { + "feature_set": fs, + "n_nodes": int(n), + "k": args.k, + "n_query_sample": int(len(sample_idx)), + "concordance": conc.to_dict(orient="records"), + "trustworthiness": trust, + "notes": [ + "Concordance = mean fraction of top-k neighbours sharing the query's attribute.", + "weighted = clinical ReinsertionMatcher metric (L1); feature_l2 = full 22-D space; " + "embedding = reduced layout space (legacy search).", + "Higher concordance = more coherent donor neighbourhoods for reinsertion.", + ], + } + (art / "nodulemap_similarity_report.json").write_text(json.dumps(report, indent=2)) + + md = ["# NoduleMap search-quality report", ""] + md.append( + f"- feature_set: `{fs}` · nodes: {n:,} · k={args.k} · " f"query sample={len(sample_idx)}" + ) + md.append("") + md.append("## k-NN concordance (fraction of top-k neighbours sharing attribute)") + md.append("") + md.append("| backend | space | lobe | size_bucket | side | malignancy |") + md.append("|---|---|---|---|---|---|") + for r in rows: + md.append( + f"| {r['backend']} | {r['space']} | {r.get('lobe')} | " + f"{r.get('size_bucket')} | {r.get('side')} | {r.get('label')} |" + ) + md.append("") + md.append("## Layout trustworthiness (2D embedding vs full feature space)") + md.append("") + md.append("| layout model | trustworthiness |") + md.append("|---|---|") + for t in trust: + md.append(f"| {t['model']} | {t['trustworthiness']} |") + md.append("") + md.append( + "> weighted/feature_l2 are the recommended **search** backends; 2D embeddings " + "are **layout only**. Higher concordance for weighted/feature_l2 vs embedding " + "confirms search should not run in the reduced space." + ) + (art / "nodulemap_similarity_report.md").write_text("\n".join(md)) + + print("\n".join(md)) + print(f"\nWrote {art/'nodulemap_similarity_report.md'} and .json") + + +if __name__ == "__main__": + main() diff --git a/itrialspace/src/itrialspace/apps/nodulemap/tools/verify_purge.py b/itrialspace/src/itrialspace/apps/nodulemap/tools/verify_purge.py new file mode 100644 index 0000000000000000000000000000000000000000..b35e12008920d0a58f11946590e99366e84fce75 --- /dev/null +++ b/itrialspace/src/itrialspace/apps/nodulemap/tools/verify_purge.py @@ -0,0 +1,149 @@ +#!/usr/bin/env python3 +""" +verify_purge.py — Post-rebuild verification that NLST3D is fully absent +from every NoduleMap artifact. + +Checks: + 1. Metadata parquets: no rows with dataset == "NLST3D" + 2. Info YAMLs: n_samples matches metadata row count + 3. Embeddings: .npy row count matches metadata + 4. Edge parquets: no src_id / dst_id starting with "NLST3D_" + 5. Preprocessor PKLs: exist and are loadable + 6. Node count: consistent across all models + +Exit code: + 0 = all checks passed + 1 = at least one check failed + +Usage: + python -m itrialspace.apps.nodulemap.tools.verify_purge --artifact-dir ./nodulemap_artifacts +""" + +from __future__ import annotations + +import argparse +import pickle +import sys +from pathlib import Path + +import numpy as np +import pandas as pd +import yaml + + +def verify(artifact_dir: str) -> bool: + """Run all checks. Returns True if clean.""" + art = Path(artifact_dir) + ok = True + n_nodes_set: set[int] = set() + + print(f"\n{'=' * 64}") + print(" NoduleMap NLST3D Purge Verification") + print(f" Artifact dir: {art}") + print(f"{'=' * 64}\n") + + # ── 1. Metadata parquets ───────────────────────────────────────── + meta_files = sorted(art.glob("metadata_*.parquet")) + if not meta_files: + _fail("No metadata parquets found") + return False + + for mf in meta_files: + df = pd.read_parquet(mf) + tag = mf.stem.replace("metadata_", "") + datasets = sorted(df["dataset"].unique()) + n = len(df) + n_nodes_set.add(n) + + if "NLST3D" in datasets: + nlst_n = (df["dataset"] == "NLST3D").sum() + _fail(f"{mf.name}: NLST3D found ({nlst_n} rows)") + ok = False + else: + _pass(f"{mf.name}: {n:,} rows, {len(datasets)} datasets — no NLST3D") + + # Check for NLST3D in node_id + if "node_id" in df.columns: + nlst_ids = df["node_id"].str.startswith("NLST3D_").sum() + if nlst_ids > 0: + _fail(f"{mf.name}: {nlst_ids} node_ids start with NLST3D_") + ok = False + + # ── 2. Embeddings .npy ─────────────────────────────────────────── + emb_files = sorted(art.glob("embeddings_*.npy")) + for ef in emb_files: + arr = np.load(ef) + tag = ef.stem.replace("embeddings_", "") + n_nodes_set.add(arr.shape[0]) + _pass(f"{ef.name}: {arr.shape} float32") + + # ── 3. Info YAMLs ──────────────────────────────────────────────── + info_files = sorted(art.glob("info_*.yaml")) + for yf in info_files: + with open(yf) as f: + info = yaml.safe_load(f) + n_yaml = info.get("n_samples", -1) + n_nodes_set.add(n_yaml) + _pass(f"{yf.name}: n_samples={n_yaml}") + + # ── 4. Edge parquets ───────────────────────────────────────────── + edge_files = sorted(art.glob("edges_*.parquet")) + for ef in edge_files: + edf = pd.read_parquet(ef) + tag = ef.stem.replace("edges_", "") + bad_src = edf["src_id"].str.startswith("NLST3D_").sum() + bad_dst = edf["dst_id"].str.startswith("NLST3D_").sum() + if bad_src > 0 or bad_dst > 0: + _fail(f"{ef.name}: NLST3D references ({bad_src} src, {bad_dst} dst)") + ok = False + else: + _pass(f"{ef.name}: {len(edf):,} edges — no NLST3D refs") + + # ── 5. Preprocessor PKLs ──────────────────────────────────────── + pkl_files = sorted(art.glob("preprocessor_*.pkl")) + for pf in pkl_files: + try: + with open(pf, "rb") as f: + pickle.load(f) + _pass(f"{pf.name}: loadable") + except Exception as e: + _fail(f"{pf.name}: cannot load — {e}") + ok = False + + # ── 6. Cross-model consistency ─────────────────────────────────── + if len(n_nodes_set) == 1: + _pass(f"All artifacts have consistent node count: {n_nodes_set.pop():,}") + else: + _fail(f"Inconsistent node counts across artifacts: {n_nodes_set}") + ok = False + + # ── Summary ────────────────────────────────────────────────────── + print(f"\n{'=' * 64}") + if ok: + print(" RESULT: ALL CHECKS PASSED — NLST3D fully purged") + else: + print(" RESULT: CHECKS FAILED — NLST3D contamination detected") + print(f"{'=' * 64}\n") + + return ok + + +def _pass(msg: str) -> None: + print(f" [PASS] {msg}") + + +def _fail(msg: str) -> None: + print(f" [FAIL] {msg}") + + +def main(): + parser = argparse.ArgumentParser(description="Verify NLST3D purge from NoduleMap artifacts") + parser.add_argument("--artifact-dir", required=True, help="Path to artifact directory") + args = parser.parse_args() + + clean = verify(args.artifact_dir) + sys.exit(0 if clean else 1) + + +if __name__ == "__main__": + main() diff --git a/itrialspace/src/itrialspace/apps/retriever/__init__.py b/itrialspace/src/itrialspace/apps/retriever/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..97e8f89e84c79a5a51237a23e1d6a8fa0c55fcbf --- /dev/null +++ b/itrialspace/src/itrialspace/apps/retriever/__init__.py @@ -0,0 +1,21 @@ +""" +iTrialSpace Retriever — interactive retrieval + visualization framework. + +Three deployment modes: + 1. Full Web App: Streamlit + FastAPI backend + 2. Headless: FastAPI backend + Jupyter notebook client + 3. Library + CLI: Pure Python API + command-line tools + +Quick start (library mode): + from itrialspace.apps.retriever import RetrieverEngine + engine = RetrieverEngine.from_defaults() + results = engine.search(datasets=["DLCS24"], label=1, diameter_range=(5, 20)) + similar = engine.find_similar("DLCS24_n0001", k=10) +""" + +__version__ = "0.1.0" + +from itrialspace.apps.retriever.engine import RetrieverEngine +from itrialspace.apps.retriever.search import FacetedSearch, SearchFilters +from itrialspace.apps.retriever.similarity import SimilarityEngine +from itrialspace.apps.retriever.slicer import NIfTISlicer diff --git a/itrialspace/src/itrialspace/apps/retriever/__main__.py b/itrialspace/src/itrialspace/apps/retriever/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..0410bb32ada31cbb45c104dd79e285fba548d8a7 --- /dev/null +++ b/itrialspace/src/itrialspace/apps/retriever/__main__.py @@ -0,0 +1,7 @@ +""" +__main__.py — allow `python -m itrialspace.apps.retriever` to invoke the CLI. +""" + +from itrialspace.apps.retriever.cli import main + +main() diff --git a/itrialspace/src/itrialspace/apps/retriever/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/apps/retriever/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0c9e43eeff0c4a1104049331f435e9338f686cd2 Binary files /dev/null and b/itrialspace/src/itrialspace/apps/retriever/__pycache__/__init__.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/apps/retriever/__pycache__/__main__.cpython-310.pyc b/itrialspace/src/itrialspace/apps/retriever/__pycache__/__main__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ec065a2030c729eba1a77604fcb94de496a87bf Binary files /dev/null and b/itrialspace/src/itrialspace/apps/retriever/__pycache__/__main__.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/apps/retriever/__pycache__/cli.cpython-310.pyc b/itrialspace/src/itrialspace/apps/retriever/__pycache__/cli.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a49035154f06390e7b1f9feb0eb5f47741a1ab96 Binary files /dev/null and b/itrialspace/src/itrialspace/apps/retriever/__pycache__/cli.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/apps/retriever/__pycache__/engine.cpython-310.pyc b/itrialspace/src/itrialspace/apps/retriever/__pycache__/engine.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..df46b8c77414c7739b0bb4d20ae1b33269e958a2 Binary files /dev/null and b/itrialspace/src/itrialspace/apps/retriever/__pycache__/engine.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/apps/retriever/__pycache__/notebook.cpython-310.pyc b/itrialspace/src/itrialspace/apps/retriever/__pycache__/notebook.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b338e92e8d29b03bf7f29ab2971a77e16ee40e9 Binary files /dev/null and b/itrialspace/src/itrialspace/apps/retriever/__pycache__/notebook.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/apps/retriever/__pycache__/search.cpython-310.pyc b/itrialspace/src/itrialspace/apps/retriever/__pycache__/search.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e8db0d84d4ae7a11aca02f98a8b32e2a2760e022 Binary files /dev/null and b/itrialspace/src/itrialspace/apps/retriever/__pycache__/search.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/apps/retriever/__pycache__/similarity.cpython-310.pyc b/itrialspace/src/itrialspace/apps/retriever/__pycache__/similarity.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5523ae4684daae62ce3b7fa55d2f9ee39a9e0f6a Binary files /dev/null and b/itrialspace/src/itrialspace/apps/retriever/__pycache__/similarity.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/apps/retriever/__pycache__/slicer.cpython-310.pyc b/itrialspace/src/itrialspace/apps/retriever/__pycache__/slicer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0da132ba6c7bbd9dfb6121b4ba5a0004710fe844 Binary files /dev/null and b/itrialspace/src/itrialspace/apps/retriever/__pycache__/slicer.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/apps/retriever/api/__init__.py b/itrialspace/src/itrialspace/apps/retriever/api/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/itrialspace/src/itrialspace/apps/retriever/api/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/apps/retriever/api/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d4464181b08ec7dd69fbc062ba9b71a5017f5af5 Binary files /dev/null and b/itrialspace/src/itrialspace/apps/retriever/api/__pycache__/__init__.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/apps/retriever/api/__pycache__/app.cpython-310.pyc b/itrialspace/src/itrialspace/apps/retriever/api/__pycache__/app.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..433f5084637ab288acb46097bbdf80256a536d36 Binary files /dev/null and b/itrialspace/src/itrialspace/apps/retriever/api/__pycache__/app.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/apps/retriever/api/__pycache__/models.cpython-310.pyc b/itrialspace/src/itrialspace/apps/retriever/api/__pycache__/models.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..87bddf8fcd5853685470754fe02fc1de16fb3e8a Binary files /dev/null and b/itrialspace/src/itrialspace/apps/retriever/api/__pycache__/models.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/apps/retriever/api/app.py b/itrialspace/src/itrialspace/apps/retriever/api/app.py new file mode 100644 index 0000000000000000000000000000000000000000..e9196b7b7d93885626ebf43b8d4f81e2618c4d0d --- /dev/null +++ b/itrialspace/src/itrialspace/apps/retriever/api/app.py @@ -0,0 +1,369 @@ +""" +FastAPI backend for the iTrialSpace Retriever. + +Endpoints: + GET /health — service health + stats + GET /filters — available filter values + POST /search — faceted search + POST /similar — query-by-example similarity + POST /matcher — reinsertion anatomy matching + GET /nodule/{id} — full nodule detail + GET /ct/slice — extract a 2-D CT slice (PNG) + GET /ct/nodule-view — CT slice at nodule centre (PNG) + GET /ct/info — volume metadata + POST /export — export search results (CSV/JSON download) + +Launch: + uvicorn retriever.api.app:create_app --factory --host 0.0.0.0 --port 8421 +""" + +from __future__ import annotations + +import os +import tempfile +from typing import Optional + +import numpy as np +import pandas as pd +from fastapi import FastAPI, HTTPException, Response +from fastapi.middleware.cors import CORSMiddleware +from fastapi.responses import FileResponse + +from itrialspace.apps.retriever.api.models import ( + ExportRequest, + FiltersInfoResponse, + HealthResponse, + MatchedNodule, + MatcherRequest, + MatcherResponse, + NoduleDetailResponse, + NoduleSummary, + SearchRequest, + SearchResponse, + SimilarityRequest, + SimilarityResponse, + SimilarNodule, + VolumeInfoResponse, +) +from itrialspace.apps.retriever.engine import RetrieverEngine +from itrialspace.apps.retriever.search import SearchFilters + +# --------------------------------------------------------------------------- +# App factory +# --------------------------------------------------------------------------- + +_engine: Optional[RetrieverEngine] = None + + +def get_engine() -> RetrieverEngine: + """Lazy singleton engine loader.""" + global _engine + if _engine is None: + print("[Retriever API] Loading NoduleIndex …") + _engine = RetrieverEngine.from_defaults(verbose=True) + print(f"[Retriever API] Ready — {_engine.n_nodules:,} nodules loaded") + return _engine + + +def create_app( + engine: Optional[RetrieverEngine] = None, +) -> FastAPI: + """ + Create and configure the FastAPI application. + + Args: + engine: optional pre-built engine (for testing or Jupyter embedding). + """ + global _engine + if engine is not None: + _engine = engine + + app = FastAPI( + title="iTrialSpace Retriever", + description="Interactive retrieval + visualization for 13k+ lung nodules across 7 datasets.", + version="0.1.0", + ) + + app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], + ) + + # ── Health ──────────────────────────────────────────────────────────────── + + @app.get("/health", response_model=HealthResponse) + def health(): + eng = get_engine() + return HealthResponse( + version="0.1.0", + n_nodules=eng.n_nodules, + datasets=eng.datasets, + ) + + # ── Filters info ────────────────────────────────────────────────────────── + + @app.get("/filters", response_model=FiltersInfoResponse) + def filters_info(): + eng = get_engine() + af = eng.available_filters + return FiltersInfoResponse(**af) + + # ── Faceted search ──────────────────────────────────────────────────────── + + @app.post("/search", response_model=SearchResponse) + def search(req: SearchRequest): + eng = get_engine() + sf = SearchFilters(**req.model_dump()) + result = eng.search(sf) + summaries = _df_to_summaries(result.df) + return SearchResponse( + total_matching=result.total_matching, + returned=len(summaries), + results=summaries, + facet_counts=result.facet_counts, + ) + + # ── Similarity ──────────────────────────────────────────────────────────── + + @app.post("/similar", response_model=SimilarityResponse) + def similar(req: SimilarityRequest): + eng = get_engine() + try: + results = eng.find_similar( + annotation_id=req.annotation_id, + k=req.k, + exclude_same_patient=req.exclude_same_patient, + include_datasets=req.include_datasets, + exclude_datasets=req.exclude_datasets, + label=req.label, + ) + except KeyError as e: + raise HTTPException(404, detail=str(e)) + + items = [] + for r in results: + row = r.row + items.append( + SimilarNodule( + annotation_id=r.annotation_id, + dataset=r.dataset, + distance=round(r.distance, 4), + rank=r.rank, + lobe_name=str(row.get("lobe_name", "")), + nodule_mean_diam_mm=float(row.get("nodule_mean_diam_mm", 0)), + label=int(row["label"]) if pd.notna(row.get("label")) else None, + feature_deltas={k: round(v, 4) for k, v in r.feature_deltas.items()}, + ) + ) + return SimilarityResponse( + reference_id=req.annotation_id, + k=req.k, + results=items, + ) + + # ── Reinsertion matcher ─────────────────────────────────────────────────── + + @app.post("/matcher", response_model=MatcherResponse) + def matcher(req: MatcherRequest): + eng = get_engine() + results = eng.find_reinsertion_match( + lobe=req.lobe, + lobe_cc_pct=req.lobe_cc_pct, + pleural_dist_mm=req.pleural_dist_mm, + diameter_mm=req.diameter_mm, + label=req.label, + lung_zone=req.lung_zone, + lung_side=req.lung_side, + include_datasets=req.include_datasets, + exclude_datasets=req.exclude_datasets, + k=req.k, + ) + items = [ + MatchedNodule( + annotation_id=m.annotation_id, + dataset=m.dataset, + ct_path=m.ct_path, + score=round(m.score, 4), + lobe=m.lobe, + diameter_mm=round(m.diameter_mm, 2), + pleural_mm=round(m.pleural_mm, 2) if m.pleural_mm is not None else None, + lobe_cc_pct=round(m.lobe_cc_pct, 2), + label=m.label, + ) + for m in results + ] + return MatcherResponse( + target_lobe=req.lobe, + k=req.k, + results=items, + ) + + # ── Nodule detail ───────────────────────────────────────────────────────── + + @app.get("/nodule/{annotation_id}", response_model=NoduleDetailResponse) + def nodule_detail(annotation_id: str): + eng = get_engine() + try: + detail = eng.get_nodule_detail(annotation_id) + except KeyError as e: + raise HTTPException(404, detail=str(e)) + + paths = detail.pop("_paths", {}) + paths_exist = { + k.replace("_exists_", ""): v for k, v in detail.items() if k.startswith("_exists_") + } + for k in list(detail.keys()): + if k.startswith("_exists_"): + del detail[k] + + # Convert NaN/NaT to None for JSON serialisation + cleaned = {} + for k, v in detail.items(): + if isinstance(v, float) and np.isnan(v): + cleaned[k] = None + elif pd.isna(v): + cleaned[k] = None + else: + cleaned[k] = v + + return NoduleDetailResponse( + annotation_id=str(cleaned.get("annotation_id", annotation_id)), + dataset=str(cleaned.get("dataset", "")), + patient_id=str(cleaned.get("patient_id", "")), + label=cleaned.get("label"), + detail=cleaned, + paths=paths, + paths_exist=paths_exist, + ) + + # ── CT slice viewer ─────────────────────────────────────────────────────── + + @app.get("/ct/slice") + def ct_slice( + ct_path: str, + axis: str = "axial", + index: Optional[int] = None, + mask_path: Optional[str] = None, + window: str = "lung", + ): + eng = get_engine() + try: + sl = eng.get_slice( + ct_path=ct_path, + axis=axis, + index=index, + mask_path=mask_path, + window=window, + ) + png = sl.to_png_bytes() + except FileNotFoundError as e: + raise HTTPException(404, detail=str(e)) + except Exception as e: + raise HTTPException(500, detail=str(e)) + + return Response(content=png, media_type="image/png") + + @app.get("/ct/nodule-view") + def ct_nodule_view( + annotation_id: str, + axis: str = "axial", + window: str = "lung", + show_mask: bool = True, + ): + eng = get_engine() + try: + sl = eng.get_nodule_view(annotation_id, axis=axis, window=window, show_mask=show_mask) + png = sl.to_png_bytes() + except (KeyError, FileNotFoundError) as e: + raise HTTPException(404, detail=str(e)) + except Exception as e: + raise HTTPException(500, detail=str(e)) + + return Response(content=png, media_type="image/png") + + @app.get("/ct/info", response_model=VolumeInfoResponse) + def ct_info(ct_path: str): + eng = get_engine() + try: + shape = eng.volume_shape(ct_path) + spacing = eng._slicer.voxel_spacing(ct_path) + except FileNotFoundError as e: + raise HTTPException(404, detail=str(e)) + return VolumeInfoResponse( + shape=list(shape), + spacing_mm=[round(s, 3) for s in spacing], + ) + + # ── Export ──────────────────────────────────────────────────────────────── + + @app.post("/export") + def export(req: ExportRequest): + eng = get_engine() + sf = SearchFilters(**req.filters.model_dump()) + + ext = "csv" if req.format == "csv" else "json" + fname = req.filename or f"itrialspace_export.{ext}" + + tmp = tempfile.NamedTemporaryFile(suffix=f".{ext}", delete=False, prefix="retriever_") + tmp.close() + + try: + if req.format == "csv": + eng.export_search_csv(sf, tmp.name, include_paths=req.include_paths) + else: + eng.export_search_json(sf, tmp.name, include_paths=req.include_paths) + except Exception as e: + os.unlink(tmp.name) + raise HTTPException(500, detail=str(e)) + + media = "text/csv" if ext == "csv" else "application/json" + return FileResponse( + tmp.name, + media_type=media, + filename=fname, + background=None, + ) + + return app + + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + + +def _df_to_summaries(df: pd.DataFrame) -> list[NoduleSummary]: + """Convert a results DataFrame to NoduleSummary list.""" + summaries = [] + for _, row in df.iterrows(): + summaries.append( + NoduleSummary( + annotation_id=str(row.get("annotation_id", "")), + dataset=str(row.get("dataset", "")), + patient_id=str(row.get("patient_id", "")), + ct_path=str(row.get("ct_path", "")), + label=int(row["label"]) if pd.notna(row.get("label")) else None, + lobe_name=str(row.get("lobe_name", "")), + lung_side=str(row.get("lung_side", "")), + lung_zone=str(row.get("lung_zone", "")), + central_peripheral=str(row.get("central_peripheral", "")), + nodule_mean_diam_mm=float(row.get("nodule_mean_diam_mm", 0)), + pleural_distance_mm=( + float(row["pleural_distance_mm"]) + if pd.notna(row.get("pleural_distance_mm")) + else None + ), + reinsertion_lobe=str(row.get("reinsertion_lobe", "")), + reinsertion_nodule_diam_mm=float(row.get("reinsertion_nodule_diam_mm", 0)), + reinsertion_pleural_dist_mm=( + float(row["reinsertion_pleural_dist_mm"]) + if pd.notna(row.get("reinsertion_pleural_dist_mm")) + else None + ), + reinsertion_lobe_cc_pct=float(row.get("reinsertion_lobe_cc_pct", 0)), + ) + ) + return summaries diff --git a/itrialspace/src/itrialspace/apps/retriever/api/models.py b/itrialspace/src/itrialspace/apps/retriever/api/models.py new file mode 100644 index 0000000000000000000000000000000000000000..c890fb1cafb68a9c9f34716368151572c5f7dafe --- /dev/null +++ b/itrialspace/src/itrialspace/apps/retriever/api/models.py @@ -0,0 +1,243 @@ +""" +Pydantic request / response models for the FastAPI backend. +""" + +from __future__ import annotations + +from typing import Optional + +from pydantic import BaseModel, Field + +# --------------------------------------------------------------------------- +# Search +# --------------------------------------------------------------------------- + + +class SearchRequest(BaseModel): + """POST /search request body.""" + + datasets: Optional[list[str]] = None + exclude_datasets: Optional[list[str]] = None + label: Optional[int] = Field(None, ge=0, le=1) + lobe: Optional[list[str]] = None + lung_zone: Optional[list[str]] = None + lung_side: Optional[str] = None + central_peripheral: Optional[str] = None + diameter_min: Optional[float] = None + diameter_max: Optional[float] = None + pleural_distance_min: Optional[float] = None + pleural_distance_max: Optional[float] = None + airway_distance_min: Optional[float] = None + airway_distance_max: Optional[float] = None + reinsertion_lobe: Optional[list[str]] = None + reinsertion_zone: Optional[list[str]] = None + reinsertion_side: Optional[str] = None + reinsertion_diameter_min: Optional[float] = None + reinsertion_diameter_max: Optional[float] = None + reinsertion_pleural_min: Optional[float] = None + reinsertion_pleural_max: Optional[float] = None + reinsertion_cc_pct_min: Optional[float] = None + reinsertion_cc_pct_max: Optional[float] = None + n_nodules_min: Optional[int] = None + n_nodules_max: Optional[int] = None + population_type: Optional[str] = None + label_source: Optional[str] = None + limit: Optional[int] = Field(50, ge=1, le=5000) + offset: int = Field(0, ge=0) + sample_n: Optional[int] = None + sample_seed: Optional[int] = None + sort_by: Optional[str] = None + sort_ascending: bool = True + + +class NoduleSummary(BaseModel): + """Compact nodule representation for search results.""" + + annotation_id: str + dataset: str + patient_id: str + ct_path: str + label: Optional[int] = None + lobe_name: str = "" + lung_side: str = "" + lung_zone: str = "" + central_peripheral: str = "" + nodule_mean_diam_mm: float = 0.0 + pleural_distance_mm: Optional[float] = None + reinsertion_lobe: str = "" + reinsertion_nodule_diam_mm: float = 0.0 + reinsertion_pleural_dist_mm: Optional[float] = None + reinsertion_lobe_cc_pct: float = 0.0 + + +class SearchResponse(BaseModel): + """POST /search response.""" + + total_matching: int + returned: int + results: list[NoduleSummary] + facet_counts: Optional[dict] = None + + +# --------------------------------------------------------------------------- +# Similarity +# --------------------------------------------------------------------------- + + +class SimilarityRequest(BaseModel): + """POST /similar request body.""" + + annotation_id: str + k: int = Field(10, ge=1, le=500) + exclude_same_patient: bool = True + include_datasets: Optional[list[str]] = None + exclude_datasets: Optional[list[str]] = None + label: Optional[int] = None + + +class SimilarNodule(BaseModel): + """Single similar nodule result.""" + + annotation_id: str + dataset: str + distance: float + rank: int + lobe_name: str = "" + nodule_mean_diam_mm: float = 0.0 + label: Optional[int] = None + feature_deltas: dict = {} + + +class SimilarityResponse(BaseModel): + """POST /similar response.""" + + reference_id: str + k: int + results: list[SimilarNodule] + + +# --------------------------------------------------------------------------- +# Reinsertion matcher +# --------------------------------------------------------------------------- + + +class MatcherRequest(BaseModel): + """POST /matcher request body.""" + + lobe: str + lobe_cc_pct: Optional[float] = None + pleural_dist_mm: Optional[float] = None + diameter_mm: Optional[float] = None + label: Optional[int] = None + lung_zone: Optional[str] = None + lung_side: Optional[str] = None + include_datasets: Optional[list[str]] = None + exclude_datasets: Optional[list[str]] = None + k: int = Field(10, ge=1, le=500) + + +class MatchedNodule(BaseModel): + """A single match result.""" + + annotation_id: str + dataset: str + ct_path: str + score: float + lobe: str + diameter_mm: float + pleural_mm: Optional[float] = None + lobe_cc_pct: float = 0.0 + label: Optional[int] = None + + +class MatcherResponse(BaseModel): + """POST /matcher response.""" + + target_lobe: str + k: int + results: list[MatchedNodule] + + +# --------------------------------------------------------------------------- +# CT slice viewer +# --------------------------------------------------------------------------- + + +class SliceRequest(BaseModel): + """GET /ct/slice query params.""" + + ct_path: str + axis: str = "axial" + index: Optional[int] = None + mask_path: Optional[str] = None + window: str = "lung" + + +class NoduleViewRequest(BaseModel): + """GET /ct/nodule-view query params.""" + + annotation_id: str + axis: str = "axial" + window: str = "lung" + + +class VolumeInfoResponse(BaseModel): + """GET /ct/info response.""" + + shape: list[int] + spacing_mm: list[float] + + +# --------------------------------------------------------------------------- +# Export +# --------------------------------------------------------------------------- + + +class ExportRequest(BaseModel): + """POST /export request body.""" + + filters: SearchRequest + format: str = "csv" # "csv" or "json" + include_paths: bool = True + filename: Optional[str] = None + + +# --------------------------------------------------------------------------- +# Nodule detail +# --------------------------------------------------------------------------- + + +class NoduleDetailResponse(BaseModel): + """GET /nodule/{annotation_id} response.""" + + annotation_id: str + dataset: str + patient_id: str + label: Optional[int] = None + detail: dict + paths: dict = {} + paths_exist: dict = {} + + +# --------------------------------------------------------------------------- +# General +# --------------------------------------------------------------------------- + + +class HealthResponse(BaseModel): + version: str + n_nodules: int + datasets: list[str] + + +class FiltersInfoResponse(BaseModel): + """GET /filters response — available facet values.""" + + datasets: list[str] + lobes: list[str] + zones: list[str] + sides: list[str] + labels: list + central_peripheral: list[str] + population_types: list[str] + label_sources: list[str] diff --git a/itrialspace/src/itrialspace/apps/retriever/cli.py b/itrialspace/src/itrialspace/apps/retriever/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..def371034d383debcae22d30d99072d5507d0bf5 --- /dev/null +++ b/itrialspace/src/itrialspace/apps/retriever/cli.py @@ -0,0 +1,338 @@ +#!/usr/bin/env python3 +""" +iTrialSpace Retriever CLI — command-line interface. + +Usage: + python -m itrialspace.apps.retriever.cli search --label 1 --lobe right_lung_upper_lobe --limit 20 + python -m itrialspace.apps.retriever.cli similar --id DLCS24_n0001 --k 10 + python -m itrialspace.apps.retriever.cli match --lobe left_lung_lower_lobe --diameter 12 --k 5 + python -m itrialspace.apps.retriever.cli export --label 1 --format csv -o results.csv + python -m itrialspace.apps.retriever.cli info + python -m itrialspace.apps.retriever.cli serve --port 8421 +""" + +from __future__ import annotations + +import argparse +import json +import sys + +import pandas as pd + +# --------------------------------------------------------------------------- +# Lazy engine loader +# --------------------------------------------------------------------------- + +_engine = None + + +def _get_engine(): + global _engine + if _engine is None: + from itrialspace.apps.retriever.engine import RetrieverEngine + + print("Loading NoduleIndex …", file=sys.stderr) + _engine = RetrieverEngine.from_defaults(verbose=True) + print(f"Ready — {_engine.n_nodules:,} nodules.\n", file=sys.stderr) + return _engine + + +# --------------------------------------------------------------------------- +# Commands +# --------------------------------------------------------------------------- + + +def cmd_search(args): + engine = _get_engine() + from itrialspace.apps.retriever.search import SearchFilters + + kwargs = {} + if args.datasets: + kwargs["datasets"] = args.datasets + if args.label is not None: + kwargs["label"] = args.label + if args.lobe: + kwargs["lobe"] = args.lobe + if args.zone: + kwargs["lung_zone"] = args.zone + if args.side: + kwargs["lung_side"] = args.side + if args.diam_min is not None: + kwargs["diameter_min"] = args.diam_min + if args.diam_max is not None: + kwargs["diameter_max"] = args.diam_max + if args.pleural_min is not None: + kwargs["pleural_distance_min"] = args.pleural_min + if args.pleural_max is not None: + kwargs["pleural_distance_max"] = args.pleural_max + if args.population: + kwargs["population_type"] = args.population + if args.label_source: + kwargs["label_source"] = args.label_source + kwargs["limit"] = args.limit + if args.sort: + kwargs["sort_by"] = args.sort + kwargs["sort_ascending"] = not args.desc + + sf = SearchFilters(**kwargs) + result = engine.search(sf) + + print(f"Total matching: {result.total_matching:,}") + print(f"Showing: {len(result.df)}\n") + + display_cols = [ + "annotation_id", + "dataset", + "label", + "lobe_name", + "nodule_mean_diam_mm", + "pleural_distance_mm", + ] + cols = [c for c in display_cols if c in result.df.columns] + print(result.df[cols].to_string(index=False)) + + +def cmd_similar(args): + engine = _get_engine() + + kwargs = {} + if args.label is not None: + kwargs["label"] = args.label + if args.datasets: + kwargs["include_datasets"] = args.datasets + + results = engine.find_similar( + annotation_id=args.id, + k=args.k, + exclude_same_patient=not args.allow_same_patient, + **kwargs, + ) + + if not results: + print("No similar nodules found.") + return + + print(f"Top-{args.k} similar to {args.id}:\n") + rows = [] + for r in results: + rows.append( + { + "rank": r.rank, + "annotation_id": r.annotation_id, + "dataset": r.dataset, + "distance": f"{r.distance:.4f}", + } + ) + print(pd.DataFrame(rows).to_string(index=False)) + + +def cmd_match(args): + engine = _get_engine() + + kwargs = {} + if args.cc_pct is not None: + kwargs["lobe_cc_pct"] = args.cc_pct + if args.pleural is not None: + kwargs["pleural_dist_mm"] = args.pleural + if args.diameter is not None: + kwargs["diameter_mm"] = args.diameter + if args.label is not None: + kwargs["label"] = args.label + if args.datasets: + kwargs["include_datasets"] = args.datasets + + results = engine.find_reinsertion_match(lobe=args.lobe, k=args.k, **kwargs) + + if not results: + print("No matches found.") + return + + print(f"Top-{args.k} reinsertion matches for {args.lobe}:\n") + rows = [] + for m in results: + label_str = {0: "benign", 1: "malignant", None: "?"}[m.label] + rows.append( + { + "annotation_id": m.annotation_id, + "dataset": m.dataset, + "score": f"{m.score:.4f}", + "diameter_mm": f"{m.diameter_mm:.1f}", + "lobe_cc_pct": f"{m.lobe_cc_pct:.1f}", + "label": label_str, + } + ) + print(pd.DataFrame(rows).to_string(index=False)) + + +def cmd_export(args): + engine = _get_engine() + from itrialspace.apps.retriever.search import SearchFilters + + kwargs = {} + if args.datasets: + kwargs["datasets"] = args.datasets + if args.label is not None: + kwargs["label"] = args.label + if args.lobe: + kwargs["lobe"] = args.lobe + if args.diam_min is not None: + kwargs["diameter_min"] = args.diam_min + if args.diam_max is not None: + kwargs["diameter_max"] = args.diam_max + + sf = SearchFilters(**kwargs) + + if args.format == "csv": + path = engine.export_search_csv(sf, args.output, include_paths=args.include_paths) + else: + path = engine.export_search_json(sf, args.output, include_paths=args.include_paths) + + print(f"Exported to {path}") + + +def cmd_info(args): + engine = _get_engine() + summary = engine.summary() + print("iTrialSpace Retriever v0.1.0") + print(f"Nodules: {summary['n_nodules']:,}") + print(f"Datasets: {', '.join(summary['datasets'])}") + print() + stats_df = pd.DataFrame(summary["stats"]).T + print(stats_df.to_string()) + + +def cmd_detail(args): + engine = _get_engine() + detail = engine.get_nodule_detail(args.id) + + if args.json: + # Serialise NaN-safe + cleaned = {} + for k, v in detail.items(): + if isinstance(v, float) and pd.isna(v): + cleaned[k] = None + elif isinstance(v, pd.Series): + cleaned[k] = v.to_dict() + else: + cleaned[k] = v + print(json.dumps(cleaned, indent=2, default=str)) + else: + for k, v in detail.items(): + if not str(k).startswith("_"): + print(f" {k:40s} {v}") + + +def cmd_serve(args): + """Launch the FastAPI server.""" + try: + import uvicorn + except ImportError: + print("uvicorn is required: pip install uvicorn", file=sys.stderr) + sys.exit(1) + + print(f"Starting retriever API on {args.host}:{args.port}") + uvicorn.run( + "itrialspace.apps.retriever.api.app:create_app", + factory=True, + host=args.host, + port=args.port, + reload=args.reload, + ) + + +# --------------------------------------------------------------------------- +# Argument parser +# --------------------------------------------------------------------------- + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + prog="retriever", + description="iTrialSpace Retriever CLI — search, similarity, matching, export.", + ) + sub = parser.add_subparsers(dest="command", required=True) + + # -- search --- + p_search = sub.add_parser("search", help="Faceted search") + p_search.add_argument("--datasets", nargs="+", default=None) + p_search.add_argument("--label", type=int, choices=[0, 1], default=None) + p_search.add_argument("--lobe", nargs="+", default=None) + p_search.add_argument("--zone", nargs="+", default=None) + p_search.add_argument("--side", default=None) + p_search.add_argument("--diam-min", type=float, default=None) + p_search.add_argument("--diam-max", type=float, default=None) + p_search.add_argument("--pleural-min", type=float, default=None) + p_search.add_argument("--pleural-max", type=float, default=None) + p_search.add_argument("--population", choices=["screening", "diagnostic"], default=None) + p_search.add_argument("--label-source", choices=["histopathology", "radiology"], default=None) + p_search.add_argument("--limit", type=int, default=50) + p_search.add_argument("--sort", default=None) + p_search.add_argument("--desc", action="store_true") + p_search.set_defaults(func=cmd_search) + + # -- similar --- + p_sim = sub.add_parser("similar", help="Find similar nodules") + p_sim.add_argument("--id", required=True, help="Reference annotation_id") + p_sim.add_argument("--k", type=int, default=10) + p_sim.add_argument("--label", type=int, choices=[0, 1], default=None) + p_sim.add_argument("--datasets", nargs="+", default=None) + p_sim.add_argument("--allow-same-patient", action="store_true") + p_sim.set_defaults(func=cmd_similar) + + # -- match --- + p_match = sub.add_parser("match", help="Reinsertion anatomy matching") + p_match.add_argument("--lobe", required=True) + p_match.add_argument("--k", type=int, default=10) + p_match.add_argument("--cc-pct", type=float, default=None) + p_match.add_argument("--pleural", type=float, default=None) + p_match.add_argument("--diameter", type=float, default=None) + p_match.add_argument("--label", type=int, choices=[0, 1], default=None) + p_match.add_argument("--datasets", nargs="+", default=None) + p_match.set_defaults(func=cmd_match) + + # -- export --- + p_export = sub.add_parser("export", help="Export search results") + p_export.add_argument("-o", "--output", required=True) + p_export.add_argument("--format", choices=["csv", "json"], default="csv") + p_export.add_argument("--datasets", nargs="+", default=None) + p_export.add_argument("--label", type=int, choices=[0, 1], default=None) + p_export.add_argument("--lobe", nargs="+", default=None) + p_export.add_argument("--diam-min", type=float, default=None) + p_export.add_argument("--diam-max", type=float, default=None) + p_export.add_argument("--include-paths", action="store_true", default=True) + p_export.add_argument("--no-paths", dest="include_paths", action="store_false") + p_export.set_defaults(func=cmd_export) + + # -- info --- + p_info = sub.add_parser("info", help="Index summary statistics") + p_info.set_defaults(func=cmd_info) + + # -- detail --- + p_detail = sub.add_parser("detail", help="Full detail for a nodule") + p_detail.add_argument("--id", required=True, help="annotation_id") + p_detail.add_argument("--json", action="store_true", help="Output as JSON") + p_detail.set_defaults(func=cmd_detail) + + # -- serve --- + p_serve = sub.add_parser("serve", help="Start FastAPI server") + p_serve.add_argument("--host", default="0.0.0.0") + p_serve.add_argument("--port", type=int, default=8421) + p_serve.add_argument("--reload", action="store_true") + p_serve.set_defaults(func=cmd_serve) + + return parser + + +# --------------------------------------------------------------------------- +# Main +# --------------------------------------------------------------------------- + + +def main(): + parser = build_parser() + args = parser.parse_args() + args.func(args) + + +if __name__ == "__main__": + main() diff --git a/itrialspace/src/itrialspace/apps/retriever/engine.py b/itrialspace/src/itrialspace/apps/retriever/engine.py new file mode 100644 index 0000000000000000000000000000000000000000..4804facd23c27604e57b7e6f00ce03e517c0a633 --- /dev/null +++ b/itrialspace/src/itrialspace/apps/retriever/engine.py @@ -0,0 +1,345 @@ +""" +RetrieverEngine — top-level façade for the iTrialSpace Retriever. + +Composes FacetedSearch, SimilarityEngine, ReinsertionMatcher, PathResolver, +and NIfTISlicer into a single object for all three deployment modes. +""" + +from __future__ import annotations + +import os +from typing import Optional + +import pandas as pd + +from itrialspace import ( + MatchResult, + NoduleIndex, + ReinsertionMatcher, + ReinsertionTarget, +) +from itrialspace.apps.retriever.search import FacetedSearch, SearchFilters, SearchResult +from itrialspace.apps.retriever.similarity import SimilarityEngine, SimilarityResult +from itrialspace.apps.retriever.slicer import NIfTISlicer, SliceAxis, SliceResult +from itrialspace.io.registry import DatasetRegistry +from itrialspace.site.path_resolver import PathResolver + + +class RetrieverEngine: + """ + Unified façade: search + similarity + matching + NIfTI viewing + export. + + Usage: + engine = RetrieverEngine.from_defaults() + results = engine.search(SearchFilters(label=1, diameter_min=5)) + similar = engine.find_similar("DLCS24_n0001", k=10) + match = engine.find_reinsertion_match(lobe="right_lung_upper_lobe", ...) + sl = engine.get_slice("DLCS24", "DLCS_0001", axis="axial", index=128) + """ + + def __init__( + self, + index: NoduleIndex, + path_resolver: PathResolver, + similarity_weights: Optional[dict] = None, + matcher_weights: Optional[dict] = None, + per_dataset_norm: bool = False, + ): + self._index = index + self._resolver = path_resolver + self._search = FacetedSearch(index) + self._similarity = SimilarityEngine( + index, weights=similarity_weights, per_dataset_norm=per_dataset_norm + ) + self._matcher = ReinsertionMatcher(index, weights=matcher_weights) + self._slicer = NIfTISlicer() + + # ── Factory ─────────────────────────────────────────────────────────────── + + @classmethod + def from_defaults( + cls, + datasets_yaml: Optional[str] = None, + paths_yaml: Optional[str] = None, + base_dir: Optional[str] = None, + verbose: bool = True, + ) -> "RetrieverEngine": + """Load the full NoduleIndex from the default registry. + + Paths are resolved portably via ``itrialspace.config.settings`` when the optional + ``datasets_yaml`` / ``paths_yaml`` overrides are not given. + """ + registry = DatasetRegistry.from_yaml(datasets_yaml) + if verbose: + print("Loading NoduleIndex …") + index = NoduleIndex.from_registry(registry, verbose=verbose) + resolver = PathResolver(config_path=paths_yaml, base_dir=base_dir) + + return cls(index=index, path_resolver=resolver) + + @classmethod + def from_index( + cls, + index: NoduleIndex, + paths_yaml: Optional[str] = None, + base_dir: Optional[str] = None, + ) -> "RetrieverEngine": + """Build from a pre-loaded NoduleIndex.""" + resolver = PathResolver(config_path=paths_yaml, base_dir=base_dir) + return cls(index=index, path_resolver=resolver) + + # ── Properties ──────────────────────────────────────────────────────────── + + @property + def index(self) -> NoduleIndex: + return self._index + + @property + def resolver(self) -> PathResolver: + return self._resolver + + @property + def n_nodules(self) -> int: + return len(self._index) + + @property + def datasets(self) -> list[str]: + return self._index.datasets + + # ── A. Faceted search ───────────────────────────────────────────────────── + + def search(self, filters: Optional[SearchFilters] = None, **kwargs) -> SearchResult: + """Run a faceted search. + + Accepts either a SearchFilters object or keyword args matching + SearchFilters fields. Returns SearchResult with matching DataFrame. + """ + if filters is None: + filters = SearchFilters(**kwargs) + return self._search.search(filters) + + @property + def available_filters(self) -> dict: + return self._search.available_filters + + @property + def facet_counts(self) -> dict: + """Return facet counts for the full (unfiltered) index.""" + return self._search._compute_facets(SearchFilters()) + + # ── B. Query-by-example similarity ──────────────────────────────────────── + + def find_similar( + self, + annotation_id: str, + k: int = 10, + exclude_same_patient: bool = True, + include_datasets: Optional[list[str]] = None, + exclude_datasets: Optional[list[str]] = None, + label: Optional[int] = None, + ) -> list[SimilarityResult]: + """Find the k most similar nodules to a reference.""" + return self._similarity.find_similar( + annotation_id=annotation_id, + k=k, + exclude_same_patient=exclude_same_patient, + include_datasets=include_datasets, + exclude_datasets=exclude_datasets, + label=label, + ) + + def get_feature_vector(self, annotation_id: str) -> dict[str, float]: + """Return the normalised feature vector for a nodule.""" + return self._similarity.get_feature_vector(annotation_id) + + # ── C. Anatomy-aware reinsertion matching ───────────────────────────────── + + def find_reinsertion_match( + self, + lobe: str, + lobe_cc_pct: Optional[float] = None, + pleural_dist_mm: Optional[float] = None, + diameter_mm: Optional[float] = None, + label: Optional[int] = None, + lung_zone: Optional[str] = None, + lung_side: Optional[str] = None, + include_datasets: Optional[list[str]] = None, + exclude_datasets: Optional[list[str]] = None, + k: int = 10, + ) -> list[MatchResult]: + """Find the best reinsertion-matched donor nodules.""" + target = ReinsertionTarget( + lobe=lobe, + lobe_cc_pct=lobe_cc_pct, + pleural_dist_mm=pleural_dist_mm, + diameter_mm=diameter_mm, + label=label, + lung_zone=lung_zone, + lung_side=lung_side, + include_datasets=include_datasets or [], + exclude_datasets=exclude_datasets or [], + ) + return self._matcher.find_top_k(target, k=k) + + # ── D. CT viewer / NIfTI slicing ────────────────────────────────────────── + + def resolve_paths(self, annotation_id: str) -> dict[str, str]: + """Resolve all file paths for a nodule.""" + mask = self._index.df["annotation_id"] == annotation_id + if not mask.any(): + raise KeyError(f"annotation_id '{annotation_id}' not found") + row = self._index.df.loc[mask.idxmax()] + return self._resolver.resolve_all_paths(row) + + def get_slice( + self, + ct_path: str, + axis: str = "axial", + index: Optional[int] = None, + mask_path: Optional[str] = None, + window: str = "lung", + ) -> SliceResult: + """Extract a 2-D slice from a CT or mask volume.""" + return self._slicer.get_slice( + ct_path=ct_path, + axis=SliceAxis(axis), + index=index, + mask_path=mask_path, + window=window, + ) + + def get_nodule_view( + self, + annotation_id: str, + axis: str = "axial", + window: str = "lung", + show_mask: bool = True, + ) -> SliceResult: + """Convenience: resolve paths and get the slice at the nodule centre.""" + mask = self._index.df["annotation_id"] == annotation_id + if not mask.any(): + raise KeyError(f"annotation_id '{annotation_id}' not found") + row = self._index.df.loc[mask.idxmax()] + paths = self._resolver.resolve_all_paths(row) + + ct_path = paths["ct_path"] + mask_path = paths.get("nodule_mask_path") if show_mask else None + coord_x = float(row.get("coordX", 0)) + coord_y = float(row.get("coordY", 0)) + coord_z = float(row.get("coordZ", 0)) + + return self._slicer.get_nodule_slice( + ct_path=ct_path, + mask_path=mask_path or "", + coord_x=coord_x, + coord_y=coord_y, + coord_z=coord_z, + axis=SliceAxis(axis), + window=window, + ) + + def volume_shape(self, ct_path: str) -> tuple[int, int, int]: + """Return the 3-D shape of a NIfTI volume.""" + return self._slicer.volume_shape(ct_path) + + # ── E. Export to CohortManifest format ──────────────────────────────────── + + def export_search_csv( + self, + filters: SearchFilters, + output_path: str, + include_paths: bool = True, + ) -> str: + """Run search and export results to CSV. + + If include_paths=True, resolved absolute paths are added. + Returns the output path. + """ + result = self.search(filters) + df = result.df.copy() + + if include_paths: + path_rows = [] + for _, row in df.iterrows(): + try: + p = self._resolver.resolve_all_paths(row) + path_rows.append(p) + except Exception: + path_rows.append({}) + paths_df = pd.DataFrame(path_rows) + df = pd.concat([df, paths_df], axis=1) + + os.makedirs(os.path.dirname(output_path) or ".", exist_ok=True) + df.to_csv(output_path, index=False) + return output_path + + def export_search_json( + self, + filters: SearchFilters, + output_path: str, + include_paths: bool = True, + ) -> str: + """Run search and export results to JSON.""" + import json + + result = self.search(filters) + df = result.df.copy() + + if include_paths: + path_rows = [] + for _, row in df.iterrows(): + try: + p = self._resolver.resolve_all_paths(row) + path_rows.append(p) + except Exception: + path_rows.append({}) + paths_df = pd.DataFrame(path_rows) + df = pd.concat([df, paths_df], axis=1) + + records = df.to_dict(orient="records") + os.makedirs(os.path.dirname(output_path) or ".", exist_ok=True) + with open(output_path, "w") as f: + json.dump( + { + "n_results": len(records), + "filters": filters.to_dict(), + "results": records, + }, + f, + indent=2, + default=str, + ) + return output_path + + # ── Nodule detail ───────────────────────────────────────────────────────── + + def get_nodule_detail(self, annotation_id: str) -> dict: + """Return full detail dict for a nodule (for UI detail panel).""" + mask = self._index.df["annotation_id"] == annotation_id + if not mask.any(): + raise KeyError(f"annotation_id '{annotation_id}' not found") + + row = self._index.df.loc[mask.idxmax()] + detail = row.to_dict() + + # Add resolved paths + try: + detail["_paths"] = self._resolver.resolve_all_paths(row) + except Exception: + detail["_paths"] = {} + + # Add path existence flags + for key, path in detail.get("_paths", {}).items(): + detail[f"_exists_{key}"] = os.path.isfile(str(path)) if path else False + + return detail + + # ── Summary stats ───────────────────────────────────────────────────────── + + def summary(self) -> dict: + """Return summary statistics about the index.""" + return { + "n_nodules": len(self._index), + "datasets": self._index.datasets, + "stats": self._index.stats().to_dict(orient="index"), + } diff --git a/itrialspace/src/itrialspace/apps/retriever/notebook.py b/itrialspace/src/itrialspace/apps/retriever/notebook.py new file mode 100644 index 0000000000000000000000000000000000000000..167e8a79d999df42e584812d8f66d222643b0ca9 --- /dev/null +++ b/itrialspace/src/itrialspace/apps/retriever/notebook.py @@ -0,0 +1,344 @@ +""" +Jupyter notebook client for the iTrialSpace Retriever. + +Two modes: + 1. **Direct mode** (default): Loads the engine in-process. + 2. **API mode**: Connects to a running FastAPI backend. + +Usage (direct): + from itrialspace.apps.retriever.notebook import RetrieverClient + client = RetrieverClient() + client.search(label=1, lobe=["right_lung_upper_lobe"]) + client.find_similar("DLCS24_n0001", k=10) + client.show_nodule("DLCS24_n0001") + +Usage (API mode): + client = RetrieverClient(api_url="http://localhost:8421") +""" + +from __future__ import annotations + +from typing import Optional + +import numpy as np +import pandas as pd + +try: + import matplotlib.pyplot as plt + + HAS_MPL = True +except ImportError: + HAS_MPL = False + +try: + from IPython.display import HTML, display + from IPython.display import Image as IPImage + + HAS_IPYTHON = True +except ImportError: + HAS_IPYTHON = False + + +class RetrieverClient: + """ + Interactive Jupyter client for the iTrialSpace Retriever. + """ + + def __init__( + self, + api_url: Optional[str] = None, + datasets_yaml: Optional[str] = None, + paths_yaml: Optional[str] = None, + verbose: bool = True, + ): + self._api_url = api_url + self._engine = None + + if api_url is None: + # Direct mode — load engine + from itrialspace.apps.retriever.engine import RetrieverEngine + + self._engine = RetrieverEngine.from_defaults( + datasets_yaml=datasets_yaml, + paths_yaml=paths_yaml, + verbose=verbose, + ) + if verbose: + print(f"RetrieverClient ready — {self._engine.n_nodules:,} nodules") + + # ── Properties ──────────────────────────────────────────────────────────── + + @property + def n_nodules(self) -> int: + if self._engine: + return self._engine.n_nodules + return self._api_get("/health")["n_nodules"] + + @property + def datasets(self) -> list[str]: + if self._engine: + return self._engine.datasets + return self._api_get("/health")["datasets"] + + # ── A. Search ───────────────────────────────────────────────────────────── + + def search(self, display_results: bool = True, **kwargs) -> pd.DataFrame: + """Run a faceted search. + + All kwargs map to SearchFilters fields: + datasets, label, lobe, lung_zone, lung_side, diameter_min, diameter_max, + pleural_distance_min, pleural_distance_max, population_type, label_source, + limit, sort_by, ... + + Returns: + DataFrame of results. + """ + if self._engine: + from itrialspace.apps.retriever.search import SearchFilters + + sf = SearchFilters(**kwargs) + result = self._engine.search(sf) + df = result.df + total = result.total_matching + else: + resp = self._api_post("/search", kwargs) + df = pd.DataFrame(resp["results"]) + total = resp["total_matching"] + + if display_results and HAS_IPYTHON: + display(HTML(f"{total:,} matching, showing {len(df)}")) + display(self._format_results(df)) + return df + + # ── B. Similarity ───────────────────────────────────────────────────────── + + def find_similar( + self, + annotation_id: str, + k: int = 10, + display_results: bool = True, + **kwargs, + ) -> pd.DataFrame: + """Find the k most similar nodules to a reference. + + Extra kwargs: exclude_same_patient, include_datasets, exclude_datasets, label. + """ + if self._engine: + results = self._engine.find_similar(annotation_id=annotation_id, k=k, **kwargs) + rows = [ + { + "rank": r.rank, + "annotation_id": r.annotation_id, + "dataset": r.dataset, + "distance": round(r.distance, 4), + } + for r in results + ] + df = pd.DataFrame(rows) + else: + body = {"annotation_id": annotation_id, "k": k, **kwargs} + resp = self._api_post("/similar", body) + df = pd.DataFrame(resp["results"]) + + if display_results and HAS_IPYTHON: + display(HTML(f"Top-{k} similar to {annotation_id}")) + display(df) + return df + + # ── C. Reinsertion matching ─────────────────────────────────────────────── + + def find_match( + self, + lobe: str, + k: int = 10, + display_results: bool = True, + **kwargs, + ) -> pd.DataFrame: + """Find best reinsertion-matched donor nodules. + + Extra kwargs: lobe_cc_pct, pleural_dist_mm, diameter_mm, label, lung_zone, ... + """ + if self._engine: + results = self._engine.find_reinsertion_match(lobe=lobe, k=k, **kwargs) + rows = [ + { + "annotation_id": m.annotation_id, + "dataset": m.dataset, + "score": round(m.score, 4), + "lobe": m.lobe, + "diameter_mm": round(m.diameter_mm, 2), + "label": m.label, + } + for m in results + ] + df = pd.DataFrame(rows) + else: + body = {"lobe": lobe, "k": k, **kwargs} + resp = self._api_post("/matcher", body) + df = pd.DataFrame(resp["results"]) + + if display_results and HAS_IPYTHON: + display(HTML(f"Top-{k} matches for {lobe}")) + display(df) + return df + + # ── D. CT viewer ────────────────────────────────────────────────────────── + + def show_nodule( + self, + annotation_id: str, + axis: str = "axial", + window: str = "lung", + figsize: tuple = (8, 8), + ): + """Display the CT slice at the nodule centre with mask overlay. + + Works in both direct mode (nibabel) and API mode (PNG download). + """ + if self._engine: + try: + sl = self._engine.get_nodule_view(annotation_id, axis=axis, window=window) + self._plot_slice(sl, title=f"{annotation_id} ({axis}, {window})", figsize=figsize) + except FileNotFoundError as e: + print(f"File not found: {e}") + except Exception as e: + print(f"Error: {e}") + else: + resp = self._api_get_bytes( + f"/ct/nodule-view?annotation_id={annotation_id}&axis={axis}&window={window}" + ) + if resp and HAS_IPYTHON: + display(IPImage(data=resp)) + + def show_slice( + self, + ct_path: str, + axis: str = "axial", + index: Optional[int] = None, + mask_path: Optional[str] = None, + window: str = "lung", + figsize: tuple = (8, 8), + ): + """Display an arbitrary CT slice.""" + if self._engine: + sl = self._engine.get_slice( + ct_path=ct_path, + axis=axis, + index=index, + mask_path=mask_path, + window=window, + ) + self._plot_slice(sl, title=f"{ct_path} (z={sl.slice_index})", figsize=figsize) + else: + params = f"ct_path={ct_path}&axis={axis}&window={window}" + if index is not None: + params += f"&index={index}" + if mask_path: + params += f"&mask_path={mask_path}" + resp = self._api_get_bytes(f"/ct/slice?{params}") + if resp and HAS_IPYTHON: + display(IPImage(data=resp)) + + # ── E. Export ───────────────────────────────────────────────────────────── + + def export_csv(self, output_path: str, include_paths: bool = True, **kwargs) -> str: + """Export search results to CSV.""" + if self._engine: + from itrialspace.apps.retriever.search import SearchFilters + + sf = SearchFilters(**kwargs) + return self._engine.export_search_csv(sf, output_path, include_paths=include_paths) + else: + # Download from API + body = {"filters": kwargs, "format": "csv", "include_paths": include_paths} + import requests + + resp = requests.post(f"{self._api_url}/export", json=body, timeout=60) + resp.raise_for_status() + with open(output_path, "wb") as f: + f.write(resp.content) + return output_path + + # ── F. Nodule detail ────────────────────────────────────────────────────── + + def detail(self, annotation_id: str, display_detail: bool = True) -> dict: + """Get full detail for a nodule.""" + if self._engine: + d = self._engine.get_nodule_detail(annotation_id) + else: + d = self._api_get(f"/nodule/{annotation_id}") + + if display_detail and HAS_IPYTHON: + info = d.get("detail", d) if isinstance(d, dict) else d + rows = [(k, v) for k, v in info.items() if not str(k).startswith("_")] + display(pd.DataFrame(rows, columns=["Field", "Value"])) + return d + + # ── G. Summary ──────────────────────────────────────────────────────────── + + def summary(self) -> dict: + if self._engine: + return self._engine.summary() + return self._api_get("/health") + + # ── Internals ───────────────────────────────────────────────────────────── + + def _plot_slice(self, sl, title: str = "", figsize: tuple = (8, 8)): + """Render a SliceResult with matplotlib.""" + if not HAS_MPL: + print("matplotlib required for inline plotting") + return + + fig, ax = plt.subplots(1, 1, figsize=figsize) + ax.imshow(sl.windowed, cmap="gray", aspect="auto") + + if sl.mask is not None and sl.mask.any(): + mask_rgba = np.zeros((*sl.mask.shape, 4), dtype=np.float32) + mask_rgba[sl.mask > 0] = [1, 0.2, 0.2, 0.4] + ax.imshow(mask_rgba, aspect="auto") + + ax.set_title(title, fontsize=10) + ax.axis("off") + plt.tight_layout() + plt.show() + + @staticmethod + def _format_results(df: pd.DataFrame) -> pd.DataFrame: + """Pick display columns for nice notebook rendering.""" + cols = [ + c + for c in [ + "annotation_id", + "dataset", + "label", + "lobe_name", + "nodule_mean_diam_mm", + "pleural_distance_mm", + "reinsertion_lobe", + "reinsertion_nodule_diam_mm", + ] + if c in df.columns + ] + return df[cols] if cols else df + + def _api_get(self, path: str) -> dict: + import requests + + resp = requests.get(f"{self._api_url}{path}", timeout=15) + resp.raise_for_status() + return resp.json() + + def _api_post(self, path: str, body: dict) -> dict: + import requests + + resp = requests.post(f"{self._api_url}{path}", json=body, timeout=30) + resp.raise_for_status() + return resp.json() + + def _api_get_bytes(self, path: str) -> Optional[bytes]: + import requests + + resp = requests.get(f"{self._api_url}{path}", timeout=30) + if resp.ok: + return resp.content + return None diff --git a/itrialspace/src/itrialspace/apps/retriever/search.py b/itrialspace/src/itrialspace/apps/retriever/search.py new file mode 100644 index 0000000000000000000000000000000000000000..e3cdc6ea95a00f6438570a0445baf909bcac2dd1 --- /dev/null +++ b/itrialspace/src/itrialspace/apps/retriever/search.py @@ -0,0 +1,300 @@ +""" +FacetedSearch — multi-dimensional filtering over the NoduleIndex. + +Wraps itrialspace.NoduleQuery with a typed filter dataclass and +result-summary logic for the retriever UI layer. +""" + +from __future__ import annotations + +from dataclasses import asdict, dataclass +from typing import Optional + +import pandas as pd + +from itrialspace import ( + DATASET_NAMES, + LOBE_NAMES, + SIDE_NAMES, + ZONE_NAMES, + NoduleIndex, + NoduleQuery, +) + +# --------------------------------------------------------------------------- +# Filter specification +# --------------------------------------------------------------------------- + + +@dataclass +class SearchFilters: + """Typed, serialisable filter spec for faceted search.""" + + # Dataset selection + datasets: Optional[list[str]] = None # None = all + exclude_datasets: Optional[list[str]] = None + + # Label + label: Optional[int] = None # 0, 1, or None = any + + # Anatomy + lobe: Optional[list[str]] = None + lung_zone: Optional[list[str]] = None + lung_side: Optional[str] = None + central_peripheral: Optional[str] = None + + # Size (mm) + diameter_min: Optional[float] = None + diameter_max: Optional[float] = None + + # Distance (mm) + pleural_distance_min: Optional[float] = None + pleural_distance_max: Optional[float] = None + airway_distance_min: Optional[float] = None + airway_distance_max: Optional[float] = None + + # Reinsertion space (preferred for retrieval) + reinsertion_lobe: Optional[list[str]] = None + reinsertion_zone: Optional[list[str]] = None + reinsertion_side: Optional[str] = None + reinsertion_diameter_min: Optional[float] = None + reinsertion_diameter_max: Optional[float] = None + reinsertion_pleural_min: Optional[float] = None + reinsertion_pleural_max: Optional[float] = None + reinsertion_cc_pct_min: Optional[float] = None + reinsertion_cc_pct_max: Optional[float] = None + + # Multi-nodule + n_nodules_min: Optional[int] = None + n_nodules_max: Optional[int] = None + + # Population / label source + population_type: Optional[str] = None # "screening" | "diagnostic" + label_source: Optional[str] = None # "histopathology" | "radiology" + + # Pagination / sampling + limit: Optional[int] = None + offset: int = 0 + sample_n: Optional[int] = None + sample_seed: Optional[int] = None + + # Sort + sort_by: Optional[str] = None + sort_ascending: bool = True + + def to_dict(self) -> dict: + return {k: v for k, v in asdict(self).items() if v is not None} + + +# --------------------------------------------------------------------------- +# Search result container +# --------------------------------------------------------------------------- + + +@dataclass +class SearchResult: + """Wraps a DataFrame of matches + metadata.""" + + df: pd.DataFrame + total_matching: int + filters_applied: SearchFilters + facet_counts: Optional[dict] = None + + def __repr__(self) -> str: + shown = len(self.df) + return f"SearchResult({shown}/{self.total_matching} shown)" + + +# --------------------------------------------------------------------------- +# Faceted search engine +# --------------------------------------------------------------------------- + +# Label-source / population-type dataset maps (from spec.py) +_LABEL_SOURCE_MAP = { + "histopathology": ["DLCS24", "LUNA25", "NSCLCR", "IMDCT", "LUNGx"], + "radiology": ["LUNA16", "LNDbv4"], +} +_POPULATION_TYPE_MAP = { + "screening": ["DLCS24", "LUNA16", "LUNA25", "LNDbv4"], + "diagnostic": ["NSCLCR", "IMDCT", "LUNGx"], +} + + +class FacetedSearch: + """ + Apply SearchFilters to a NoduleIndex and return SearchResult. + + Builds a NoduleQuery chain from the filter dataclass, runs it, and + computes facet counts for the UI sidebar. + """ + + def __init__(self, index: NoduleIndex): + self._index = index + + @property + def index(self) -> NoduleIndex: + return self._index + + # ── Main entry ──────────────────────────────────────────────────────────── + + def search(self, filters: SearchFilters) -> SearchResult: + """Apply *filters* and return a SearchResult.""" + q = self._build_query(filters) + total = q.count() + + # Fetch (optionally sampled) results + if filters.sample_n is not None: + q = q.sample(filters.sample_n, seed=filters.sample_seed) + + df = q.fetch() + + # Sort + if filters.sort_by and filters.sort_by in df.columns: + df = df.sort_values(filters.sort_by, ascending=filters.sort_ascending).reset_index( + drop=True + ) + + # Paginate + if filters.limit is not None: + start = filters.offset + df = df.iloc[start : start + filters.limit].reset_index(drop=True) + + facets = self._compute_facets(filters) + + return SearchResult( + df=df, + total_matching=total, + filters_applied=filters, + facet_counts=facets, + ) + + # ── Facet counts ────────────────────────────────────────────────────────── + + def _compute_facets(self, filters: SearchFilters) -> dict: + """Compute value counts for each facet dimension. + + Uses the *unfiltered* index so users can see options outside + their current selection (like an e-commerce sidebar). + """ + df = self._index.df + facets: dict = {} + + facets["datasets"] = df["dataset"].value_counts().to_dict() + + if "lobe_name" in df.columns: + facets["lobes"] = df["lobe_name"].value_counts().to_dict() + + if "lung_zone" in df.columns: + facets["zones"] = df["lung_zone"].value_counts().to_dict() + + if "lung_side" in df.columns: + facets["sides"] = df["lung_side"].value_counts().to_dict() + + if "central_peripheral" in df.columns: + facets["central_peripheral"] = df["central_peripheral"].value_counts().to_dict() + + if "label" in df.columns: + label_counts: dict = {} + label_counts["malignant"] = int((df["label"] == 1).sum()) + label_counts["benign"] = int((df["label"] == 0).sum()) + label_counts["unlabelled"] = int(df["label"].isna().sum()) + facets["labels"] = label_counts + + # Size histogram bins + if "nodule_mean_diam_mm" in df.columns: + bins = [0, 5, 10, 15, 20, 30, 200] + lbls = ["<5mm", "5-10mm", "10-15mm", "15-20mm", "20-30mm", ">30mm"] + facets["size_buckets"] = ( + pd.cut(df["nodule_mean_diam_mm"], bins=bins, labels=lbls).value_counts().to_dict() + ) + + return facets + + # ── Query builder ───────────────────────────────────────────────────────── + + def _build_query(self, f: SearchFilters) -> NoduleQuery: + """Translate SearchFilters into a NoduleQuery chain.""" + q = self._index.query() + + # Dataset selection (label-source / population-type → dataset list) + effective_datasets = self._resolve_datasets(f) + if effective_datasets is not None: + q = q.datasets(effective_datasets) + if f.exclude_datasets: + q = q.exclude_datasets(f.exclude_datasets) + + # Label + if f.label is not None: + q = q.label(f.label) + + # Anatomy + if f.lobe: + q = q.lobe(f.lobe) + if f.lung_zone: + q = q.lung_zone(f.lung_zone) + if f.lung_side: + q = q.lung_side(f.lung_side) + if f.central_peripheral: + q = q.central_peripheral(f.central_peripheral) + + # Size + q = q.diameter(min=f.diameter_min, max=f.diameter_max) + + # Distances + q = q.pleural_distance(min=f.pleural_distance_min, max=f.pleural_distance_max) + q = q.airway_distance(min=f.airway_distance_min, max=f.airway_distance_max) + + # Reinsertion-space filters + if f.reinsertion_lobe: + q = q.reinsertion_lobe(f.reinsertion_lobe) + if f.reinsertion_zone: + q = q.reinsertion_zone(f.reinsertion_zone) + if f.reinsertion_side: + q = q.reinsertion_side(f.reinsertion_side) + q = q.reinsertion_diameter(min=f.reinsertion_diameter_min, max=f.reinsertion_diameter_max) + q = q.reinsertion_pleural(min=f.reinsertion_pleural_min, max=f.reinsertion_pleural_max) + q = q.reinsertion_cc_pct(min=f.reinsertion_cc_pct_min, max=f.reinsertion_cc_pct_max) + + # Multi-nodule + q = q.n_nodules_in_patient(min=f.n_nodules_min, max=f.n_nodules_max) + + return q + + @staticmethod + def _resolve_datasets(f: SearchFilters) -> Optional[list[str]]: + """Merge explicit datasets with label-source/population-type filters.""" + explicit = set(f.datasets) if f.datasets else None + + # Label source filter + ls_set = None + if f.label_source and f.label_source in _LABEL_SOURCE_MAP: + ls_set = set(_LABEL_SOURCE_MAP[f.label_source]) + + # Population type filter + pt_set = None + if f.population_type and f.population_type in _POPULATION_TYPE_MAP: + pt_set = set(_POPULATION_TYPE_MAP[f.population_type]) + + # Intersect all non-None sets + result = None + for s in [explicit, ls_set, pt_set]: + if s is not None: + result = s if result is None else result & s + + return list(result) if result is not None else None + + # ── Convenience: available options ──────────────────────────────────────── + + @property + def available_filters(self) -> dict: + """Return the valid values for each categorical filter.""" + return { + "datasets": DATASET_NAMES, + "lobes": LOBE_NAMES, + "zones": ZONE_NAMES, + "sides": SIDE_NAMES, + "labels": [0, 1, None], + "central_peripheral": ["central", "peripheral"], + "population_types": ["screening", "diagnostic", "all"], + "label_sources": ["histopathology", "radiology", "all"], + } diff --git a/itrialspace/src/itrialspace/apps/retriever/similarity.py b/itrialspace/src/itrialspace/apps/retriever/similarity.py new file mode 100644 index 0000000000000000000000000000000000000000..089f7f9624e499980a985be737268873fd2a1c9e --- /dev/null +++ b/itrialspace/src/itrialspace/apps/retriever/similarity.py @@ -0,0 +1,248 @@ +""" +SimilarityEngine — query-by-example nearest-neighbour retrieval. + +Given a reference nodule (by annotation_id), find the k most similar +nodules using weighted Euclidean distance over the reinsertion feature +space with optional per-dataset z-score normalisation. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Optional + +import numpy as np +import pandas as pd + +from itrialspace import NoduleIndex + +# --------------------------------------------------------------------------- +# Feature definitions +# --------------------------------------------------------------------------- + +# The 12 reinsertion columns used as the similarity feature vector. +# Categorical columns are one-hot-encoded; numeric columns are z-normalised. +_NUMERIC_FEATURES = [ + "reinsertion_lobe_cc_pct", + "reinsertion_lobe_ml_pct", + "reinsertion_lobe_ap_pct", + "reinsertion_lung_cc_pct", + "reinsertion_lung_ml_pct", + "reinsertion_lung_ap_pct", + "reinsertion_pleural_dist_mm", + "reinsertion_airway_dist_mm", + "reinsertion_nodule_diam_mm", +] + +_CATEGORICAL_FEATURES = [ + "reinsertion_lobe", + "reinsertion_lung_side", + "reinsertion_lung_zone", +] + +# Default weights (higher = more important in distance calc) +DEFAULT_WEIGHTS = { + "reinsertion_lobe_cc_pct": 1.0, + "reinsertion_lobe_ml_pct": 0.8, + "reinsertion_lobe_ap_pct": 0.8, + "reinsertion_lung_cc_pct": 0.6, + "reinsertion_lung_ml_pct": 0.5, + "reinsertion_lung_ap_pct": 0.5, + "reinsertion_pleural_dist_mm": 1.2, + "reinsertion_airway_dist_mm": 0.7, + "reinsertion_nodule_diam_mm": 1.0, + # Categorical one-hot penalty (lobe mismatch costs this much) + "_lobe_mismatch": 3.0, + "_side_mismatch": 2.0, + "_zone_mismatch": 1.5, +} + + +# --------------------------------------------------------------------------- +# Result container +# --------------------------------------------------------------------------- + + +@dataclass +class SimilarityResult: + """A single similar nodule with its distance.""" + + annotation_id: str + dataset: str + distance: float + rank: int + feature_deltas: dict # per-feature raw delta for explainability + row: pd.Series = field(repr=False) + + def __repr__(self) -> str: + return ( + f"SimilarityResult(rank={self.rank} | d={self.distance:.4f} | " + f"{self.dataset}/{self.annotation_id})" + ) + + +# --------------------------------------------------------------------------- +# Similarity engine +# --------------------------------------------------------------------------- + + +class SimilarityEngine: + """ + Weighted nearest-neighbour search over reinsertion feature space. + + On construction the engine z-normalises numeric features (globally or + per-dataset, controlled by *per_dataset_norm*) and caches the result + matrix for O(n) distance lookups. + """ + + def __init__( + self, + index: NoduleIndex, + weights: Optional[dict[str, float]] = None, + per_dataset_norm: bool = False, + ): + self._index = index + self._weights = {**DEFAULT_WEIGHTS, **(weights or {})} + self._per_dataset = per_dataset_norm + + # Build normalised feature matrix + self._df = index.df.copy() + self._feat_matrix, self._feat_cols = self._build_features() + + # ── Public API ──────────────────────────────────────────────────────────── + + def find_similar( + self, + annotation_id: str, + k: int = 10, + exclude_same_patient: bool = True, + include_datasets: Optional[list[str]] = None, + exclude_datasets: Optional[list[str]] = None, + label: Optional[int] = None, + ) -> list[SimilarityResult]: + """Find the k most similar nodules to the given reference. + + Args: + annotation_id: The reference nodule. + k: Number of results to return. + exclude_same_patient: Exclude nodules from the same patient. + include_datasets: Restrict search to these datasets. + exclude_datasets: Exclude these datasets. + label: Filter by label (0, 1, or None for any). + + Returns: + List of SimilarityResult sorted by distance ascending. + """ + ref_mask = self._df["annotation_id"] == annotation_id + if not ref_mask.any(): + raise KeyError(f"annotation_id '{annotation_id}' not found in index") + + ref_idx = ref_mask.idxmax() + ref_row = self._df.loc[ref_idx] + ref_vec = self._feat_matrix[ref_idx] + + # Build candidate mask + cand_mask = ~ref_mask # exclude self + if exclude_same_patient: + cand_mask &= self._df["patient_id"] != ref_row["patient_id"] + if include_datasets: + cand_mask &= self._df["dataset"].isin(include_datasets) + if exclude_datasets: + cand_mask &= ~self._df["dataset"].isin(exclude_datasets) + if label is not None: + cand_mask &= self._df["label"] == label + + cand_indices = self._df.index[cand_mask].to_numpy() + if len(cand_indices) == 0: + return [] + + # Compute distances + cand_vecs = self._feat_matrix[cand_indices] + dists = np.linalg.norm(cand_vecs - ref_vec, axis=1) + + # Top-k + top_k_local = np.argsort(dists)[:k] + top_k_global = cand_indices[top_k_local] + top_k_dists = dists[top_k_local] + + results = [] + for rank, (gi, d) in enumerate(zip(top_k_global, top_k_dists), 1): + row = self._df.loc[gi] + deltas = self._compute_deltas(ref_vec, self._feat_matrix[gi]) + results.append( + SimilarityResult( + annotation_id=str(row["annotation_id"]), + dataset=str(row["dataset"]), + distance=float(d), + rank=rank, + feature_deltas=deltas, + row=row, + ) + ) + return results + + def get_feature_vector(self, annotation_id: str) -> dict[str, float]: + """Return the normalised feature vector for a nodule.""" + mask = self._df["annotation_id"] == annotation_id + if not mask.any(): + raise KeyError(f"annotation_id '{annotation_id}' not found") + idx = mask.idxmax() + return dict(zip(self._feat_cols, self._feat_matrix[idx])) + + # ── Internals ───────────────────────────────────────────────────────────── + + def _build_features(self) -> tuple[np.ndarray, list[str]]: + """Build the normalised numeric + one-hot feature matrix.""" + df = self._df + feat_cols: list[str] = [] + feat_arrays: list[np.ndarray] = [] + + # Numeric features — z-score normalise + for col in _NUMERIC_FEATURES: + if col not in df.columns: + continue + raw = df[col].fillna(0.0).to_numpy(dtype=np.float64) + w = self._weights.get(col, 1.0) + + if self._per_dataset: + normed = np.zeros_like(raw) + for ds in df["dataset"].unique(): + ds_mask = (df["dataset"] == ds).to_numpy() + subset = raw[ds_mask] + mu, sigma = subset.mean(), subset.std() + sigma = max(sigma, 1e-8) + normed[ds_mask] = (subset - mu) / sigma + else: + mu, sigma = raw.mean(), raw.std() + sigma = max(sigma, 1e-8) + normed = (raw - mu) / sigma + + feat_arrays.append(normed * w) + feat_cols.append(col) + + # Categorical features — one-hot with mismatch penalty + penalty_map = { + "reinsertion_lobe": self._weights.get("_lobe_mismatch", 3.0), + "reinsertion_lung_side": self._weights.get("_side_mismatch", 2.0), + "reinsertion_lung_zone": self._weights.get("_zone_mismatch", 1.5), + } + for col in _CATEGORICAL_FEATURES: + if col not in df.columns: + continue + penalty = penalty_map.get(col, 1.0) + dummies = pd.get_dummies(df[col], prefix=col).to_numpy(dtype=np.float64) + dummies *= penalty + for i in range(dummies.shape[1]): + feat_cols.append(f"{col}_{i}") + feat_arrays.append(dummies) + + matrix = np.column_stack(feat_arrays) if feat_arrays else np.zeros((len(df), 0)) + return matrix, feat_cols + + def _compute_deltas(self, ref_vec: np.ndarray, cand_vec: np.ndarray) -> dict[str, float]: + """Per-feature delta for explainability.""" + deltas = {} + for i, col in enumerate(self._feat_cols): + if i < len(ref_vec): + deltas[col] = float(cand_vec[i] - ref_vec[i]) + return deltas diff --git a/itrialspace/src/itrialspace/apps/retriever/slicer.py b/itrialspace/src/itrialspace/apps/retriever/slicer.py new file mode 100644 index 0000000000000000000000000000000000000000..a41a19ddca249e5e35e088fb373d170ee7d425c9 --- /dev/null +++ b/itrialspace/src/itrialspace/apps/retriever/slicer.py @@ -0,0 +1,312 @@ +""" +NIfTISlicer — extract 2-D slices from NIfTI CT/mask volumes. + +Supports axial, coronal, sagittal views with optional overlay of +nodule masks or organ segmentations. Returns numpy arrays that +can be converted to PNG by the API layer or rendered directly in +matplotlib / Streamlit. +""" + +from __future__ import annotations + +import io +import os +from dataclasses import dataclass +from enum import Enum +from typing import Optional + +import numpy as np + +try: + import nibabel as nib +except ImportError: + nib = None # type: ignore[assignment] + +try: + from PIL import Image +except ImportError: + Image = None # type: ignore[assignment] + + +class SliceAxis(str, Enum): + AXIAL = "axial" # Z-axis + CORONAL = "coronal" # Y-axis + SAGITTAL = "sagittal" # X-axis + + +@dataclass +class SliceResult: + """A rendered 2-D slice with metadata.""" + + image: np.ndarray # 2-D float array (HU or normalised) + mask: Optional[np.ndarray] # 2-D binary mask (or None) + axis: SliceAxis + slice_index: int + shape_3d: tuple[int, int, int] + window_center: float + window_width: float + spacing_mm: tuple[float, float, float] + + @property + def windowed(self) -> np.ndarray: + """Apply CT window and return uint8 [0, 255].""" + lo = self.window_center - self.window_width / 2 + hi = self.window_center + self.window_width / 2 + img = np.clip(self.image, lo, hi) + img = ((img - lo) / (hi - lo) * 255).astype(np.uint8) + return img + + def to_png_bytes(self, overlay_alpha: float = 0.35, labels: bool = True) -> bytes: + """Render as PNG bytes with optional mask overlay and orientation labels.""" + if Image is None: + raise ImportError("Pillow is required: pip install Pillow") + + base = self.windowed + rgb = np.stack([base, base, base], axis=-1) # grayscale → RGB + + if self.mask is not None and self.mask.any(): + overlay = np.zeros_like(rgb) + overlay[self.mask > 0] = [255, 50, 50] # red overlay + alpha = overlay_alpha + blended = (rgb.astype(float) * (1 - alpha) + overlay.astype(float) * alpha).astype( + np.uint8 + ) + # Only blend where mask is active + rgb[self.mask > 0] = blended[self.mask > 0] + + img = Image.fromarray(rgb) + + # ── Orientation labels (radiology convention) ────────────────── + if labels: + from PIL import ImageDraw, ImageFont + + draw = ImageDraw.Draw(img) + try: + font = ImageFont.truetype( + "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 14 + ) + except (IOError, OSError): + font = ImageFont.load_default() + + h_img, w_img = rgb.shape[0], rgb.shape[1] + label_color = (255, 255, 0) # yellow + shadow = (0, 0, 0) + m = 4 # margin + + def _lbl(x, y, text, anchor=None): + draw.text((x + 1, y + 1), text, fill=shadow, font=font, anchor=anchor) + draw.text((x, y), text, fill=label_color, font=font, anchor=anchor) + + if self.axis == SliceAxis.AXIAL: + _lbl(m, h_img // 2, "R", "lm") # left = patient-Right + _lbl(w_img - m, h_img // 2, "L", "rm") # right = patient-Left + _lbl(w_img // 2, m, "A", "mt") # top = Anterior + _lbl(w_img // 2, h_img - m, "P", "mb") # bot = Posterior + elif self.axis == SliceAxis.CORONAL: + _lbl(m, h_img // 2, "R", "lm") + _lbl(w_img - m, h_img // 2, "L", "rm") + _lbl(w_img // 2, m, "S", "mt") # top = Superior + _lbl(w_img // 2, h_img - m, "I", "mb") # bot = Inferior + elif self.axis == SliceAxis.SAGITTAL: + _lbl(m, h_img // 2, "A", "lm") # left = Anterior + _lbl(w_img - m, h_img // 2, "P", "rm") # right = Posterior + _lbl(w_img // 2, m, "S", "mt") + _lbl(w_img // 2, h_img - m, "I", "mb") + + buf = io.BytesIO() + img.save(buf, format="PNG") + return buf.getvalue() + + +# Default CT window presets +WINDOW_PRESETS = { + "lung": {"center": -600, "width": 1500}, + "mediastinum": {"center": 40, "width": 400}, + "bone": {"center": 400, "width": 1800}, + "soft_tissue": {"center": 50, "width": 350}, +} + + +class NIfTISlicer: + """ + Load NIfTI volumes and extract 2-D slices for the viewer. + + Uses a small LRU cache to avoid re-loading the same volume + on sequential slice requests (e.g. scrolling through axial slices). + """ + + def __init__(self, cache_size: int = 4): + if nib is None: + raise ImportError("nibabel is required: pip install nibabel") + self._cache: dict[str, np.ndarray] = {} + self._cache_order: list[str] = [] + self._cache_size = cache_size + self._affine_cache: dict[str, np.ndarray] = {} + + # ── Volume loading ──────────────────────────────────────────────────────── + + def _load(self, path: str) -> tuple[np.ndarray, np.ndarray]: + """Load a NIfTI volume, reorient to RAS+ canonical, return (data, affine).""" + if path in self._cache: + return self._cache[path], self._affine_cache[path] + + if not os.path.isfile(path): + raise FileNotFoundError(f"NIfTI file not found: {path}") + + img = nib.load(path) + # Reorient to RAS+ canonical so axes are always: + # axis-0 = R→L (X), axis-1 = A→P (Y), axis-2 = I→S (Z) + canon = nib.as_closest_canonical(img) + data = np.asarray(canon.dataobj, dtype=np.float32) + + # Squeeze extra dims (some files are 5-D) + while data.ndim > 3: + data = data[..., 0] + + affine = canon.affine + + # Cache management (LRU eviction) + if len(self._cache) >= self._cache_size: + evict = self._cache_order.pop(0) + self._cache.pop(evict, None) + self._affine_cache.pop(evict, None) + self._cache[path] = data + self._affine_cache[path] = affine + self._cache_order.append(path) + + return data, affine + + def volume_shape(self, path: str) -> tuple[int, int, int]: + """Return the 3-D shape of a NIfTI volume.""" + data, _ = self._load(path) + return data.shape[:3] # type: ignore[return-value] + + def voxel_spacing(self, path: str) -> tuple[float, float, float]: + """Return voxel spacing in mm from the affine.""" + _, affine = self._load(path) + spacing = np.abs(np.diag(affine)[:3]) + return tuple(float(s) for s in spacing) # type: ignore[return-value] + + # ── Slice extraction ────────────────────────────────────────────────────── + + def get_slice( + self, + ct_path: str, + axis: SliceAxis = SliceAxis.AXIAL, + index: Optional[int] = None, + mask_path: Optional[str] = None, + window: str = "lung", + window_center: Optional[float] = None, + window_width: Optional[float] = None, + ) -> SliceResult: + """Extract a 2-D slice from a CT volume. + + Args: + ct_path: Path to CT NIfTI. + axis: Slice orientation. + index: Slice index. None = middle slice. + mask_path: Optional path to mask NIfTI for overlay. + window: CT window preset name. + window_center: Override window center. + window_width: Override window width. + """ + data, affine = self._load(ct_path) + shape = data.shape[:3] + spacing = tuple(float(s) for s in np.abs(np.diag(affine)[:3])) + + # Determine axis dimension + axis_dim = {"axial": 2, "coronal": 1, "sagittal": 0}[axis.value] + max_idx = shape[axis_dim] - 1 + + if index is None: + index = max_idx // 2 + index = max(0, min(index, max_idx)) + + # Extract slice and apply radiology display transform. + # After RAS+ canonical load: + # axis-0 = R→L (X), axis-1 = A→P (Y), axis-2 = I→S (Z) + if axis_dim == 2: # Axial — fixed Z, shows (X, Y) plane + img_slice = data[:, :, index] + elif axis_dim == 1: # Coronal — fixed Y, shows (X, Z) plane + img_slice = data[:, index, :] + else: # Sagittal — fixed X, shows (Y, Z) plane + img_slice = data[index, :, :] + + # Apply radiology display transform: + # Axial: .T → (Y,X) then fliplr (R on left) then flipud (A at top) + # Coronal: .T → (Z,X) then fliplr (R on left) then flipud (S at top) + # Sagittal: .T → (Z,Y) then fliplr (A on left) then flipud (S at top) + img_slice = np.flipud(np.fliplr(img_slice.T)) + + # Mask overlay + mask_slice = None + if mask_path and os.path.isfile(mask_path): + mask_data, _ = self._load(mask_path) + # Ensure compatible shape + if mask_data.shape[:3] == shape: + if axis_dim == 2: + mask_slice = mask_data[:, :, index] + elif axis_dim == 1: + mask_slice = mask_data[:, index, :] + else: + mask_slice = mask_data[index, :, :] + # Same radiology display transform as CT + mask_slice = np.flipud(np.fliplr(mask_slice.T)) + mask_slice = (mask_slice > 0).astype(np.uint8) + + # Window + wc = ( + window_center + if window_center is not None + else WINDOW_PRESETS.get(window, WINDOW_PRESETS["lung"])["center"] + ) + ww = ( + window_width + if window_width is not None + else WINDOW_PRESETS.get(window, WINDOW_PRESETS["lung"])["width"] + ) + + return SliceResult( + image=img_slice, + mask=mask_slice, + axis=SliceAxis(axis), + slice_index=index, + shape_3d=shape, # type: ignore[arg-type] + window_center=wc, + window_width=ww, + spacing_mm=spacing, # type: ignore[arg-type] + ) + + def get_nodule_slice( + self, + ct_path: str, + mask_path: str, + coord_x: float, + coord_y: float, + coord_z: float, + axis: SliceAxis = SliceAxis.AXIAL, + window: str = "lung", + ) -> SliceResult: + """Extract the slice passing through the nodule centre. + + Coordinates are in world/physical space (mm) as stored in the + nodule profile CSVs. We convert to voxel indices using the + inverse affine. + """ + data, affine = self._load(ct_path) + inv = np.linalg.inv(affine) + world = np.array([coord_x, coord_y, coord_z, 1.0]) + voxel = inv @ world + + # Map axis → voxel dimension + axis_to_dim = {"axial": 2, "coronal": 1, "sagittal": 0} + dim = axis_to_dim[axis.value] + idx = int(round(voxel[dim])) + + return self.get_slice( + ct_path, + axis=axis, + index=idx, + mask_path=mask_path, + window=window, + ) diff --git a/itrialspace/src/itrialspace/apps/retriever/ui/__init__.py b/itrialspace/src/itrialspace/apps/retriever/ui/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/itrialspace/src/itrialspace/apps/retriever/ui/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/apps/retriever/ui/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ba9bc66780dcd05f26bcd6aed8846190549cd2f Binary files /dev/null and b/itrialspace/src/itrialspace/apps/retriever/ui/__pycache__/__init__.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/apps/retriever/ui/__pycache__/app.cpython-310.pyc b/itrialspace/src/itrialspace/apps/retriever/ui/__pycache__/app.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f909616f95f8247ed6c6a7172d120b40cc05bca3 Binary files /dev/null and b/itrialspace/src/itrialspace/apps/retriever/ui/__pycache__/app.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/apps/retriever/ui/app.py b/itrialspace/src/itrialspace/apps/retriever/ui/app.py new file mode 100644 index 0000000000000000000000000000000000000000..9cc5cdf04dce6ffb5c7359067ee6f730bfe69518 --- /dev/null +++ b/itrialspace/src/itrialspace/apps/retriever/ui/app.py @@ -0,0 +1,763 @@ +""" +Streamlit frontend for the iTrialSpace Retriever. + +Launch: + streamlit run retriever/ui/app.py -- [--api-url http://localhost:8421] + +Two modes: + 1. **Direct mode** (default): Loads the NoduleIndex in-process. + 2. **API mode** (--api-url): Calls the FastAPI backend via requests. +""" + +from __future__ import annotations + +import sys +from typing import Optional + +import numpy as np +import pandas as pd +import streamlit as st + +# --------------------------------------------------------------------------- +# Mode detection (direct vs API) +# --------------------------------------------------------------------------- + + +def _parse_api_url() -> Optional[str]: + """Check for --api-url flag in sys.argv (Streamlit passes args after --).""" + for i, arg in enumerate(sys.argv): + if arg == "--api-url" and i + 1 < len(sys.argv): + return sys.argv[i + 1] + return None + + +API_URL = _parse_api_url() + +# --------------------------------------------------------------------------- +# Engine / API wrappers +# --------------------------------------------------------------------------- + + +@st.cache_resource(show_spinner="Loading 13k+ nodules …") +def _load_engine(): + """Load the retriever engine in direct mode.""" + from itrialspace.apps.retriever.engine import RetrieverEngine + + return RetrieverEngine.from_defaults(verbose=True) + + +def _search(filters: dict) -> dict: + """Run a search, returning {total_matching, results (list[dict]), facet_counts}.""" + if API_URL: + import requests + + resp = requests.post(f"{API_URL}/search", json=filters, timeout=30) + resp.raise_for_status() + return resp.json() + else: + from itrialspace.apps.retriever.search import SearchFilters + + engine = _load_engine() + sf = SearchFilters(**{k: v for k, v in filters.items() if v is not None}) + result = engine.search(sf) + rows = result.df.to_dict(orient="records") + # Serialise NaN + for r in rows: + for k, v in r.items(): + if isinstance(v, float) and np.isnan(v): + r[k] = None + return { + "total_matching": result.total_matching, + "results": rows, + "facet_counts": result.facet_counts, + } + + +def _find_similar(annotation_id: str, k: int, **kwargs) -> list[dict]: + if API_URL: + import requests + + body = {"annotation_id": annotation_id, "k": k, **kwargs} + resp = requests.post(f"{API_URL}/similar", json=body, timeout=30) + resp.raise_for_status() + return resp.json()["results"] + else: + engine = _load_engine() + results = engine.find_similar(annotation_id=annotation_id, k=k, **kwargs) + return [ + { + "annotation_id": r.annotation_id, + "dataset": r.dataset, + "distance": round(r.distance, 4), + "rank": r.rank, + } + for r in results + ] + + +def _find_match(lobe: str, k: int = 10, **kwargs) -> list[dict]: + if API_URL: + import requests + + body = {"lobe": lobe, "k": k, **kwargs} + resp = requests.post(f"{API_URL}/matcher", json=body, timeout=30) + resp.raise_for_status() + return resp.json()["results"] + else: + engine = _load_engine() + results = engine.find_reinsertion_match(lobe=lobe, k=k, **kwargs) + return [ + { + "annotation_id": m.annotation_id, + "dataset": m.dataset, + "score": round(m.score, 4), + "lobe": m.lobe, + "diameter_mm": round(m.diameter_mm, 2), + "label": m.label, + } + for m in results + ] + + +def _get_nodule_detail(annotation_id: str) -> dict: + if API_URL: + import requests + + resp = requests.get(f"{API_URL}/nodule/{annotation_id}", timeout=15) + resp.raise_for_status() + return resp.json() + else: + engine = _load_engine() + return engine.get_nodule_detail(annotation_id) + + +def _get_slice_png( + ct_path: str, axis: str, index: int, mask_path: str = None, window: str = "lung" +) -> Optional[bytes]: + """Return PNG bytes for a CT slice.""" + if API_URL: + import requests + + params = {"ct_path": ct_path, "axis": axis, "index": index, "window": window} + if mask_path: + params["mask_path"] = mask_path + resp = requests.get(f"{API_URL}/ct/slice", params=params, timeout=30) + if resp.ok: + return resp.content + return None + else: + try: + engine = _load_engine() + sl = engine.get_slice( + ct_path=ct_path, axis=axis, index=index, mask_path=mask_path, window=window + ) + return sl.to_png_bytes() + except Exception: + return None + + +def _get_nodule_view_png( + annotation_id: str, axis: str = "axial", window: str = "lung", show_mask: bool = True +) -> Optional[bytes]: + """Return PNG bytes for the CT slice at the nodule centre.""" + if API_URL: + import requests + + params = { + "annotation_id": annotation_id, + "axis": axis, + "window": window, + "show_mask": show_mask, + } + resp = requests.get(f"{API_URL}/ct/nodule-view", params=params, timeout=30) + if resp.ok: + return resp.content + return None + else: + try: + engine = _load_engine() + sl = engine.get_nodule_view( + annotation_id, axis=axis, window=window, show_mask=show_mask + ) + return sl.to_png_bytes() + except Exception: + return None + + +def _get_volume_info(ct_path: str) -> Optional[dict]: + """Return {shape, spacing_mm} for a CT volume.""" + if API_URL: + import requests + + resp = requests.get(f"{API_URL}/ct/info", params={"ct_path": ct_path}, timeout=15) + if resp.ok: + return resp.json() + return None + else: + try: + engine = _load_engine() + shape = engine.volume_shape(ct_path) + spacing = engine._slicer.voxel_spacing(ct_path) + return {"shape": list(shape), "spacing_mm": [round(s, 3) for s in spacing]} + except Exception: + return None + + +def _resolve_paths(annotation_id: str) -> dict: + """Resolve all file paths for a nodule.""" + if API_URL: + import requests + + resp = requests.get(f"{API_URL}/nodule/{annotation_id}", timeout=15) + if resp.ok: + data = resp.json() + return data.get("paths", {}) + return {} + else: + try: + engine = _load_engine() + return engine.resolve_paths(annotation_id) + except Exception: + return {} + + +def _available_filters() -> dict: + if API_URL: + import requests + + resp = requests.get(f"{API_URL}/filters", timeout=10) + resp.raise_for_status() + return resp.json() + else: + engine = _load_engine() + return engine.available_filters + + +# --------------------------------------------------------------------------- +# Streamlit UI +# --------------------------------------------------------------------------- + + +# --------------------------------------------------------------------------- +# Branding (consistent with the NoduleMap viewer) +# --------------------------------------------------------------------------- + +APP_VERSION = "0.1.0" +ACCENT = "#4a9eff" +ORG = "Anonymized Lab · Dept. of [Anonymized] · [Anonymized Institution]" +DISCLAIMER = "For research use only — not for clinical use." + + +def _render_brand_header(): + st.markdown( + f""" + +
+ 🫁 + +
iTrialSpace·Retriever
+
{ORG}
+
+ + v{APP_VERSION} +
+ """, + unsafe_allow_html=True, + ) + + +def _render_about(): + with st.sidebar.expander("ℹ About"): + st.markdown(f""" +**iTrialSpace · Retriever** — browse, visualize, and export lung-nodule data across +**13,140 nodules / 7 datasets**. Faceted search, query-by-example similarity, and +reinsertion donor matching (clinical `ReinsertionMatcher` metric), with a CT-slice viewer +and CSV/JSON export. + +_Repository link removed for blinded review._ + +⚠ **{DISCLAIMER}** Not a medical device. +""") + + +def _render_footer(): + st.markdown( + f""" +
+ ⚠ {DISCLAIMER} +
+ """, + unsafe_allow_html=True, + ) + + +def _download_buttons(df: pd.DataFrame, stem: str): + """CSV + JSON download buttons for a result DataFrame (consistent across modes).""" + st.subheader("Export") + c1, c2 = st.columns(2) + with c1: + st.download_button( + "⬇ Download CSV", + df.to_csv(index=False), + file_name=f"{stem}.csv", + mime="text/csv", + key=f"dl_csv_{stem}", + ) + with c2: + st.download_button( + "⬇ Download JSON", + df.to_json(orient="records", indent=2, default_handler=str), + file_name=f"{stem}.json", + mime="application/json", + key=f"dl_json_{stem}", + ) + + +def main(): + st.set_page_config( + page_title="iTrialSpace · Retriever", + page_icon="🫁", + layout="wide", + initial_sidebar_state="expanded", + ) + + _render_brand_header() + st.caption("Interactive retrieval across 13,140 lung nodules from 7 datasets") + + # Sidebar filters + with st.sidebar: + st.header("Filters") + af = _available_filters() + + # Tabs for different modes + mode = st.radio("Mode", ["Search", "Similarity", "Matcher"], horizontal=True) + + if mode == "Search": + filters = _build_search_sidebar(af) + elif mode == "Similarity": + sim_params = _build_similarity_sidebar() + else: + match_params = _build_matcher_sidebar(af) + + _render_about() + + # Main content area + if mode == "Search": + _render_search(filters) + elif mode == "Similarity": + _render_similarity(sim_params) + else: + _render_matcher(match_params) + + _render_footer() + + +# --------------------------------------------------------------------------- +# Sidebar builders +# --------------------------------------------------------------------------- + + +def _build_search_sidebar(af: dict) -> dict: + """Build the faceted search sidebar, return filter dict.""" + filters: dict = {} + + # Dataset multi-select + ds_options = af.get("datasets", []) + selected_ds = st.multiselect("Datasets", ds_options, default=None) + if selected_ds: + filters["datasets"] = selected_ds + + # Label + label_choice = st.selectbox("Label", ["Any", "Malignant (1)", "Benign (0)"]) + if label_choice == "Malignant (1)": + filters["label"] = 1 + elif label_choice == "Benign (0)": + filters["label"] = 0 + + # Lobe + lobe_options = af.get("lobes", []) + selected_lobes = st.multiselect("Lobe", lobe_options, default=None) + if selected_lobes: + filters["lobe"] = selected_lobes + + # Zone + zone_options = af.get("zones", []) + selected_zones = st.multiselect("Zone", zone_options, default=None) + if selected_zones: + filters["lung_zone"] = selected_zones + + # Side + side = st.selectbox("Side", ["Any", "left", "right"]) + if side != "Any": + filters["lung_side"] = side + + # Central/peripheral + cp = st.selectbox("Position", ["Any", "central", "peripheral"]) + if cp != "Any": + filters["central_peripheral"] = cp + + # Diameter range + st.subheader("Size (mm)") + diam_range = st.slider("Diameter", 0.0, 100.0, (0.0, 100.0), step=1.0) + if diam_range[0] > 0: + filters["diameter_min"] = diam_range[0] + if diam_range[1] < 100: + filters["diameter_max"] = diam_range[1] + + # Pleural distance + st.subheader("Pleural distance") + pleural = st.slider("Pleural distance (mm)", 0.0, 80.0, (0.0, 80.0), step=1.0) + if pleural[0] > 0: + filters["pleural_distance_min"] = pleural[0] + if pleural[1] < 80: + filters["pleural_distance_max"] = pleural[1] + + # Population type + pop = st.selectbox("Population type", ["Any", "screening", "diagnostic"]) + if pop != "Any": + filters["population_type"] = pop + + # Label source + ls = st.selectbox("Label source", ["Any", "histopathology", "radiology"]) + if ls != "Any": + filters["label_source"] = ls + + # Limit + filters["limit"] = st.number_input("Max results", 10, 5000, 200, step=50) + + # Sort + sort_col = st.selectbox( + "Sort by", + [ + "None", + "nodule_mean_diam_mm", + "pleural_distance_mm", + "reinsertion_lobe_cc_pct", + "dataset", + "lobe_name", + ], + ) + if sort_col != "None": + filters["sort_by"] = sort_col + filters["sort_ascending"] = st.checkbox("Ascending", value=True) + + return filters + + +def _build_similarity_sidebar() -> dict: + """Build the similarity query sidebar.""" + params: dict = {} + params["annotation_id"] = st.text_input( + "Reference annotation_id", placeholder="e.g. DLCS24_n0001" + ) + params["k"] = st.slider("Top-K", 1, 100, 10) + params["exclude_same_patient"] = st.checkbox("Exclude same patient", value=True) + + label_choice = st.selectbox("Label filter", ["Any", "Malignant (1)", "Benign (0)"]) + if label_choice == "Malignant (1)": + params["label"] = 1 + elif label_choice == "Benign (0)": + params["label"] = 0 + + return params + + +def _build_matcher_sidebar(af: dict) -> dict: + """Build the reinsertion matcher sidebar.""" + params: dict = {} + lobe_options = af.get("lobes", []) + params["lobe"] = st.selectbox("Target lobe", lobe_options) + params["k"] = st.slider("Top-K", 1, 100, 10) + + params["lobe_cc_pct"] = st.slider("Lobe CC %", 0.0, 100.0, 50.0, step=1.0) + params["pleural_dist_mm"] = st.number_input("Pleural dist (mm)", 0.0, 100.0, 15.0, step=1.0) + params["diameter_mm"] = st.number_input("Target diameter (mm)", 1.0, 60.0, 10.0, step=0.5) + + label_choice = st.selectbox("Label", ["Any", "Malignant (1)", "Benign (0)"]) + if label_choice == "Malignant (1)": + params["label"] = 1 + elif label_choice == "Benign (0)": + params["label"] = 0 + + return params + + +# --------------------------------------------------------------------------- +# Main content renderers +# --------------------------------------------------------------------------- + + +def _render_search(filters: dict): + """Render faceted search results.""" + if st.sidebar.button("Search", type="primary"): + with st.spinner("Searching …"): + data = _search(filters) + st.session_state["search_data"] = data + + # Render from session_state so the page survives widget interactions + data = st.session_state.get("search_data") + if data is None: + st.info("Configure filters in the sidebar and click **Search**.") + return + + total = data["total_matching"] + results = data["results"] + facets = data.get("facet_counts", {}) + + st.metric("Total matching", f"{total:,}") + + # Facet counts in expander + if facets: + with st.expander("Facet counts (full index)"): + for facet_name, counts in facets.items(): + st.write(f"**{facet_name}**") + st.json(counts) + + if results: + df = pd.DataFrame(results) + display_cols = [ + c + for c in [ + "annotation_id", + "dataset", + "label", + "lobe_name", + "lung_side", + "lung_zone", + "central_peripheral", + "nodule_mean_diam_mm", + "pleural_distance_mm", + "reinsertion_lobe", + "reinsertion_nodule_diam_mm", + ] + if c in df.columns + ] + st.dataframe(df[display_cols], use_container_width=True, height=500) + + # Detail viewer + st.subheader("Nodule detail") + selected_id = st.selectbox( + "Select nodule for detail", + df["annotation_id"].tolist() if "annotation_id" in df.columns else [], + key="search_detail_select", + ) + if selected_id: + _render_detail(selected_id) + + # Export + _download_buttons(df, "itrialspace_search") + else: + st.info("No results. Adjust filters and try again.") + + +def _render_similarity(params: dict): + """Render similarity results with CT viewer for similar nodules.""" + aid = params.get("annotation_id", "").strip() + if not aid: + st.info("Enter a reference annotation_id in the sidebar to find similar nodules.") + return + + if st.sidebar.button("Find similar", type="primary"): + with st.spinner("Computing similarity …"): + kwargs = { + k: v for k, v in params.items() if k not in ("annotation_id", "k") and v is not None + } + results = _find_similar(aid, params["k"], **kwargs) + + if results: + st.session_state["sim_results"] = results + st.session_state["sim_ref"] = aid + else: + st.session_state.pop("sim_results", None) + st.warning("No similar nodules found.") + return + + results = st.session_state.get("sim_results") + aid = st.session_state.get("sim_ref", aid) + if not results: + return + + st.subheader(f"Top-{len(results)} similar to {aid}") + df = pd.DataFrame(results) + st.dataframe(df, use_container_width=True) + _download_buttons(df, "itrialspace_similar") + + # ── Window preset for all CT views in this section + sim_window = st.selectbox( + "CT window (for all views below)", + ["lung", "mediastinum", "soft_tissue", "bone"], + key="sim_ct_window", + ) + + # ── Reference nodule + with st.expander("Reference nodule detail", expanded=True): + _render_detail(aid) + + # ── Similar nodules — CT comparison + st.subheader("Compare similar nodules") + sim_ids = [r["annotation_id"] for r in results if "annotation_id" in r] + if not sim_ids: + return + + selected_sim = st.multiselect( + "Select similar nodules to view", + sim_ids, + default=sim_ids[: min(3, len(sim_ids))], + key="sim_compare_select", + ) + + if selected_sim: + # Show in a grid: up to 3 per row + for row_start in range(0, len(selected_sim), 3): + row_ids = selected_sim[row_start : row_start + 3] + cols = st.columns(len(row_ids)) + for col, sid in zip(cols, row_ids): + with col: + st.markdown(f"**{sid}**") + match = next((r for r in results if r.get("annotation_id") == sid), {}) + dist = match.get("distance", "?") + diam = match.get("nodule_mean_diam_mm", "?") + lobe = match.get("lobe_name", "?") + label = match.get("label", "?") + st.caption(f"dist={dist} | diam={diam}mm | {lobe} | label={label}") + + png = _get_nodule_view_png(sid, axis="axial", window=sim_window, show_mask=True) + if png: + st.image(png, use_container_width=True) + else: + st.warning("CT unavailable") + + +def _render_matcher(params: dict): + """Render reinsertion matcher results.""" + if st.sidebar.button("Find matches", type="primary"): + with st.spinner("Matching …"): + kwargs = {k: v for k, v in params.items() if k not in ("lobe", "k") and v is not None} + results = _find_match(params["lobe"], params["k"], **kwargs) + st.session_state["matcher_results"] = results + st.session_state["matcher_params"] = {"k": params["k"], "lobe": params["lobe"]} + + results = st.session_state.get("matcher_results") + mp = st.session_state.get("matcher_params", {}) + if not results: + st.info("Configure parameters in the sidebar and click **Find matches**.") + return + + st.subheader(f"Top-{mp.get('k', '?')} matches for {mp.get('lobe', '?')}") + df = pd.DataFrame(results) + st.dataframe(df, use_container_width=True) + _download_buttons(df, "itrialspace_matches") + + +def _render_detail(annotation_id: str): + """Render full detail panel for a nodule with CT viewer.""" + try: + detail = _get_nodule_detail(annotation_id) + except Exception as e: + st.error(f"Could not load detail: {e}") + return + + # If detail is a dict with nested 'detail', flatten + info = detail.get("detail", detail) if isinstance(detail, dict) else detail + paths = detail.get("_paths", detail.get("paths", {})) + + # ── CT Viewer — Axial slice at nodule centre ───────────────────────── + ct_abs = paths.get("ct_path", "") + + if ct_abs: + wcol1, wcol2 = st.columns([1, 1]) + with wcol1: + view_window = st.selectbox( + "Window preset", + ["lung", "mediastinum", "soft_tissue", "bone"], + key=f"window_{annotation_id}", + ) + with wcol2: + show_mask = st.checkbox("Show nodule mask", value=True, key=f"mask_{annotation_id}") + + png = _get_nodule_view_png( + annotation_id, axis="axial", window=view_window, show_mask=show_mask + ) + + # Volume info badge + vol_info = _get_volume_info(ct_abs) + if vol_info: + s = vol_info["shape"] + sp = vol_info["spacing_mm"] + st.caption( + f"Volume: {s[0]}×{s[1]}×{s[2]} | " + f"Spacing: {sp[0]:.2f}×{sp[1]:.2f}×{sp[2]:.2f} mm | " + f"Centre: ({info.get('coordX','?')}, {info.get('coordY','?')}, {info.get('coordZ','?')})" + ) + + if png: + st.image(png, caption=f"Axial — {view_window} window", use_container_width=True) + else: + st.warning("CT file not accessible from this node. " f"Expected: `{ct_abs}`") + else: + st.info("No CT path resolved for this nodule.") + + # ── Metadata tables ────────────────────────────────────────────────── + st.subheader("Nodule Metadata") + col1, col2 = st.columns([2, 1]) + with col1: + core_keys = [ + "annotation_id", + "dataset", + "patient_id", + "label", + "lobe_name", + "lung_side", + "lung_zone", + "central_peripheral", + "nodule_mean_diam_mm", + "nodule_vol_mm3", + "pleural_distance_mm", + "airway_distance_mm", + "cranio_caudal_pct", + "mediolateral_pct", + "anteroposterior_pct", + "coordX", + "coordY", + "coordZ", + ] + rows = [(k, info.get(k, "")) for k in core_keys if k in info] + st.table(pd.DataFrame(rows, columns=["Field", "Value"])) + + with col2: + rkeys = [k for k in info if str(k).startswith("reinsertion_")] + if rkeys: + st.write("**Reinsertion coordinates**") + rrows = [(k, info[k]) for k in rkeys] + st.table(pd.DataFrame(rrows, columns=["Field", "Value"])) + + # ── File paths ──────────────────────────────────────────────────────── + if paths: + with st.expander("File paths"): + for k, v in paths.items(): + import os + + exists = os.path.isfile(str(v)) if v else False + icon = "✅" if exists else "❌" + st.text(f"{icon} {k}: {v}") + + +# --------------------------------------------------------------------------- +# Entry point +# --------------------------------------------------------------------------- + +if __name__ == "__main__": + main() diff --git a/itrialspace/src/itrialspace/cli.py b/itrialspace/src/itrialspace/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..2969088d01243d20f9df7fd183e48bfdb217f923 --- /dev/null +++ b/itrialspace/src/itrialspace/cli.py @@ -0,0 +1,92 @@ +"""Umbrella command-line interface for iTrialSpace (``its``). + +Lightweight entry point over the core nodule index. Component-specific commands have +their own console scripts (``its-insert``, ``its-trials``, ``its-nodulemap``, +``its-retriever``). +""" + +from __future__ import annotations + +import argparse +import sys + +from itrialspace import __version__ +from itrialspace.config import settings + + +def _cmd_config(_args: argparse.Namespace) -> int: + """Print resolved paths so users can verify their environment.""" + print("iTrialSpace resolved configuration:") + print(f" repo_root {settings.repo_root()}") + print(f" data_dir {settings.data_dir()}") + print(f" output_dir {settings.output_dir()}") + print(f" configs_dir {settings.configs_dir()}") + print(f" nodulemap_artifacts {settings.nodulemap_artifacts_dir()}") + try: + ds = settings.find_config("datasets.yaml") + print(f" datasets config {ds}") + except FileNotFoundError as exc: + print(f" datasets config (not found: {exc})") + return 0 + + +def _load_index(): + from itrialspace import DatasetRegistry, NoduleIndex + + registry = DatasetRegistry.from_yaml() + if len(registry) == 0: + print( + "No datasets found. Set ITRIALSPACE_DATA_DIR (see `its config`) and ensure " + "profile CSVs exist; see docs/data.md.", + file=sys.stderr, + ) + raise SystemExit(2) + return NoduleIndex.from_registry(registry) + + +def _cmd_stats(_args: argparse.Namespace) -> int: + idx = _load_index() + print(f"Loaded {len(idx)} nodules across {len(idx.datasets)} datasets.\n") + print(idx.stats().to_string()) + return 0 + + +def _cmd_info(_args: argparse.Namespace) -> int: + from itrialspace import DatasetRegistry + + registry = DatasetRegistry.from_yaml() + print(repr(registry)) + return 0 + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser(prog="its", description="iTrialSpace command-line interface") + parser.add_argument("--version", action="version", version=f"iTrialSpace {__version__}") + sub = parser.add_subparsers(dest="command") + + p_config = sub.add_parser("config", help="show resolved paths / environment") + p_config.set_defaults(func=_cmd_config) + + p_info = sub.add_parser("info", help="list configured datasets") + p_info.set_defaults(func=_cmd_info) + + p_index = sub.add_parser("index", help="nodule index operations") + index_sub = p_index.add_subparsers(dest="index_command") + p_stats = index_sub.add_parser("stats", help="build the index and print summary stats") + p_stats.set_defaults(func=_cmd_stats) + + return parser + + +def main(argv: list[str] | None = None) -> int: + parser = build_parser() + args = parser.parse_args(argv) + func = getattr(args, "func", None) + if func is None: + parser.print_help() + return 0 + return func(args) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/itrialspace/src/itrialspace/config/__init__.py b/itrialspace/src/itrialspace/config/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e349ea733a48e37f312f868548f8ed2e3fde21af --- /dev/null +++ b/itrialspace/src/itrialspace/config/__init__.py @@ -0,0 +1,23 @@ +"""Configuration and portable path resolution for iTrialSpace.""" + +from itrialspace.config.settings import ( + configs_dir, + data_dir, + expand, + expand_tree, + find_config, + load_yaml, + output_dir, + repo_root, +) + +__all__ = [ + "repo_root", + "data_dir", + "output_dir", + "configs_dir", + "expand", + "expand_tree", + "load_yaml", + "find_config", +] diff --git a/itrialspace/src/itrialspace/config/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/config/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a17ea1edadc839206cddd122d38e3c200056256 Binary files /dev/null and b/itrialspace/src/itrialspace/config/__pycache__/__init__.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/config/__pycache__/settings.cpython-310.pyc b/itrialspace/src/itrialspace/config/__pycache__/settings.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae1d66d7d5d6d71f5056f816095c42c2ec1ba087 Binary files /dev/null and b/itrialspace/src/itrialspace/config/__pycache__/settings.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/config/datasets.yaml b/itrialspace/src/itrialspace/config/datasets.yaml new file mode 100644 index 0000000000000000000000000000000000000000..37d3d2d2f9eb4f8e9d951f5e863fcc24b956d0b7 --- /dev/null +++ b/itrialspace/src/itrialspace/config/datasets.yaml @@ -0,0 +1,35 @@ +# iTrialSpace Dataset Registry — maps dataset name → nodule-profile CSV path. +# +# Copy to `configs/datasets.yaml` and adjust if your layout differs. Paths use the +# ${ITRIALSPACE_DATA_DIR} placeholder, which is expanded by itrialspace.config.settings +# (default: ~/.itrialspace/data). You usually only need to set ITRIALSPACE_DATA_DIR in .env. + +datasets: + + DLCS24: + csv_path: ${ITRIALSPACE_DATA_DIR}/profiles/DLCS24_nodule_profiles.csv + notes: "Binary label. Lung-RADS scores, smoking, age/sex. 2,487 nodules." + + LUNA25: + csv_path: ${ITRIALSPACE_DATA_DIR}/profiles/LUNA25_nodule_profiles.csv + notes: "Binary label. Largest dataset (6,163 nodules). Multi-nodule screening." + + LUNA16: + csv_path: ${ITRIALSPACE_DATA_DIR}/profiles/LUNA16_nodule_profiles.csv + notes: "No malignancy label. Use for reinsertion/anatomy analysis only." + + LUNGx: + csv_path: ${ITRIALSPACE_DATA_DIR}/profiles/LUNGx_nodule_profiles.csv + notes: "Benchmark challenge. 49.4% malignant." + + LNDbv4: + csv_path: ${ITRIALSPACE_DATA_DIR}/profiles/LNDbv4_nodule_profiles.csv + notes: "Malignancy is continuous float (radiologist avg 1-5). Threshold 3.0 used." + + NSCLCR: + csv_path: ${ITRIALSPACE_DATA_DIR}/profiles/NSCLCR_nodule_profiles.csv + notes: "All malignant (100%). Large tumours (median 52mm). Has staging/survival." + + IMDCT: + csv_path: ${ITRIALSPACE_DATA_DIR}/profiles/IMDCT_nodule_profiles.csv + notes: "Label is string benign/cancer. Has nodule type, PET, spiculation." diff --git a/itrialspace/src/itrialspace/config/settings.py b/itrialspace/src/itrialspace/config/settings.py new file mode 100644 index 0000000000000000000000000000000000000000..73a267a6e312e29075c968a4ff772519b900c842 --- /dev/null +++ b/itrialspace/src/itrialspace/config/settings.py @@ -0,0 +1,231 @@ +"""Central, machine-portable settings and path resolution for iTrialSpace. + +This module is the **single source of truth** for every filesystem path the project +needs. Nothing else in the codebase should hardcode an absolute path. All locations +are derived from environment variables (with sensible defaults), so the same code runs +unchanged on a laptop, a workstation, or an HPC cluster. + +Environment variables (see ``.env.example``): + + ITRIALSPACE_DATA_DIR base directory of the unified data layout + (default: ~/.itrialspace/data) + ITRIALSPACE_ROOT repo root (auto-detected from this file when editable) + ITRIALSPACE_OUTPUT_DIR where generated artifacts go (default: ITRIALSPACE_DATA_DIR) + +YAML interpolation: + + Any string value in a config YAML may reference these variables with ``${VAR}`` + syntax, e.g. ``base_dir: ${ITRIALSPACE_DATA_DIR}``. Use :func:`load_yaml` (or + :func:`expand`) so the placeholders resolve — falling back to the documented + defaults even when the variable is not exported. +""" + +from __future__ import annotations + +import os +from functools import lru_cache +from pathlib import Path +from string import Template +from typing import Any, Optional + +_ENV_DATA = "ITRIALSPACE_DATA_DIR" +_ENV_ROOT = "ITRIALSPACE_ROOT" +_ENV_OUTPUT = "ITRIALSPACE_OUTPUT_DIR" +_ENV_NODULEMAP_ARTIFACTS = "NODULEMAP_ARTIFACTS" + +# HuggingFace token env var (and the legacy alias transformers/hub also honour). +_ENV_HF_TOKEN = "HF_TOKEN" +_ENV_HF_TOKEN_LEGACY = "HUGGING_FACE_HUB_TOKEN" + + +def _parse_env_file(path: Path) -> None: + """Load KEY=VALUE lines from a .env file into os.environ (real env wins).""" + for raw in path.read_text().splitlines(): + line = raw.strip() + if not line or line.startswith("#") or "=" not in line: + continue + key, _, val = line.partition("=") + key = key.strip() + if not key.isidentifier(): + continue + val = val.strip().strip('"').strip("'") + os.environ.setdefault(key, val) # never override an already-set variable + + +def load_dotenv_once() -> Optional[Path]: + """Load the project's ``.env`` into ``os.environ`` exactly once. + + Mirrors ``infra/slurm/env.sh``: variables already in the real environment win, + so a per-invocation override (or the SLURM-exported value) is never clobbered. + Looks at ``$CWD/.env`` first, then the repo root's ``.env``. Secrets such as + ``HF_TOKEN`` therefore come from ``.env`` (gitignored) and never from code. + """ + if getattr(load_dotenv_once, "_done", False): + return getattr(load_dotenv_once, "_path", None) + load_dotenv_once._done = True # type: ignore[attr-defined] + candidates = [Path.cwd() / ".env"] + here = Path(__file__).resolve() + for parent in here.parents: + if (parent / "pyproject.toml").is_file(): + candidates.append(parent / ".env") + break + for envf in candidates: + if envf.is_file(): + _parse_env_file(envf) + load_dotenv_once._path = envf # type: ignore[attr-defined] + return envf + return None + + +def hf_token() -> Optional[str]: + """HuggingFace access token from the environment (``.env`` → ``HF_TOKEN``). + + Returns ``None`` when unset (public models still load; gated models such as + MedGemma need a token — set ``HF_TOKEN`` in ``.env`` or the environment). + """ + load_dotenv_once() + return os.environ.get(_ENV_HF_TOKEN) or os.environ.get(_ENV_HF_TOKEN_LEGACY) + + +# Load .env as early as possible so every os.environ read below sees it. +load_dotenv_once() + + +@lru_cache(maxsize=1) +def repo_root() -> Path: + """Best-effort repo root. + + Prefers ``$ITRIALSPACE_ROOT``; otherwise walks up from this file looking for a + repo marker (``pyproject.toml``). Falls back to the current working directory + when installed as a non-editable wheel. + """ + env = os.environ.get(_ENV_ROOT) + if env: + return Path(env).expanduser().resolve() + here = Path(__file__).resolve() + for parent in here.parents: + if (parent / "pyproject.toml").is_file(): + return parent + return Path.cwd() + + +@lru_cache(maxsize=1) +def data_dir() -> Path: + """Base directory of the unified data layout (raw_ct/, masks/, profiles/, ...).""" + env = os.environ.get(_ENV_DATA) + base = Path(env).expanduser() if env else Path.home() / ".itrialspace" / "data" + return base + + +@lru_cache(maxsize=1) +def output_dir() -> Path: + """Where generated artifacts (manifests, masks, CTs, reports) are written.""" + env = os.environ.get(_ENV_OUTPUT) + return Path(env).expanduser() if env else data_dir() + + +def configs_dir() -> Path: + """Top-level ``configs/`` directory holding user/example configs.""" + return repo_root() / "configs" + + +def nodulemap_artifacts_dir() -> Path: + """Directory holding NoduleMap build artifacts (embeddings, edges, metadata). + + Set ``$NODULEMAP_ARTIFACTS`` to read pre-built artifacts (or to choose where new + ones are written). Default: ``$ITRIALSPACE_OUTPUT_DIR/nodulemap_artifacts``. + """ + env = os.environ.get(_ENV_NODULEMAP_ARTIFACTS) + return Path(env).expanduser() if env else output_dir() / "nodulemap_artifacts" + + +def _defaults() -> dict[str, str]: + """Mapping used for ``${VAR}`` expansion: resolved defaults + live environment.""" + base = { + _ENV_DATA: str(data_dir()), + _ENV_ROOT: str(repo_root()), + _ENV_OUTPUT: str(output_dir()), + _ENV_NODULEMAP_ARTIFACTS: str(nodulemap_artifacts_dir()), + } + base.update(os.environ) # real environment wins + return base + + +def expand(value: Any) -> Any: + """Expand ``${VAR}`` placeholders and ``~`` in a string. + + Non-strings are returned unchanged. Unknown variables are left intact (via + ``safe_substitute``) so misconfigurations are visible rather than silently empty. + """ + if not isinstance(value, str): + return value + substituted = Template(value).safe_substitute(_defaults()) + return os.path.expanduser(substituted) + + +def expand_tree(obj: Any) -> Any: + """Recursively expand ``${VAR}`` in all string leaves of a dict/list structure.""" + if isinstance(obj, dict): + return {k: expand_tree(v) for k, v in obj.items()} + if isinstance(obj, list): + return [expand_tree(v) for v in obj] + return expand(obj) + + +def load_yaml(path: str | Path) -> dict: + """Load a YAML file and expand ``${VAR}`` placeholders throughout.""" + try: + import yaml + except ImportError as exc: # pragma: no cover + raise ImportError("PyYAML required: pip install pyyaml") from exc + with open(path) as f: + raw = yaml.safe_load(f) or {} + return expand_tree(raw) + + +def find_config(name: str, package_default: Optional[str | Path] = None) -> Path: + """Resolve a config file name to a concrete path. + + Resolution order: + 1. ``$ITRIALSPACE__CONFIG`` env override (NAME upper-cased, no extension) + 2. top-level ``configs/`` (user copy) + 3. top-level ``configs/.example.`` (shipped example) + 4. ``package_default`` (config bundled inside the package), if provided + + Raises ``FileNotFoundError`` if nothing is found. + """ + stem = Path(name).stem + ext = Path(name).suffix or ".yaml" + + env_key = f"ITRIALSPACE_{stem.upper()}_CONFIG" + if os.environ.get(env_key): + return Path(os.environ[env_key]).expanduser() + + cfg = configs_dir() + candidates = [cfg / name, cfg / f"{stem}.example{ext}"] + for cand in candidates: + if cand.is_file(): + return cand + + if package_default is not None and Path(package_default).is_file(): + return Path(package_default) + + raise FileNotFoundError( + f"Config '{name}' not found. Looked for: " + + ", ".join(str(c) for c in candidates) + + (f", {package_default}" if package_default else "") + + f". Set {env_key} or create configs/{name}." + ) + + +__all__ = [ + "repo_root", + "data_dir", + "output_dir", + "configs_dir", + "nodulemap_artifacts_dir", + "expand", + "expand_tree", + "load_yaml", + "find_config", +] diff --git a/itrialspace/src/itrialspace/core/__init__.py b/itrialspace/src/itrialspace/core/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/itrialspace/src/itrialspace/core/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/core/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5286290bbb9d0ece2e037bbccb145722ef15b250 Binary files /dev/null and b/itrialspace/src/itrialspace/core/__pycache__/__init__.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/core/__pycache__/label.cpython-310.pyc b/itrialspace/src/itrialspace/core/__pycache__/label.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..613c0aca82682b80ca1d72a44657eb285c29119d Binary files /dev/null and b/itrialspace/src/itrialspace/core/__pycache__/label.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/core/__pycache__/profile.cpython-310.pyc b/itrialspace/src/itrialspace/core/__pycache__/profile.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cc72925d60a2d345236af892489da1d1e588482b Binary files /dev/null and b/itrialspace/src/itrialspace/core/__pycache__/profile.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/core/__pycache__/schema.cpython-310.pyc b/itrialspace/src/itrialspace/core/__pycache__/schema.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..da9e2ee48ec4d965498a80e7afd30ba378accdc4 Binary files /dev/null and b/itrialspace/src/itrialspace/core/__pycache__/schema.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/core/label.py b/itrialspace/src/itrialspace/core/label.py new file mode 100644 index 0000000000000000000000000000000000000000..0c8df7b43571b9e56c12123abf38429940e3acbe --- /dev/null +++ b/itrialspace/src/itrialspace/core/label.py @@ -0,0 +1,99 @@ +""" +LabelNormaliser — maps each dataset's native label column(s) +to a unified int | None value: + 0 = benign + 1 = malignant + None = unknown / unlabelled +""" + +from __future__ import annotations + +from typing import Optional + +import pandas as pd + + +class LabelNormaliser: + """ + Per-dataset rules for producing a unified binary label. + + Usage: + normaliser = LabelNormaliser("DLCS24") + label = normaliser.normalise(row) # row is a pandas Series + """ + + # Maps dataset → callable(row) → int | None + _RULES: dict[str, callable] = {} + + def __init__(self, dataset: str): + if dataset not in self._RULES: + raise ValueError(f"Unknown dataset '{dataset}'. " f"Known: {list(self._RULES.keys())}") + self.dataset = dataset + self._fn = self._RULES[dataset] + + def normalise(self, row: pd.Series) -> Optional[int]: + return self._fn(row) + + def normalise_series(self, df: pd.DataFrame) -> pd.Series: + """Apply to entire DataFrame, return Series of normalised labels.""" + return df.apply(self._fn, axis=1) + + # ── Register all dataset rules ──────────────────────────────────────────── + + @classmethod + def _register(cls): + def _safe_int(v) -> Optional[int]: + try: + return int(v) + except (TypeError, ValueError): + return None + + cls._RULES["DLCS24"] = lambda row: _safe_int(row.get("label")) + + cls._RULES["LUNA25"] = lambda row: _safe_int(row.get("label")) + + cls._RULES["LUNA16"] = lambda row: None # no malignancy label available + + cls._RULES["LUNGx"] = lambda row: _safe_int(row.get("CADx_label")) + + def _lndbv4(row) -> Optional[int]: + v = row.get("Malignancy") + if pd.isna(v): + return None + try: + return 1 if float(v) >= 3.0 else 0 + except (TypeError, ValueError): + return None + + cls._RULES["LNDbv4"] = _lndbv4 + + cls._RULES["NSCLCR"] = lambda row: 1 # 100% cancer cohort + + def _imdct(row) -> Optional[int]: + v = row.get("CADx_label") + if pd.isna(v): + return None + s = str(v).strip().lower() + if s == "cancer": + return 1 + if s == "benign": + return 0 + return None + + cls._RULES["IMDCT"] = _imdct + + @classmethod + def available_datasets(cls) -> list[str]: + return list(cls._RULES.keys()) + + +# Register rules at import time +LabelNormaliser._register() + + +# ── Standalone helper ───────────────────────────────────────────────────────── + + +def normalise_label(row: pd.Series, dataset: str) -> Optional[int]: + """Convenience function — normalise a single row.""" + return LabelNormaliser(dataset).normalise(row) diff --git a/itrialspace/src/itrialspace/core/profile.py b/itrialspace/src/itrialspace/core/profile.py new file mode 100644 index 0000000000000000000000000000000000000000..c20cf0fb4e3b4f9638fd5f290a0cfe84b82ee49d --- /dev/null +++ b/itrialspace/src/itrialspace/core/profile.py @@ -0,0 +1,150 @@ +""" +NoduleProfile — the unified representation of a single lung nodule +across all 8 iTrialSpace datasets. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Optional + + +@dataclass +class NoduleProfile: + """ + A single nodule record, normalised from any iTrialSpace dataset CSV. + + The 53 core pipeline fields are typed attributes. + Dataset-specific columns (Lung-RADS, staging, pack-years, etc.) + live in `meta` and are also retained in the NoduleIndex DataFrame. + """ + + # ── Identity ────────────────────────────────────────────────────────────── + annotation_id: str # AnnotationID (universal across datasets) + patient_id: str # normalised from 8 different source col names + dataset: str # 'DLCS24' | 'LUNA25' | 'LUNA16' | ... + ct_path: str + + # ── Label ───────────────────────────────────────────────────────────────── + label: Optional[int] = None # 0=benign, 1=malignant, None=unknown + + # ── Bounding box ────────────────────────────────────────────────────────── + coord_x: float = 0.0 + coord_y: float = 0.0 + coord_z: float = 0.0 + w: float = 0.0 + h: float = 0.0 + d: float = 0.0 + + # ── Morphology ──────────────────────────────────────────────────────────── + nodule_mean_diam_mm: float = 0.0 + nodule_vol_mm3: Optional[float] = None + + # ── Anatomy ─────────────────────────────────────────────────────────────── + lobe_name: str = "unknown" + lung_side: str = "unknown" + lung_zone: str = "unknown" + organ_label_id: int = 0 + organ_label_name: str = "" + central_peripheral: str = "unknown" + nearby_organs_10mm: Optional[str] = None + + # ── Position — whole-lung % ─────────────────────────────────────────────── + cranio_caudal_pct: Optional[float] = None + mediolateral_pct: Optional[float] = None + anteroposterior_pct: Optional[float] = None + + # ── Position — lobe % ──────────────────────────────────────────────────── + # NOTE: lobe_cc_pct is clean (use freely). + # lobe_ml_pct and lobe_ap_pct have known outliers in DLCS24 + # due to a normalisation bug — check dataset_flags before using. + lobe_cc_pct: Optional[float] = None + lobe_ml_pct: Optional[float] = None + lobe_ap_pct: Optional[float] = None + + # ── Distances (mm) ──────────────────────────────────────────────────────── + dist_to_trachea_mm: Optional[float] = None + dist_to_aorta_mm: Optional[float] = None + dist_to_heart_mm: Optional[float] = None + dist_to_esophagus_mm: Optional[float] = None + dist_to_pulmonary_vein_mm: Optional[float] = None + dist_to_superior_vena_cava_mm: Optional[float] = None + pleural_distance_mm: Optional[float] = None + airway_distance_mm: Optional[float] = None + + # ── Inter-nodule ────────────────────────────────────────────────────────── + n_nodules_in_patient: int = 1 + nearest_nodule_id: Optional[str] = None + nearest_nodule_dist_mm: Optional[float] = None + nearest_dx_mm: Optional[float] = None + nearest_dy_mm: Optional[float] = None + nearest_dz_mm: Optional[float] = None + all_nodule_ids: Optional[str] = None + all_nodule_dists_mm: Optional[str] = None + ipsilateral: Optional[bool] = None + nearest_same_lobe: Optional[bool] = None + bilateral_distribution: bool = False + + # ── Reinsertion — 100% complete, primary query / match index ───────────── + reinsertion_lobe: str = "unknown" + reinsertion_lung_side: str = "unknown" + reinsertion_lung_zone: str = "unknown" + reinsertion_lobe_cc_pct: float = 0.0 + reinsertion_lobe_ml_pct: float = 0.0 + reinsertion_lobe_ap_pct: float = 0.0 + reinsertion_lung_cc_pct: float = 0.0 + reinsertion_lung_ml_pct: float = 0.0 + reinsertion_lung_ap_pct: float = 0.0 + reinsertion_pleural_dist_mm: Optional[float] = None + reinsertion_airway_dist_mm: Optional[float] = None + reinsertion_nodule_diam_mm: float = 0.0 + + # ── Dataset-specific metadata ───────────────────────────────────────────── + # All extra columns from the source CSV land here. + # Also retained in NoduleIndex DataFrame under original column names. + # + # Examples by dataset: + # DLCS24: 'Lung-RADS score', 'Smoking Status', 'Age', 'Sex', 'annotation_group' + # LUNA25: 'LesionID', 'NoduleID', 'StudyDate', 'Split', 'age', 'gender' + # LNDbv4: 'Malignancy' (raw float), 'Texture', 'Spiculation', 'NumRadsFound' + # NSCLCR: 'overall.stage', 'histology', 'survival.time', 'deadstatus.event' + # IMDCT: 'nodules_types', 'Spiculation', 'Emphysema', 'PET', 'uptake_class' + # LUNGx: 'Final Diagnosis', 'ANod_score', 'meta_prob' + meta: dict = field(default_factory=dict) + + # ── Convenience properties ──────────────────────────────────────────────── + @property + def is_malignant(self) -> Optional[bool]: + if self.label is None: + return None + return bool(self.label) + + @property + def is_upper_lobe(self) -> bool: + return "upper" in self.lobe_name + + @property + def is_peripheral(self) -> bool: + return self.central_peripheral == "peripheral" + + @property + def size_bucket(self) -> str: + d = self.nodule_mean_diam_mm + if d < 5: + return "<5mm" + if d < 10: + return "5-10mm" + if d < 15: + return "10-15mm" + if d < 20: + return "15-20mm" + if d < 30: + return "20-30mm" + return ">30mm" + + def __repr__(self) -> str: + lbl = {0: "benign", 1: "malignant", None: "unlabelled"}[self.label] + return ( + f"NoduleProfile({self.dataset} | {self.annotation_id} | " + f"{self.nodule_mean_diam_mm:.1f}mm | {self.lobe_name} | {lbl})" + ) diff --git a/itrialspace/src/itrialspace/core/schema.py b/itrialspace/src/itrialspace/core/schema.py new file mode 100644 index 0000000000000000000000000000000000000000..4650f8d77c6d085b39fc410c8eff89292fba5afe --- /dev/null +++ b/itrialspace/src/itrialspace/core/schema.py @@ -0,0 +1,198 @@ +""" +Schema constants — the 53 columns present in every nodule profile CSV, +plus enums for categorical values. +""" + +from enum import Enum + +# ── Core columns present in ALL 7 datasets ──────────────────────────────────── +CORE_COLS = [ + # identity + "ct_path", + # bounding box + "coordX", + "coordY", + "coordZ", + "w", + "h", + "d", + # morphology + "nodule_mean_diam_mm", + "nodule_vol_mm3", + # anatomy + "organ_label_id", + "organ_label_name", + "nearby_organs_10mm", + "lung_side", + "lobe_name", + "lung_zone", + "central_peripheral", + # position – whole lung % + "cranio_caudal_pct", + "mediolateral_pct", + "anteroposterior_pct", + # position – lobe % + "lobe_cc_pct", + "lobe_ml_pct", + "lobe_ap_pct", + # distances mm + "dist_to_trachea_mm", + "dist_to_aorta_mm", + "dist_to_heart_mm", + "dist_to_esophagus_mm", + "dist_to_pulmonary_vein_mm", + "dist_to_superior_vena_cava_mm", + "pleural_distance_mm", + "airway_distance_mm", + # inter-nodule + "n_nodules_in_patient", + "nearest_nodule_id", + "nearest_nodule_dist_mm", + "nearest_dx_mm", + "nearest_dy_mm", + "nearest_dz_mm", + "all_nodule_ids", + "all_nodule_dists_mm", + "ipsilateral", + "nearest_same_lobe", + "bilateral_distribution", + # reinsertion (100% complete across all datasets) + "reinsertion_lobe", + "reinsertion_lung_side", + "reinsertion_lung_zone", + "reinsertion_lobe_cc_pct", + "reinsertion_lobe_ml_pct", + "reinsertion_lobe_ap_pct", + "reinsertion_lung_cc_pct", + "reinsertion_lung_ml_pct", + "reinsertion_lung_ap_pct", + "reinsertion_pleural_dist_mm", + "reinsertion_airway_dist_mm", + "reinsertion_nodule_diam_mm", +] + +# Pipeline-computed columns that map to NoduleProfile typed fields +PROFILING_COLS = [c for c in CORE_COLS if c != "ct_path"] + +# Reinsertion subset — 100% complete, primary query index +REINSERTION_COLS = [c for c in CORE_COLS if c.startswith("reinsertion_")] + +# ── Categorical values ───────────────────────────────────────────────────────── +LOBE_NAMES = [ + "right_lung_upper_lobe", + "right_lung_middle_lobe", + "right_lung_lower_lobe", + "left_lung_upper_lobe", + "left_lung_lower_lobe", +] +LOBE_NAMES_WITH_BG = LOBE_NAMES + ["background", "unknown"] + +ZONE_NAMES = ["upper_zone", "middle_zone", "lower_zone"] +SIDE_NAMES = ["right", "left", "unknown"] +CP_VALUES = ["central", "peripheral", "unknown"] + +DATASET_NAMES = ["DLCS24", "LUNA25", "LUNA16", "LUNGx", "LNDbv4", "NSCLCR", "IMDCT"] + + +class Lobe(str, Enum): + RIGHT_UPPER = "right_lung_upper_lobe" + RIGHT_MIDDLE = "right_lung_middle_lobe" + RIGHT_LOWER = "right_lung_lower_lobe" + LEFT_UPPER = "left_lung_upper_lobe" + LEFT_LOWER = "left_lung_lower_lobe" + BACKGROUND = "background" + UNKNOWN = "unknown" + + +class Zone(str, Enum): + UPPER = "upper_zone" + MIDDLE = "middle_zone" + LOWER = "lower_zone" + + +class Side(str, Enum): + RIGHT = "right" + LEFT = "left" + UNKNOWN = "unknown" + + +class CentralPeripheral(str, Enum): + CENTRAL = "central" + PERIPHERAL = "peripheral" + UNKNOWN = "unknown" + + +# ── Known data quality flags per dataset ────────────────────────────────────── +DATASET_FLAGS: dict[str, dict] = { + "DLCS24": { + "lobe_ml_pct_unreliable": True, # 93% outside [0,100] — pipeline normalisation bug + "lobe_ap_pct_unreliable": True, # 50.7% outside [0,100] + "lobe_cc_pct_unreliable": False, + "has_label": True, + "all_malignant": False, + "all_unlabelled": False, + "label_is_soft": False, + "notes": "Binary label. Includes Lung-RADS scores, smoking, age/sex.", + }, + "LUNA25": { + "lobe_ml_pct_unreliable": False, + "lobe_ap_pct_unreliable": False, + "lobe_cc_pct_unreliable": False, + "has_label": True, + "all_malignant": False, + "all_unlabelled": False, + "label_is_soft": False, + "notes": "Binary label. Largest dataset (6,163 nodules). Multi-nodule screening.", + }, + "LUNA16": { + "lobe_ml_pct_unreliable": False, + "lobe_ap_pct_unreliable": False, + "lobe_cc_pct_unreliable": False, + "has_label": False, + "all_malignant": False, + "all_unlabelled": True, + "label_is_soft": False, + "notes": "No malignancy label. Use for reinsertion/anatomy only.", + }, + "LUNGx": { + "lobe_ml_pct_unreliable": False, + "lobe_ap_pct_unreliable": False, + "lobe_cc_pct_unreliable": False, + "has_label": True, + "all_malignant": False, + "all_unlabelled": False, + "label_is_soft": False, + "notes": "Benchmark challenge dataset. CADx_label binary. 49.4% malignant.", + }, + "LNDbv4": { + "lobe_ml_pct_unreliable": False, + "lobe_ap_pct_unreliable": False, + "lobe_cc_pct_unreliable": False, + "has_label": True, + "all_malignant": False, + "all_unlabelled": False, + "label_is_soft": True, # continuous 1–5 radiologist average + "label_threshold": 3.0, + "notes": "Malignancy is float avg of radiologist ratings (1–5). Threshold >=3 used.", + }, + "NSCLCR": { + "lobe_ml_pct_unreliable": False, + "lobe_ap_pct_unreliable": False, + "lobe_cc_pct_unreliable": False, + "has_label": True, + "all_malignant": True, # 100% cancer cohort + "all_unlabelled": False, + "label_is_soft": False, + "notes": "All malignant (lung cancer patients). Large tumours (median 52mm). Has staging/survival.", + }, + "IMDCT": { + "lobe_ml_pct_unreliable": False, + "lobe_ap_pct_unreliable": False, + "lobe_cc_pct_unreliable": False, + "has_label": True, + "all_malignant": False, + "all_unlabelled": False, + "label_is_soft": False, + "notes": "Label is string 'benign'/'cancer'. Has nodule type, PET, spiculation.", + }, +} diff --git a/itrialspace/src/itrialspace/evaluation/__init__.py b/itrialspace/src/itrialspace/evaluation/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f9147288cdf80428676b059d74434388ff4a0f64 --- /dev/null +++ b/itrialspace/src/itrialspace/evaluation/__init__.py @@ -0,0 +1,9 @@ +"""Evaluation layer for iTrialSpace — downstream tools that consume generated data. + +- ``vlm_eval``: zero-shot Vision-Language Model evaluation (``pip install -e ".[vlm]"``). + +The core engine (index → trials → mask insertion → synthesis) does not depend on +anything in this subpackage; the dependency only flows one way (evaluation → core). +""" + +__all__ = ["vlm_eval"] diff --git a/itrialspace/src/itrialspace/evaluation/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/evaluation/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dc3a32da845b8a994126c233db374126677963cd Binary files /dev/null and b/itrialspace/src/itrialspace/evaluation/__pycache__/__init__.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/__init__.py b/itrialspace/src/itrialspace/evaluation/vlm_eval/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fda812eca7cd7665f41eeb71b2d4eab660e5f368 --- /dev/null +++ b/itrialspace/src/itrialspace/evaluation/vlm_eval/__init__.py @@ -0,0 +1,12 @@ +""" +vlm_evaluation — Vision-Language Model evaluation framework for iTrialSpace. + +Evaluates VLMs on iTrialSpace-generated synthetic CT trial cases. + +Supported models: + - BiomedCLIP (contrastive, image-text similarity) + - LLaVA-Med (generative, instruction-following) + - MedGemma 1.5 4B (generative, multi-slice CT, 3-channel windowing) +""" + +__version__ = "0.5.0" diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a6178e7a4edd9fe1c40415268de1c99bd7fdc85 Binary files /dev/null and b/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/__init__.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/biomedclip_model.cpython-310.pyc b/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/biomedclip_model.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7870cb8301286d8c0e8f37f7832411a0b5c05c5a Binary files /dev/null and b/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/biomedclip_model.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/build_dataset.cpython-310.pyc b/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/build_dataset.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..65aa1647f65ac898a51290c11a2cea0d67492772 Binary files /dev/null and b/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/build_dataset.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/build_negative_dataset.cpython-310.pyc b/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/build_negative_dataset.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8d19c7087d11ccaa5396032f0cc965248db2eb34 Binary files /dev/null and b/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/build_negative_dataset.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/build_real_dataset.cpython-310.pyc b/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/build_real_dataset.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..39164db7b37cbb104966d5d9d95bce92ddce571d Binary files /dev/null and b/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/build_real_dataset.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/comparison.cpython-310.pyc b/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/comparison.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e803c4db927a1c1562442ce0b21e840663c53eaa Binary files /dev/null and b/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/comparison.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/cross_model_comparison.cpython-310.pyc b/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/cross_model_comparison.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b4e6faa22d49734c5d9ade948ff372f61df8cfe Binary files /dev/null and b/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/cross_model_comparison.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/inference_cache.cpython-310.pyc b/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/inference_cache.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2e3fd79c951dacab0a220c32e29c6692717e8e28 Binary files /dev/null and b/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/inference_cache.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/make_split.cpython-310.pyc b/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/make_split.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d67bdb80d1a42c8421747f3d1599255a7e2c2f6c Binary files /dev/null and b/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/make_split.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/metrics.cpython-310.pyc b/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/metrics.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..07af7c8c98851a1c2e8ca1935b7077b30949bb8c Binary files /dev/null and b/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/metrics.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/overlay.cpython-310.pyc b/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/overlay.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..10626a5761eddf2963d72518f7b221ad52dd1426 Binary files /dev/null and b/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/overlay.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/parsers.cpython-310.pyc b/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/parsers.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eca6b0d8a3a2e864c5597cd9177a1d14cfbd6adc Binary files /dev/null and b/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/parsers.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/plots.cpython-310.pyc b/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/plots.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2d7e8eedbcee147953d2896d87cb8235200a458d Binary files /dev/null and b/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/plots.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/preprocess_profiles.cpython-310.pyc b/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/preprocess_profiles.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9d8b65115244637ad2cdd0d0459b6bc2afe0f97b Binary files /dev/null and b/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/preprocess_profiles.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/prompt_templates.cpython-310.pyc b/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/prompt_templates.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..977a485d85b9929ed5d5e309877ae53f20ac94b9 Binary files /dev/null and b/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/prompt_templates.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/report.cpython-310.pyc b/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/report.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ed0885c6c278bb9914f33fcc39897e683f9685e2 Binary files /dev/null and b/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/report.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/run_all.cpython-310.pyc b/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/run_all.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..075278b487045699f71d8f21bb61d5b7b1ce991c Binary files /dev/null and b/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/run_all.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/run_biomedclip.cpython-310.pyc b/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/run_biomedclip.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fe7ebcad04681b0df4f150eee6674548c732ad33 Binary files /dev/null and b/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/run_biomedclip.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/slice_extractor.cpython-310.pyc b/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/slice_extractor.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d1783d9adbb76d8cca80ff6c486d6db9f40118a5 Binary files /dev/null and b/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/slice_extractor.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/splits.cpython-310.pyc b/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/splits.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..23aaa2f053823ad68086c622f5b2ba4266fc1394 Binary files /dev/null and b/itrialspace/src/itrialspace/evaluation/vlm_eval/__pycache__/splits.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/biomedclip_model.py b/itrialspace/src/itrialspace/evaluation/vlm_eval/biomedclip_model.py new file mode 100644 index 0000000000000000000000000000000000000000..5bfab4bd1a4a7a01b171c321019a354e2c8adc33 --- /dev/null +++ b/itrialspace/src/itrialspace/evaluation/vlm_eval/biomedclip_model.py @@ -0,0 +1,168 @@ +""" +BiomedCLIP model wrapper for image-text similarity scoring. + +Uses the open_clip library to load +microsoft/BiomedCLIP-PubMedBERT_256-vit_base_patch16_224. +""" + +from __future__ import annotations + +from typing import List, Optional, Tuple + +import numpy as np +import torch +from PIL import Image + + +class BiomedCLIPModel: + """Thin wrapper around BiomedCLIP for image-text similarity tasks. + + The model is loaded lazily on first use. Supports both CPU and GPU. + """ + + MODEL_ID = "hf-hub:microsoft/BiomedCLIP-PubMedBERT_256-vit_base_patch16_224" + CONTEXT_LENGTH = 256 + + def __init__( + self, + device: Optional[str] = None, + cache_dir: Optional[str] = None, + ): + self._device_str = device + self._cache_dir = cache_dir + self._model = None + self._preprocess = None + self._tokenizer = None + self._device = None + + def _load(self): + """Lazy-load model, preprocess transform, and tokenizer via open_clip.""" + if self._model is not None: + return + + from open_clip import create_model_from_pretrained, get_tokenizer + + if self._device_str: + self._device = torch.device(self._device_str) + else: + self._device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + + print(f"Loading BiomedCLIP from {self.MODEL_ID} ...") + print(f" Device: {self._device}") + + self._model, self._preprocess = create_model_from_pretrained(self.MODEL_ID) + self._tokenizer = get_tokenizer(self.MODEL_ID) + + self._model.eval() + self._model.to(self._device) + print(" BiomedCLIP loaded.") + + @property + def device(self) -> torch.device: + self._load() + return self._device + + def score_image_texts( + self, + image_path: str, + texts: List[str], + ) -> np.ndarray: + """Compute cosine similarities between one image and multiple texts. + + Parameters + ---------- + image_path : str + Path to the PNG image. + texts : list of str + Text prompts to compare against. + + Returns + ------- + np.ndarray + Shape (len(texts),) of similarity scores (logits). + """ + self._load() + + image = Image.open(image_path).convert("RGB") + image_input = self._preprocess(image).unsqueeze(0).to(self._device) + text_input = self._tokenizer(texts, context_length=self.CONTEXT_LENGTH).to(self._device) + + with torch.no_grad(): + image_features, text_features, logit_scale = self._model(image_input, text_input) + similarities = logit_scale * image_features @ text_features.T + + return similarities.squeeze(0).cpu().numpy() + + def predict( + self, + image_path: str, + labels: List[str], + texts: List[str], + ) -> Tuple[str, np.ndarray]: + """Return the best-matching label and all similarity scores. + + Parameters + ---------- + image_path : str + Path to the PNG image. + labels : list of str + Label names corresponding to each text prompt. + texts : list of str + Text prompts. + + Returns + ------- + (predicted_label, scores) : tuple + The label with the highest score and the full score array. + """ + scores = self.score_image_texts(image_path, texts) + best_idx = int(np.argmax(scores)) + return labels[best_idx], scores + + def predict_batch( + self, + image_paths: List[str], + labels: List[str], + texts: List[str], + batch_size: int = 64, + ) -> List[Tuple[str, np.ndarray]]: + """Batched prediction: process multiple images in one forward pass. + + Parameters + ---------- + image_paths : list of str + Paths to PNG images. + labels : list of str + Label names corresponding to each text prompt. + texts : list of str + Text prompts to compare against. + batch_size : int + Images per GPU forward pass. + + Returns + ------- + list of (predicted_label, scores) + One entry per image. + """ + self._load() + + text_input = self._tokenizer(texts, context_length=self.CONTEXT_LENGTH).to(self._device) + + all_results: List[Tuple[str, np.ndarray]] = [] + + for i in range(0, len(image_paths), batch_size): + batch_paths = image_paths[i : i + batch_size] + images = [self._preprocess(Image.open(p).convert("RGB")) for p in batch_paths] + image_input = torch.stack(images).to(self._device) + + with torch.no_grad(): + image_features, text_features, logit_scale = self._model(image_input, text_input) + similarities = logit_scale * image_features @ text_features.T + + scores_np = similarities.cpu().numpy() + for j in range(scores_np.shape[0]): + row_scores = scores_np[j] + best_idx = int(np.argmax(row_scores)) + all_results.append((labels[best_idx], row_scores)) + + return all_results diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/build_dataset.py b/itrialspace/src/itrialspace/evaluation/vlm_eval/build_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..5021cafbbd49ce40814e3bc59f5c0e7ce11d7729 --- /dev/null +++ b/itrialspace/src/itrialspace/evaluation/vlm_eval/build_dataset.py @@ -0,0 +1,643 @@ +""" +Build an evaluation dataset from iTrialSpace manifest + generated CTs. + +Reads a manifest CSV (or multiple), locates the corresponding synthetic CT +for each case, extracts a lesion-centred 2D axial slice via the co-located +input_mask.nii.gz, and produces a clean eval_dataset.csv. +""" + +from __future__ import annotations + +import argparse +import logging +import multiprocessing as mp +import os +from concurrent.futures import ProcessPoolExecutor, as_completed +from typing import Dict, List, Optional, Tuple + +import numpy as np +import pandas as pd + +from itrialspace.evaluation.vlm_eval.overlay import generate_overlays, generate_qc_grid +from itrialspace.evaluation.vlm_eval.preprocess_profiles import ( + DEFAULT_PROFILE, + PreprocessProfile, + get_profile, + list_profiles, +) +from itrialspace.evaluation.vlm_eval.prompt_templates import ( + diameter_to_size_bucket, + normalise_lobe, +) +from itrialspace.evaluation.vlm_eval.slice_extractor import NODULE_LABEL, extract_slice + +logger = logging.getLogger(__name__) + + +# ── Column mapping ─────────────────────────────────────────────────────────── +# iTrialSpace manifest columns → eval dataset columns. + +_MANIFEST_KEY_COLS = [ + "case_id", + "trial_name", + "host_dataset", + "host_ct_path", + "donor_dataset", + "insertion_coord_x", + "insertion_coord_y", + "insertion_coord_z", + "insertion_lobe", + "effective_diam_mm", + "nodule_diam_mm", + "label", + "size_bucket", + "n_nodules_in_case", + "insertion_mode", + "cohort_mode", + "population_type", +] + +# These columns may appear in digital-twin manifests +_OPTIONAL_MANIFEST_COLS = [ + "mode", + "donor_nodule_mask_path", +] + + +def _find_mode_dir_name(manifest_path: str) -> str: + """Walk up from a manifest CSV path to find the ``mode*_`` ancestor. + + For flat manifests (modes 1-10) the parent directory *is* the mode + directory. For nested manifests (modes 11-13:: + + manifests/mode11_digital_twin_isolation/DLCS24/digital_twin_isolation_DLCS24.csv + + ) the immediate parent is a dataset sub-directory; we need to go one + more level up to reach the ``mode11_digital_twin_isolation`` name. + """ + parts = manifest_path.replace("\\", "/").split("/") + for part in reversed(parts): + if part.startswith("mode"): + return part + # Fallback: immediate parent (original behaviour for modes 1-10) + return os.path.basename(os.path.dirname(manifest_path)) + + +def _resolve_synthetic_ct( + case_id: int, + trial_name: str, + manifest_path: str, + ct_base: str, +) -> Optional[str]: + """Find the synthetic_ct.nii.gz produced by NodMAISI for this case. + + NodMAISI case directories are named using the mask inserter output + filename stem (the iTS--...) convention. We search for a matching + directory under generated_cts/{mode_dir}/ or, for multi-trial modes, + under generated_cts/{mode_dir}/{trial_name}/ or + generated_cts/{mode_dir}/{manifest_stem}/ (for bootstrap runs). + """ + mode_dir = _find_mode_dir_name(manifest_path) + ct_mode_dir = os.path.join(ct_base, mode_dir) + + if not os.path.isdir(ct_mode_dir): + return None + + prefix = f"iTS--{trial_name}--C{case_id:04d}--" + manifest_stem = os.path.splitext(os.path.basename(manifest_path))[0] + + # Search directories: trial_name sub-dir, manifest-stem sub-dir, mode root + search_dirs = [ct_mode_dir] + trial_subdir = os.path.join(ct_mode_dir, trial_name) + if os.path.isdir(trial_subdir): + search_dirs.insert(0, trial_subdir) # prefer sub-trial dir + stem_subdir = os.path.join(ct_mode_dir, manifest_stem) + if os.path.isdir(stem_subdir) and stem_subdir != trial_subdir: + search_dirs.insert(0, stem_subdir) # prefer manifest-stem dir + + for search_dir in search_dirs: + for entry in os.listdir(search_dir): + if entry.startswith(prefix): + ct_path = os.path.join(search_dir, entry, "synthetic_ct.nii.gz") + if os.path.isfile(ct_path): + return ct_path + + return None + + +def _resolve_input_mask(ct_path: str) -> Optional[str]: + """Find input_mask.nii.gz co-located with the synthetic CT. + + This mask is in the same NodMAISI-resampled geometry (e.g. 512x512x256) + as the synthetic CT and contains label 23 for the inserted nodule. + """ + ct_dir = os.path.dirname(ct_path) + input_mask = os.path.join(ct_dir, "input_mask.nii.gz") + if os.path.isfile(input_mask): + return input_mask + return None + + +def _resolve_mask_path( + case_id: int, + trial_name: str, + manifest_path: str, + mask_base: str, +) -> Optional[str]: + """Find the inserted combined mask for this case.""" + mode_dir = _find_mode_dir_name(manifest_path) + mask_mode_dir = os.path.join(mask_base, mode_dir) + + if not os.path.isdir(mask_mode_dir): + return None + + prefix = f"iTS--{trial_name}--C{case_id:04d}--" + manifest_stem = os.path.splitext(os.path.basename(manifest_path))[0] + + # Search: trial_name sub-dir, manifest-stem sub-dir, mode root + search_dirs = [mask_mode_dir] + trial_subdir = os.path.join(mask_mode_dir, trial_name) + if os.path.isdir(trial_subdir): + search_dirs.insert(0, trial_subdir) + stem_subdir = os.path.join(mask_mode_dir, manifest_stem) + if os.path.isdir(stem_subdir) and stem_subdir != trial_subdir: + search_dirs.insert(0, stem_subdir) + + for search_dir in search_dirs: + for entry in os.listdir(search_dir): + if entry.startswith(prefix) and entry.endswith("_mask.nii.gz"): + return os.path.join(search_dir, entry) + + return None + + +def _process_single_case(args: Tuple) -> Optional[dict]: + """Worker function for parallel case extraction. + + Handles CT resolution, mask resolution, slice extraction, overlay + generation, and ground-truth label construction for a single case. + Returns a row dict on success, or None on skip/failure. + """ + ( + case_id, + trial_name, + manifest_path, + manifest_stem, + mode_name, + slice_dir, + ct_base, + mask_base, + use_synthetic_ct, + profile, + generate_overlay_conditions, + row_dict, + ) = args + + # Resolve CT path + ct_path = None + if use_synthetic_ct: + ct_path = _resolve_synthetic_ct(case_id, trial_name, manifest_path, ct_base) + if ct_path is None: + ct_path = str(row_dict.get("host_ct_path", "")) + if not ct_path or not os.path.isfile(ct_path): + return None + + # Resolve masks + input_mask_path = _resolve_input_mask(ct_path) if use_synthetic_ct else None + inserted_mask_path = _resolve_mask_path(case_id, trial_name, manifest_path, mask_base) + + # Extract slice + png_name = f"{manifest_stem}__C{case_id:04d}.png" + png_path = os.path.join(slice_dir, png_name) + + try: + slice_info = extract_slice( + ct_path=ct_path, + output_png=png_path, + input_mask_path=input_mask_path, + inserted_mask_path=inserted_mask_path, + save_overlay=False, + profile=profile, + nodule_label=NODULE_LABEL, + ) + except Exception as e: + logging.getLogger(__name__).warning("Failed to extract slice for case %d: %s", case_id, e) + return None + + if slice_info is None: + return None + + # Generate overlay variants + overlay_paths = {"bbox": "", "contour": "", "bbox_contour": ""} + if generate_overlay_conditions: + mask_for_overlay = input_mask_path or inserted_mask_path + if mask_for_overlay: + try: + result = generate_overlays( + plain_png_path=png_path, + mask_path=mask_for_overlay, + slice_index=slice_info.center_z, + slice_plane=(profile.slice_plane if profile else "axial"), + nodule_label=NODULE_LABEL, + ) + for cond in ("bbox", "contour", "bbox_contour"): + if result.get(cond): + overlay_paths[cond] = result[cond] + except Exception as e: + logging.getLogger(__name__).warning( + "Overlay generation failed for case %d: %s", case_id, e + ) + + # Ground truth labels + insertion_lobe = str(row_dict.get("insertion_lobe", "")) + gt_lobe = normalise_lobe(insertion_lobe) + eff_diam = row_dict.get("effective_diam_mm") + if eff_diam is None or (isinstance(eff_diam, float) and np.isnan(eff_diam)): + eff_diam = row_dict.get("nodule_diam_mm") + gt_size = "" + if eff_diam is not None and not (isinstance(eff_diam, float) and np.isnan(eff_diam)): + gt_size = diameter_to_size_bucket(float(eff_diam)) + + label_val = row_dict.get("label") + if label_val is not None and isinstance(label_val, float) and np.isnan(label_val): + label_val = None + elif label_val is not None: + label_val = int(label_val) + + return { + "case_id": case_id, + "mode": mode_name, + "trial_name": trial_name, + "dataset_name": str(row_dict.get("host_dataset", "")), + "donor_dataset": str(row_dict.get("donor_dataset", "")), + "ct_path": ct_path, + "input_mask_path": input_mask_path or "", + "inserted_mask_path": inserted_mask_path or "", + "png_path": png_path, + "png_bbox_path": overlay_paths.get("bbox", ""), + "png_contour_path": overlay_paths.get("contour", ""), + "png_bbox_contour_path": overlay_paths.get("bbox_contour", ""), + "slice_z": slice_info.center_z, + "slice_method": slice_info.method, + "preprocess_profile": profile.name if profile else DEFAULT_PROFILE, + "ground_truth_presence": "present", + "ground_truth_lobe": gt_lobe, + "ground_truth_size_bucket": gt_size, + "effective_diam_mm": ( + float(eff_diam) + if eff_diam is not None and not (isinstance(eff_diam, float) and np.isnan(eff_diam)) + else None + ), + "insertion_lobe": insertion_lobe, + "label": label_val, + "population_type": str(row_dict.get("population_type", "")), + "insertion_mode": str(row_dict.get("insertion_mode", "")), + } + + +def build_dataset( + manifest_paths: List[str], + output_dir: str, + ct_base: str = os.path.join( + os.environ.get("ITRIALSPACE_OUTPUT_DIR") + or os.environ.get("ITRIALSPACE_DATA_DIR") + or os.path.expanduser("~/.itrialspace/data"), + "generated_cts", + ), + mask_base: str = os.path.join( + os.environ.get("ITRIALSPACE_OUTPUT_DIR") + or os.environ.get("ITRIALSPACE_DATA_DIR") + or os.path.expanduser("~/.itrialspace/data"), + "inserted_masks", + ), + max_cases: Optional[int] = None, + use_synthetic_ct: bool = True, + save_overlay: bool = False, + profile: Optional[PreprocessProfile] = None, + generate_overlay_conditions: bool = False, + skip_existing: bool = False, + workers: int = 1, +) -> pd.DataFrame: + """Build the evaluation dataset from one or more manifest CSVs. + + Parameters + ---------- + manifest_paths : list of str + Paths to iTrialSpace manifest CSVs. + output_dir : str + Root output directory. PNGs go to output_dir/slices/{mode_name}/. + ct_base : str + Root of NodMAISI generated CTs. + mask_base : str + Root of inserted masks. + max_cases : int, optional + Limit total cases (for quick testing). + use_synthetic_ct : bool + If True, use NodMAISI synthetic CTs. If False, use original host CTs. + save_overlay : bool + If True, save overlay PNGs alongside slices for QC. + Overridden by *profile* if provided. + profile : PreprocessProfile, optional + Preprocessing profile controlling windowing, slice plane, format, etc. + If None, uses the default ``lung_axial`` profile behaviour. + skip_existing : bool + If True and an ``eval_dataset.csv`` already exists in *output_dir*, + reuse rows whose plain PNG is still on disk. Only genuinely new + cases (not in the cache or whose PNG is missing) trigger NIfTI + loading and slice extraction. Dramatically speeds up incremental + rebuilds when only a few new CTs have appeared. + + Returns + ------- + pd.DataFrame + The evaluation dataset, also saved to output_dir/eval_dataset.csv. + """ + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s %(levelname)s %(name)s: %(message)s", + datefmt="%H:%M:%S", + ) + + os.makedirs(output_dir, exist_ok=True) + + # ── Skip-existing cache ────────────────────────────────────────────── + _cache: Dict[tuple, dict] = {} + if skip_existing: + _old_csv = os.path.join(output_dir, "eval_dataset.csv") + if os.path.isfile(_old_csv): + _old_df = pd.read_csv(_old_csv) + for _, _r in _old_df.iterrows(): + _key = (str(_r["mode"]), str(_r["trial_name"]), int(_r["case_id"])) + _png = str(_r.get("png_path", "")) + if _png and os.path.isfile(_png): + _cache[_key] = _r.to_dict() + logger.info( + "skip-existing: loaded %d cached rows from %s", + len(_cache), + _old_csv, + ) + cache_hits = 0 + + rows = [] + total_processed = 0 + skip_count = 0 + method_counts: Dict[str, int] = {} + + # ── Phase 1: resolve cache hits and collect work items ─────────────── + work_items = [] # list of tuples for _process_single_case + + for manifest_path in manifest_paths: + logger.info("Reading manifest: %s", manifest_path) + df = pd.read_csv(manifest_path) + + # Infer mode name from the mode* ancestor directory + mode_name = _find_mode_dir_name(manifest_path) + # Use manifest stem to disambiguate when multiple CSVs per mode + manifest_stem = os.path.splitext(os.path.basename(manifest_path))[0] + + # Per-mode slice directory + slice_dir = os.path.join(output_dir, "slices", mode_name) + os.makedirs(slice_dir, exist_ok=True) + + # For multi-nodule cases, take only the primary nodule row + if "is_primary_nodule" in df.columns: + df = df[df["is_primary_nodule"] == True].copy() + + for _, row in df.iterrows(): + if max_cases and (total_processed + len(work_items)) >= max_cases: + break + + case_id = int(row["case_id"]) + trial_name = str(row["trial_name"]) + + # ── Check skip-existing cache (fast, no I/O) ───────────────── + _cache_key = (mode_name, trial_name, case_id) + if _cache and _cache_key in _cache: + # Quick CT path check — need to resolve to compare + ct_path = None + if use_synthetic_ct: + ct_path = _resolve_synthetic_ct(case_id, trial_name, manifest_path, ct_base) + if ct_path is None: + ct_path = str(row.get("host_ct_path", "")) + + cached_row = _cache[_cache_key] + cached_ct = str(cached_row.get("ct_path", "")) + if cached_ct == ct_path: + rows.append(cached_row) + cache_hits += 1 + total_processed += 1 + method = str(cached_row.get("slice_method", "cached")) + method_counts[method] = method_counts.get(method, 0) + 1 + continue + + # Needs extraction — collect as a work item + work_items.append( + ( + case_id, + trial_name, + manifest_path, + manifest_stem, + mode_name, + slice_dir, + ct_base, + mask_base, + use_synthetic_ct, + profile, + generate_overlay_conditions, + row.to_dict(), + ) + ) + + if max_cases and (total_processed + len(work_items)) >= max_cases: + break + + logger.info( + "Phase 1 done: %d cache hits, %d cases need extraction (workers=%d)", + cache_hits, + len(work_items), + workers, + ) + + # ── Phase 2: extract slices (parallel or sequential) ───────────────── + if work_items: + if workers > 1: + completed = 0 + ctx = mp.get_context("spawn") + with ProcessPoolExecutor(max_workers=workers, mp_context=ctx) as pool: + futures = {pool.submit(_process_single_case, item): item for item in work_items} + for future in as_completed(futures): + completed += 1 + try: + result = future.result() + except Exception as e: + logger.warning("Worker failed: %s", e) + skip_count += 1 + continue + if result is None: + skip_count += 1 + else: + rows.append(result) + total_processed += 1 + method = result.get("slice_method", "unknown") + method_counts[method] = method_counts.get(method, 0) + 1 + if completed % 200 == 0: + logger.info("Progress: %d/%d cases processed", completed, len(work_items)) + else: + for i, item in enumerate(work_items): + result = _process_single_case(item) + if result is None: + skip_count += 1 + else: + rows.append(result) + total_processed += 1 + method = result.get("slice_method", "unknown") + method_counts[method] = method_counts.get(method, 0) + 1 + + eval_df = pd.DataFrame(rows) + out_csv = os.path.join(output_dir, "eval_dataset.csv") + eval_df.to_csv(out_csv, index=False) + + logger.info("Eval dataset: %d cases -> %s", len(eval_df), out_csv) + logger.info("Slice methods: %s", method_counts) + if cache_hits > 0: + logger.info("skip-existing: reused %d cached rows", cache_hits) + if skip_count > 0: + logger.warning("Skipped %d cases (no nodule localisation)", skip_count) + + if generate_overlay_conditions: + n_bbox = (eval_df["png_bbox_path"] != "").sum() + n_contour = (eval_df["png_contour_path"] != "").sum() + logger.info( + "Overlays generated: bbox=%d, contour=%d (of %d cases)", n_bbox, n_contour, len(eval_df) + ) + + # Save QC grid for first 10 cases + qc_dir = os.path.join(output_dir, "qc_overlays") + qc_count = 0 + for _, r in eval_df.head(min(30, len(eval_df))).iterrows(): + if r.get("png_bbox_path") and r.get("png_contour_path"): + qc_path = os.path.join(qc_dir, f"qc_{r['mode']}_C{r['case_id']:04d}.png") + generate_qc_grid( + plain_path=r["png_path"], + bbox_path=r.get("png_bbox_path"), + contour_path=r.get("png_contour_path"), + bbox_contour_path=r.get("png_bbox_contour_path"), + output_path=qc_path, + ) + qc_count += 1 + if qc_count >= 10: + break + if qc_count > 0: + logger.info("QC grids saved: %d -> %s", qc_count, qc_dir) + + return eval_df + + +# ── CLI ────────────────────────────────────────────────────────────────────── + + +def main(): + parser = argparse.ArgumentParser( + description="Build VLM evaluation dataset from iTrialSpace manifests.", + ) + parser.add_argument( + "--manifest", + "-m", + nargs="+", + required=True, + help="Path(s) to iTrialSpace manifest CSV files.", + ) + parser.add_argument( + "--output-dir", + "-o", + required=True, + help="Output directory for eval dataset and extracted slices.", + ) + parser.add_argument( + "--ct-base", + default=os.path.join( + os.environ.get("ITRIALSPACE_OUTPUT_DIR") + or os.environ.get("ITRIALSPACE_DATA_DIR") + or os.path.expanduser("~/.itrialspace/data"), + "generated_cts", + ), + help="Root directory of NodMAISI generated CTs.", + ) + parser.add_argument( + "--mask-base", + default=os.path.join( + os.environ.get("ITRIALSPACE_OUTPUT_DIR") + or os.environ.get("ITRIALSPACE_DATA_DIR") + or os.path.expanduser("~/.itrialspace/data"), + "inserted_masks", + ), + help="Root directory of inserted masks.", + ) + parser.add_argument( + "--max-cases", + type=int, + default=None, + help="Limit total number of cases (for testing).", + ) + parser.add_argument( + "--use-host-ct", + action="store_true", + help="Use original host CTs instead of NodMAISI synthetic CTs.", + ) + parser.add_argument( + "--profile", + default=DEFAULT_PROFILE, + choices=list_profiles(), + help=( + "Preprocessing profile name controlling CT window, slice plane, " + "and output format. Default: %(default)s" + ), + ) + parser.add_argument( + "--overlays", + action="store_true", + help=( + "Generate bbox, contour, and bbox_contour overlay PNGs alongside " + "each plain slice. Adds png_bbox_path, png_contour_path, " + "png_bbox_contour_path columns to the dataset CSV." + ), + ) + parser.add_argument( + "--skip-existing", + action="store_true", + help=( + "Reuse rows from existing eval_dataset.csv when the plain PNG " + "is still on disk and the CT path has not changed. Only new " + "cases trigger NIfTI loading. Dramatically speeds up incremental " + "rebuilds." + ), + ) + parser.add_argument( + "--workers", + "-j", + type=int, + default=1, + help=( + "Number of parallel worker processes for slice extraction. " + "Each worker loads one 512x512x256 CT volume at a time " + "(~256 MB RAM). Default: 1 (sequential)." + ), + ) + args = parser.parse_args() + + build_dataset( + manifest_paths=args.manifest, + output_dir=args.output_dir, + ct_base=args.ct_base, + mask_base=args.mask_base, + max_cases=args.max_cases, + use_synthetic_ct=not args.use_host_ct, + profile=get_profile(args.profile), + generate_overlay_conditions=args.overlays, + skip_existing=args.skip_existing, + workers=args.workers, + ) + + +if __name__ == "__main__": + main() diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/build_negative_dataset.py b/itrialspace/src/itrialspace/evaluation/vlm_eval/build_negative_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..e2313e2499e96cc921c8a1d08324fcd42cb6555e --- /dev/null +++ b/itrialspace/src/itrialspace/evaluation/vlm_eval/build_negative_dataset.py @@ -0,0 +1,427 @@ +#!/usr/bin/env python3 +""" +Build nodule-free negative slices for VLM presence detection evaluation. + +For each unique CT in an existing eval_dataset.csv, this script: +1. Loads the CT volume (RAS+ canonical) +2. Identifies all nodule z-locations (from the mask) to avoid +3. Picks a random z-index that is: + - Far from any nodule (>= MIN_Z_DISTANCE slices away) + - Within the lung field (>= MIN_LUNG_FRAC voxels in lung HU range) +4. Extracts the slice using the same profile/windowing as the positive pipeline +5. Outputs eval_dataset_negatives.csv with ground_truth_presence = "absent" + +Usage: + python -m itrialspace.evaluation.vlm_eval.build_negative_dataset \\ + --eval-csv vlm_eval/lung_axial/eval_dataset.csv \\ + --profile lung_axial \\ + --output-dir vlm_eval/lung_axial/negatives \\ + [--workers 8] [--seed 42] [--negatives-per-ct 1] + + # For MedGemma profile: + python -m itrialspace.evaluation.vlm_eval.build_negative_dataset \\ + --eval-csv vlm_eval/lung_axial_medgemma/eval_dataset.csv \\ + --profile lung_axial_medgemma \\ + --output-dir vlm_eval/lung_axial_medgemma/negatives +""" + +from __future__ import annotations + +import argparse +import logging +import os +import sys +from concurrent.futures import ProcessPoolExecutor, as_completed +from typing import List, Optional, Tuple + +import nibabel as nib +import numpy as np +import pandas as pd + +from itrialspace.evaluation.vlm_eval.preprocess_profiles import get_profile +from itrialspace.evaluation.vlm_eval.slice_extractor import ( + NODULE_LABEL, + _nodule_centroid_from_mask, + extract_slice_at_z, +) + +logger = logging.getLogger(__name__) + +# ── Tunables ───────────────────────────────────────────────────────────────── +MIN_Z_DISTANCE = 30 # minimum slices away from any nodule centroid z +MIN_LUNG_FRAC = 0.05 # ≥5% of voxels in lung HU range (-1024 to -200) +LUNG_HU_LO = -1024.0 +LUNG_HU_HI = -200.0 +MAX_CANDIDATES = 20 # max candidate slices to evaluate per CT + + +def _get_all_nodule_z( + mask_paths: List[str], + nodule_label: Optional[int], +) -> List[int]: + """Collect all nodule centroid z-indices from a list of mask paths.""" + z_list = [] + for mp in mask_paths: + if not mp or not os.path.isfile(mp): + continue + centroid = _nodule_centroid_from_mask(mp, nodule_label=nodule_label) + if centroid is not None: + z_list.append(centroid[2]) # z-index (axis 2 = axial) + return z_list + + +def _is_lung_slice(ct_data: np.ndarray, z: int, threshold: float = MIN_LUNG_FRAC) -> bool: + """Check if axial slice z has enough voxels in lung HU range.""" + slc = ct_data[:, :, z] + lung_voxels = np.sum((slc >= LUNG_HU_LO) & (slc <= LUNG_HU_HI)) + total = slc.size + return (lung_voxels / total) >= threshold + + +def _pick_negative_z( + ct_data: np.ndarray, + nodule_z_list: List[int], + rng: np.random.Generator, + n: int = 1, + min_dist: int = MIN_Z_DISTANCE, +) -> List[int]: + """Pick up to *n* negative z-indices far from all nodule locations. + + Returns a list of z-indices (may be shorter than *n* if not enough + valid candidates exist). + """ + max_z = ct_data.shape[2] - 1 + # Build set of excluded z-indices (nodule ± min_dist) + excluded = set() + for nz in nodule_z_list: + for offset in range(-min_dist, min_dist + 1): + excluded.add(nz + offset) + + # Candidate z-indices: within volume, not excluded + candidates = [z for z in range(0, max_z + 1) if z not in excluded] + if not candidates: + # Relax distance to min_dist // 2 + half_dist = max(min_dist // 2, 5) + excluded_relaxed = set() + for nz in nodule_z_list: + for offset in range(-half_dist, half_dist + 1): + excluded_relaxed.add(nz + offset) + candidates = [z for z in range(0, max_z + 1) if z not in excluded_relaxed] + if not candidates: + return [] + + # Shuffle and pick candidates that pass the lung-field check + rng.shuffle(candidates) + picked = [] + for z in candidates[: MAX_CANDIDATES * 3]: # check a generous number + if _is_lung_slice(ct_data, z): + picked.append(z) + if len(picked) >= n: + break + return picked + + +def _process_one_ct(args: Tuple) -> List[dict]: + """Worker function: extract negative slices for one CT. + + Returns a list of row dicts for the negatives CSV. + """ + ( + ct_path, + mask_paths, + mode, + trial_name, + dataset_name, + donor_dataset, + population_type, + insertion_mode, + profile_name, + output_dir, + seed, + n_neg, + nodule_label, + source, + ) = args + + rng = np.random.default_rng(seed) + profile = get_profile(profile_name) + + # Collect nodule z-locations to avoid + nodule_z_list = _get_all_nodule_z(mask_paths, nodule_label=nodule_label) + if not nodule_z_list: + logger.warning("No nodule z found for %s — skipping", ct_path) + return [] + + # Load CT volume + try: + nii = nib.load(ct_path) + nii = nib.as_closest_canonical(nii) + ct_data = nii.get_fdata(dtype=np.float32) + except Exception as e: + logger.warning("Failed to load CT %s: %s", ct_path, e) + return [] + + # Pick negative z-indices + neg_z_list = _pick_negative_z(ct_data, nodule_z_list, rng, n=n_neg) + if not neg_z_list: + logger.warning("No valid negative z found for %s", ct_path) + return [] + + rows = [] + for i, neg_z in enumerate(neg_z_list): + # Build output filename + ct_basename = os.path.basename(os.path.dirname(ct_path)) + if source == "real": + # Real CTs: use ct filename stem + ct_basename = os.path.splitext(os.path.splitext(os.path.basename(ct_path))[0])[0] + + suffix = f"_neg{i}" if n_neg > 1 else "_neg" + ext = ".png" + if profile and profile.output_format == "npy": + ext = ".npy" + + out_name = f"{ct_basename}{suffix}{ext}" + mode_dir = mode if source == "synthetic" else dataset_name + out_path = os.path.join(output_dir, "slices_negative", mode_dir, out_name) + + try: + extract_slice_at_z(ct_path, neg_z, out_path, profile=profile) + except Exception as e: + logger.warning("Failed extracting neg slice z=%d from %s: %s", neg_z, ct_path, e) + continue + + row = { + "ct_path": ct_path, + "mode": mode, + "trial_name": trial_name, + "dataset_name": dataset_name, + "donor_dataset": donor_dataset, + "png_path": out_path, + "slice_z": neg_z, + "slice_method": "negative_random", + "preprocess_profile": profile_name, + "ground_truth_presence": "absent", + "ground_truth_lobe": "N/A", + "ground_truth_size_bucket": "N/A", + "effective_diam_mm": 0.0, + "population_type": population_type, + "insertion_mode": insertion_mode, + "source": source, + "nodule_z_avoided": str(nodule_z_list), + } + rows.append(row) + + return rows + + +def build_synthetic_negatives( + eval_csv: str, + profile_name: str, + output_dir: str, + workers: int = 8, + seed: int = 42, + n_neg: int = 1, +) -> pd.DataFrame: + """Build negative slices from the synthetic eval_dataset.csv.""" + df = pd.read_csv(eval_csv) + logger.info( + "Loaded %d rows from %s (%d unique CTs)", len(df), eval_csv, df["ct_path"].nunique() + ) + + # Group by CT path: collect all mask paths per CT + tasks = [] + for ct_path, grp in df.groupby("ct_path"): + mask_paths = [] + for _, row in grp.iterrows(): + if pd.notna(row.get("input_mask_path")): + mask_paths.append(row["input_mask_path"]) + if pd.notna(row.get("inserted_mask_path")): + mask_paths.append(row["inserted_mask_path"]) + mask_paths = list(set(mask_paths)) + + first = grp.iloc[0] + # Deterministic per-CT seed + ct_seed = seed + hash(ct_path) % (2**31) + + tasks.append( + ( + ct_path, + mask_paths, + first.get("mode", ""), + first.get("trial_name", ""), + first.get("dataset_name", ""), + first.get("donor_dataset", ""), + first.get("population_type", ""), + first.get("insertion_mode", ""), + profile_name, + output_dir, + ct_seed, + n_neg, + NODULE_LABEL, + "synthetic", + ) + ) + + logger.info("Processing %d CTs with %d workers...", len(tasks), workers) + all_rows = [] + with ProcessPoolExecutor(max_workers=workers) as pool: + futures = {pool.submit(_process_one_ct, t): t[0] for t in tasks} + done = 0 + for fut in as_completed(futures): + done += 1 + if done % 500 == 0: + logger.info(" %d / %d CTs done", done, len(tasks)) + try: + rows = fut.result() + all_rows.extend(rows) + except Exception as e: + logger.warning("Worker error for %s: %s", futures[fut], e) + + neg_df = pd.DataFrame(all_rows) + return neg_df + + +def build_real_negatives( + eval_csv: str, + profile_name: str, + output_dir: str, + workers: int = 8, + seed: int = 42, + n_neg: int = 1, +) -> pd.DataFrame: + """Build negative slices from the real eval_dataset.csv.""" + df = pd.read_csv(eval_csv) + logger.info( + "Loaded %d rows from %s (%d unique CTs)", len(df), eval_csv, df["ct_path"].nunique() + ) + + # Group by CT path: collect all nodule mask paths per CT + tasks = [] + for ct_path, grp in df.groupby("ct_path"): + mask_paths = [] + mask_col = "nodule_mask_path" if "nodule_mask_path" in grp.columns else "input_mask_path" + for _, row in grp.iterrows(): + if pd.notna(row.get(mask_col)): + mask_paths.append(row[mask_col]) + mask_paths = list(set(mask_paths)) + + first = grp.iloc[0] + ct_seed = seed + hash(ct_path) % (2**31) + + dataset = first.get("dataset", first.get("dataset_name", "")) + + tasks.append( + ( + ct_path, + mask_paths, + "", # mode (N/A for real) + "", # trial_name + dataset, + "", # donor_dataset + "", # population_type + "", # insertion_mode + profile_name, + output_dir, + ct_seed, + n_neg, + None, # nodule_label = None (binary masks for real) + "real", + ) + ) + + logger.info("Processing %d unique real CTs with %d workers...", len(tasks), workers) + all_rows = [] + with ProcessPoolExecutor(max_workers=workers) as pool: + futures = {pool.submit(_process_one_ct, t): t[0] for t in tasks} + done = 0 + for fut in as_completed(futures): + done += 1 + if done % 500 == 0: + logger.info(" %d / %d CTs done", done, len(tasks)) + try: + rows = fut.result() + all_rows.extend(rows) + except Exception as e: + logger.warning("Worker error for %s: %s", futures[fut], e) + + neg_df = pd.DataFrame(all_rows) + return neg_df + + +def main(): + parser = argparse.ArgumentParser( + description="Build nodule-free negative slices for VLM presence evaluation." + ) + parser.add_argument( + "--eval-csv", required=True, help="Path to existing eval_dataset.csv (positive slices)" + ) + parser.add_argument("--profile", default="lung_axial", help="Preprocessing profile name") + parser.add_argument("--output-dir", required=True, help="Root output directory for negatives") + parser.add_argument( + "--source", + choices=["synthetic", "real"], + default="synthetic", + help="Whether the eval CSV is synthetic or real", + ) + parser.add_argument("--workers", type=int, default=8, help="Number of parallel workers") + parser.add_argument("--seed", type=int, default=42, help="Random seed for reproducibility") + parser.add_argument( + "--negatives-per-ct", type=int, default=1, help="Number of negative slices per CT" + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s %(levelname)-8s %(name)s: %(message)s", + ) + + if args.source == "real": + neg_df = build_real_negatives( + args.eval_csv, + args.profile, + args.output_dir, + workers=args.workers, + seed=args.seed, + n_neg=args.negatives_per_ct, + ) + else: + neg_df = build_synthetic_negatives( + args.eval_csv, + args.profile, + args.output_dir, + workers=args.workers, + seed=args.seed, + n_neg=args.negatives_per_ct, + ) + + if neg_df.empty: + logger.error("No negative slices generated!") + sys.exit(1) + + os.makedirs(args.output_dir, exist_ok=True) + out_csv = os.path.join(args.output_dir, "eval_dataset_negatives.csv") + neg_df.to_csv(out_csv, index=False) + logger.info("Saved %d negative slices → %s", len(neg_df), out_csv) + + # Summary + print(f"\n{'='*60}") + print("Negative slice extraction complete") + print(f" Source: {args.source}") + print(f" Profile: {args.profile}") + print(f" Total: {len(neg_df)} negative slices") + if "mode" in neg_df.columns and neg_df["mode"].str.len().sum() > 0: + print(" By mode:") + for mode, cnt in neg_df["mode"].value_counts().items(): + if mode: + print(f" {mode}: {cnt}") + if "dataset_name" in neg_df.columns: + print(" By dataset:") + for ds, cnt in neg_df["dataset_name"].value_counts().items(): + if ds: + print(f" {ds}: {cnt}") + print(f" CSV: {out_csv}") + print(f"{'='*60}") + + +if __name__ == "__main__": + main() diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/build_real_dataset.py b/itrialspace/src/itrialspace/evaluation/vlm_eval/build_real_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..823acebd3cf0f627a1ba41b48b9be5928757dc4c --- /dev/null +++ b/itrialspace/src/itrialspace/evaluation/vlm_eval/build_real_dataset.py @@ -0,0 +1,375 @@ +""" +Build a VLM evaluation dataset from real CT images and nodule profiles. + +Reads per-dataset nodule profile CSVs (from iTrialSpace ``profiles/``), +resolves the corresponding raw CT NIfTI and per-nodule segmentation mask, +extracts a lesion-centred 2D axial slice, and produces a clean +``eval_dataset.csv`` in the same schema as the synthetic pipeline. + +Differences from the synthetic pipeline (build_dataset.py): +- No synthetic CT / NodMAISI – uses raw CTs under ``raw_ct/`` +- Per-nodule binary masks (label > 0) under ``masks/{dataset}/nodule_seg/`` +- Ground truth from profile CSV columns (``lobe_name``, ``nodule_mean_diam_mm``) +- Column normalisation across heterogeneous datasets +""" + +from __future__ import annotations + +import argparse +import logging +import os +from typing import Dict, List, Optional + +import pandas as pd + +from itrialspace.evaluation.vlm_eval.overlay import generate_overlays, generate_qc_grid +from itrialspace.evaluation.vlm_eval.preprocess_profiles import ( + DEFAULT_PROFILE, + PreprocessProfile, + get_profile, + list_profiles, +) +from itrialspace.evaluation.vlm_eval.prompt_templates import ( + diameter_to_size_bucket, + normalise_lobe, +) +from itrialspace.evaluation.vlm_eval.slice_extractor import extract_slice + +logger = logging.getLogger(__name__) + +# The 7 public datasets of the iTrialSpace core. NLST3D is intentionally excluded — it is +# permanently purged from the project (see the core's NLST3D guard + purge tests); do not +# re-add it to this default list. +ALL_DATASETS = [ + "DLCS24", + "IMDCT", + "LNDbv4", + "LUNA16", + "LUNA25", + "LUNGx", + "NSCLCR", +] + + +def _resolve_nodule_mask( + row: pd.Series, + dataset: str, + masks_base: str, +) -> Optional[str]: + """Resolve the per-nodule segmentation mask path for a profile row. + + Returns the absolute path to the NIfTI mask, or None if not found. + + Naming conventions vary by dataset: + - Most: ``masks/{dataset}/nodule_seg/{AnnotationID}.nii.gz`` + - IMDCT: ``masks/{dataset}/nodule_seg/{PatientID}_seg.nii.gz`` + """ + mask_dir = os.path.join(masks_base, dataset, "nodule_seg") + + if dataset == "IMDCT": + pid = str(row.get("PatientID", "")) + if not pid: + return None + mask_path = os.path.join(mask_dir, f"{pid}_seg.nii.gz") + else: + ann_id = str(row.get("AnnotationID", "")) + if not ann_id or ann_id == "nan": + return None + mask_path = os.path.join(mask_dir, f"{ann_id}.nii.gz") + + return mask_path if os.path.isfile(mask_path) else None + + +def _resolve_raw_ct( + row: pd.Series, + raw_ct_base: str, +) -> Optional[str]: + """Resolve the raw CT NIfTI path from the profile row's ct_path column. + + ``ct_path`` already contains ``{DATASET}/{filename}.nii.gz``. + """ + ct_rel = str(row.get("ct_path", "")) + if not ct_rel or ct_rel == "nan": + return None + ct_full = os.path.join(raw_ct_base, ct_rel) + return ct_full if os.path.isfile(ct_full) else None + + +def _case_id_for_row(row: pd.Series, dataset: str) -> str: + """Build a unique case identifier for a profile row.""" + if dataset == "IMDCT": + return str(row.get("PatientID", "")) + return str(row.get("AnnotationID", "")) + + +def build_real_dataset( + data_base: str, + output_dir: str, + datasets: Optional[List[str]] = None, + max_cases: Optional[int] = None, + profile: Optional[PreprocessProfile] = None, + generate_overlay_conditions: bool = False, +) -> pd.DataFrame: + """Build evaluation dataset from real CT images. + + Parameters + ---------- + data_base : str + Root of iTrialSpace data (contains ``raw_ct/``, ``profiles/``, + ``masks/``). + output_dir : str + Root output directory. + datasets : list of str, optional + Which datasets to include. If None, uses all 7 core datasets. + max_cases : int, optional + Limit total cases (for quick testing). + profile : PreprocessProfile, optional + Preprocessing profile. + generate_overlay_conditions : bool + If True, generate bbox/contour/bbox_contour overlays. + + Returns + ------- + pd.DataFrame + The evaluation dataset, also saved to ``output_dir/eval_dataset.csv``. + """ + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s %(levelname)s %(name)s: %(message)s", + datefmt="%H:%M:%S", + ) + + os.makedirs(output_dir, exist_ok=True) + + if datasets is None: + datasets = list(ALL_DATASETS) + + raw_ct_base = os.path.join(data_base, "raw_ct") + masks_base = os.path.join(data_base, "masks") + profiles_dir = os.path.join(data_base, "profiles") + + rows: List[dict] = [] + total_processed = 0 + skip_count = 0 + method_counts: Dict[str, int] = {} + + for dataset in datasets: + profile_csv = os.path.join(profiles_dir, f"{dataset}_nodule_profiles.csv") + if not os.path.isfile(profile_csv): + logger.warning("Profile CSV not found: %s — skipping dataset", profile_csv) + continue + + logger.info("Reading profile: %s", profile_csv) + df = pd.read_csv(profile_csv) + + # Per-dataset slice directory + slice_dir = os.path.join(output_dir, "slices", dataset) + os.makedirs(slice_dir, exist_ok=True) + + for _, row in df.iterrows(): + if max_cases and total_processed >= max_cases: + break + + case_id = _case_id_for_row(row, dataset) + + # Resolve raw CT + ct_path = _resolve_raw_ct(row, raw_ct_base) + if ct_path is None: + logger.debug("CT not found for %s — skipping", case_id) + skip_count += 1 + continue + + # Resolve nodule mask + mask_path = _resolve_nodule_mask(row, dataset, masks_base) + if mask_path is None: + logger.debug("Nodule mask not found for %s — skipping", case_id) + skip_count += 1 + continue + + # Output PNG + png_name = f"{case_id}.png" + png_path = os.path.join(slice_dir, png_name) + + try: + slice_info = extract_slice( + ct_path=ct_path, + output_png=png_path, + input_mask_path=mask_path, + inserted_mask_path=None, + profile=profile, + nodule_label=None, # binary masks: any non-zero voxel + ) + except Exception as e: + logger.warning("Failed to extract slice for %s: %s", case_id, e) + skip_count += 1 + continue + + if slice_info is None: + skip_count += 1 + continue + + method_counts[slice_info.method] = method_counts.get(slice_info.method, 0) + 1 + + # ── Generate overlay variants ───────────────────────────────── + overlay_paths = {"bbox": "", "contour": "", "bbox_contour": ""} + if generate_overlay_conditions and mask_path: + try: + result = generate_overlays( + plain_png_path=png_path, + mask_path=mask_path, + slice_index=slice_info.center_z, + slice_plane=(profile.slice_plane if profile else "axial"), + nodule_label=None, # binary per-nodule masks + ) + for cond in ("bbox", "contour", "bbox_contour"): + if result.get(cond): + overlay_paths[cond] = result[cond] + except Exception as e: + logger.warning("Overlay generation failed for %s: %s", case_id, e) + + # ── Ground truth labels ─────────────────────────────────────── + lobe_raw = str(row.get("lobe_name", "")) + gt_lobe = normalise_lobe(lobe_raw) + + diam = row.get("nodule_mean_diam_mm") + gt_size = diameter_to_size_bucket(float(diam)) if pd.notna(diam) else "" + + rows.append( + { + "case_id": case_id, + "dataset": dataset, + "ct_path": ct_path, + "nodule_mask_path": mask_path, + "png_path": png_path, + "png_bbox_path": overlay_paths.get("bbox", ""), + "png_contour_path": overlay_paths.get("contour", ""), + "png_bbox_contour_path": overlay_paths.get("bbox_contour", ""), + "slice_z": slice_info.center_z, + "slice_method": slice_info.method, + "preprocess_profile": (profile.name if profile else DEFAULT_PROFILE), + "ground_truth_presence": "present", + "ground_truth_lobe": gt_lobe, + "ground_truth_size_bucket": gt_size, + "nodule_mean_diam_mm": (float(diam) if pd.notna(diam) else None), + "lobe_name": lobe_raw, + } + ) + total_processed += 1 + + if max_cases and total_processed >= max_cases: + break + + eval_df = pd.DataFrame(rows) + out_csv = os.path.join(output_dir, "eval_dataset.csv") + eval_df.to_csv(out_csv, index=False) + + logger.info("Real CT eval dataset: %d cases -> %s", len(eval_df), out_csv) + logger.info("Slice methods: %s", method_counts) + if skip_count > 0: + logger.warning("Skipped %d cases (missing CT/mask)", skip_count) + + # ── Per-dataset summary ─────────────────────────────────────────────── + if len(eval_df) > 0: + for ds in eval_df["dataset"].unique(): + n = len(eval_df[eval_df["dataset"] == ds]) + logger.info(" %s: %d nodules", ds, n) + + if generate_overlay_conditions: + n_bbox = (eval_df["png_bbox_path"] != "").sum() + n_contour = (eval_df["png_contour_path"] != "").sum() + logger.info( + "Overlays: bbox=%d, contour=%d (of %d cases)", + n_bbox, + n_contour, + len(eval_df), + ) + + # QC grids for first 10 cases + qc_dir = os.path.join(output_dir, "qc_overlays") + qc_count = 0 + for _, r in eval_df.head(min(30, len(eval_df))).iterrows(): + if r.get("png_bbox_path") and r.get("png_contour_path"): + qc_path = os.path.join( + qc_dir, + f"qc_{r['dataset']}_{r['case_id']}.png", + ) + generate_qc_grid( + plain_path=r["png_path"], + bbox_path=r.get("png_bbox_path"), + contour_path=r.get("png_contour_path"), + bbox_contour_path=r.get("png_bbox_contour_path"), + output_path=qc_path, + ) + qc_count += 1 + if qc_count >= 10: + break + if qc_count > 0: + logger.info("QC grids saved: %d -> %s", qc_count, qc_dir) + + return eval_df + + +# ── CLI ────────────────────────────────────────────────────────────────────── + + +def main(): + parser = argparse.ArgumentParser( + description="Build VLM evaluation dataset from real CT images.", + ) + parser.add_argument( + "--data-base", + required=True, + help=( + "Root of iTrialSpace data directory containing raw_ct/, " + "profiles/, and masks/ sub-directories." + ), + ) + parser.add_argument( + "--output-dir", + "-o", + required=True, + help="Output directory for eval dataset and extracted slices.", + ) + parser.add_argument( + "--datasets", + nargs="+", + default=None, + choices=ALL_DATASETS, + help=( + "Which datasets to include. Default: all 7 core datasets. " + f"Choices: {', '.join(ALL_DATASETS)}" + ), + ) + parser.add_argument( + "--max-cases", + type=int, + default=None, + help="Limit total number of cases (for testing).", + ) + parser.add_argument( + "--profile", + default=DEFAULT_PROFILE, + choices=list_profiles(), + help=("Preprocessing profile name. Default: %(default)s"), + ) + parser.add_argument( + "--overlays", + action="store_true", + help=( + "Generate bbox, contour, and bbox_contour overlay PNGs alongside " "each plain slice." + ), + ) + args = parser.parse_args() + + build_real_dataset( + data_base=args.data_base, + output_dir=args.output_dir, + datasets=args.datasets, + max_cases=args.max_cases, + profile=get_profile(args.profile), + generate_overlay_conditions=args.overlays, + ) + + +if __name__ == "__main__": + main() diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/comparison.py b/itrialspace/src/itrialspace/evaluation/vlm_eval/comparison.py new file mode 100644 index 0000000000000000000000000000000000000000..c4079844a967c7aa35047f808d89629f5662dfdb --- /dev/null +++ b/itrialspace/src/itrialspace/evaluation/vlm_eval/comparison.py @@ -0,0 +1,402 @@ +""" +Cross-condition comparison metrics and plots. + +Reads per-condition summary.json files produced by the run_conditions wrapper, +computes delta metrics (e.g. accuracy_bbox − accuracy_plain), and generates +side-by-side bar charts. + +Reporting convention: accuracy is reported on the cases scored in *every* +(task x condition x model) so all numbers share one N -- use +``metrics.common_case_ids()`` on the result frames before aggregating. For the +released dataset this is the full case count; the paper's 42,382 is the same rule +applied before inference finished. See ``docs/vlm_eval.md`` (section "Reporting +convention") and ``docs/dataset_card.md``. + +Usage +----- + python -m itrialspace.evaluation.vlm_eval.comparison \\ + --results-dir outputs/vlm_eval/lung_axial/biomedclip \\ + --conditions plain bbox contour +""" + +from __future__ import annotations + +import argparse +import json +import logging +import os +from pathlib import Path +from typing import Dict, List, Optional + +import matplotlib + +matplotlib.use("Agg") +import matplotlib.pyplot as plt +import numpy as np +import pandas as pd + +logger = logging.getLogger(__name__) + + +# ── Load per-condition summaries ───────────────────────────────────────────── + + +def _load_condition_summary( + results_dir: str, + condition: str, + sub_dir: str = "aggregate", +) -> Optional[Dict]: + """Load summary.json from results_dir/{condition}/{sub_dir}/summary.json.""" + path = os.path.join(results_dir, condition, sub_dir, "summary.json") + if not os.path.isfile(path): + logger.warning("Summary not found: %s", path) + return None + with open(path) as f: + data = json.load(f) + # Handle both flat {task: metrics} and nested {"tasks": {task: metrics}} + if "tasks" in data and isinstance(data["tasks"], dict): + return data["tasks"] + return data + + +def load_all_condition_summaries( + results_dir: str, + conditions: List[str], + sub_dir: str = "aggregate", +) -> Dict[str, Dict]: + """Load summaries for all conditions. + + Returns + ------- + dict + condition -> {task_name: metrics_dict} + """ + summaries = {} + for cond in conditions: + s = _load_condition_summary(results_dir, cond, sub_dir) + if s is not None: + summaries[cond] = s + return summaries + + +# ── Delta computation ──────────────────────────────────────────────────────── + + +def compute_deltas( + summaries: Dict[str, Dict], + baseline: str = "plain", + metric_key: str = "accuracy", +) -> pd.DataFrame: + """Compute per-task deltas relative to the baseline condition. + + Returns a DataFrame: + task | condition | {metric_key} | delta + """ + baseline_data = summaries.get(baseline) + if baseline_data is None: + raise ValueError(f"Baseline condition '{baseline}' not found") + + rows = [] + for cond, tasks in summaries.items(): + for task_name, metrics in tasks.items(): + value = metrics.get(metric_key, 0.0) + base_value = baseline_data.get(task_name, {}).get(metric_key, 0.0) + delta = value - base_value if cond != baseline else 0.0 + rows.append( + { + "task": task_name, + "condition": cond, + metric_key: value, + "delta": delta, + } + ) + + return pd.DataFrame(rows) + + +# ── Summary table ──────────────────────────────────────────────────────────── + + +def build_comparison_table( + summaries: Dict[str, Dict], + metric_key: str = "accuracy", +) -> pd.DataFrame: + """Build a pivot table: rows=tasks, columns=conditions. + + Returns + ------- + pd.DataFrame + Index = task names, columns = condition names, values = metric. + """ + records = [] + for cond, tasks in summaries.items(): + for task_name, metrics in tasks.items(): + records.append( + { + "task": task_name, + "condition": cond, + metric_key: metrics.get(metric_key, 0.0), + } + ) + if not records: + return pd.DataFrame() + df = pd.DataFrame(records) + return df.pivot(index="task", columns="condition", values=metric_key) + + +# ── Plots ──────────────────────────────────────────────────────────────────── + +_COND_COLORS = { + "plain": "#4C72B0", + "bbox": "#55A868", + "contour": "#C44E52", + "bbox_contour": "#8172B2", +} + + +def plot_condition_comparison( + summaries: Dict[str, Dict], + title: str, + output_path: Path, + metric_key: str = "accuracy", + figsize: tuple = (10, 5), +) -> Path: + """Grouped bar chart: tasks on x-axis, bars for each condition.""" + table = build_comparison_table(summaries, metric_key) + if table.empty: + return output_path + + tasks = list(table.index) + conditions = list(table.columns) + n_tasks = len(tasks) + n_conds = len(conditions) + + x = np.arange(n_tasks) + width = 0.8 / n_conds + + fig, ax = plt.subplots(figsize=figsize) + for i, cond in enumerate(conditions): + values = [table.loc[t, cond] if t in table.index else 0 for t in tasks] + color = _COND_COLORS.get(cond, None) + bars = ax.bar(x + i * width, values, width, label=cond, color=color) + for bar, val in zip(bars, values): + ax.text( + bar.get_x() + bar.get_width() / 2, + bar.get_height() + 0.01, + f"{val:.1%}", + ha="center", + va="bottom", + fontsize=7, + ) + + ax.set_xticks(x + width * (n_conds - 1) / 2) + ax.set_xticklabels(tasks) + ax.set_ylabel(metric_key.replace("_", " ").title()) + ax.set_title(title) + ax.set_ylim(0, 1.15) + ax.legend() + plt.tight_layout() + + output_path = Path(output_path) + output_path.parent.mkdir(parents=True, exist_ok=True) + fig.savefig(output_path, dpi=150) + plt.close(fig) + return output_path + + +def plot_delta_bars( + deltas_df: pd.DataFrame, + title: str, + output_path: Path, + metric_key: str = "accuracy", + figsize: tuple = (10, 5), +) -> Path: + """Bar chart of accuracy deltas relative to plain baseline.""" + non_baseline = deltas_df[deltas_df["condition"] != "plain"].copy() + if non_baseline.empty: + return output_path + + tasks = sorted(non_baseline["task"].unique()) + conditions = sorted(non_baseline["condition"].unique()) + n_tasks = len(tasks) + n_conds = len(conditions) + + x = np.arange(n_tasks) + width = 0.8 / max(n_conds, 1) + + fig, ax = plt.subplots(figsize=figsize) + for i, cond in enumerate(conditions): + cond_data = non_baseline[non_baseline["condition"] == cond] + values = [] + for t in tasks: + row = cond_data[cond_data["task"] == t] + values.append(row["delta"].values[0] if len(row) > 0 else 0.0) + color = _COND_COLORS.get(cond, None) + bars = ax.bar(x + i * width, values, width, label=cond, color=color) + for bar, val in zip(bars, values): + offset = 0.005 if val >= 0 else -0.015 + ax.text( + bar.get_x() + bar.get_width() / 2, + bar.get_height() + offset, + f"{val:+.1%}", + ha="center", + va="bottom" if val >= 0 else "top", + fontsize=8, + ) + + ax.set_xticks(x + width * (n_conds - 1) / 2) + ax.set_xticklabels(tasks) + ax.set_ylabel(f"Δ {metric_key}") + ax.set_title(title) + ax.axhline(0, color="gray", linewidth=0.5, linestyle="--") + ax.legend() + plt.tight_layout() + + output_path = Path(output_path) + output_path.parent.mkdir(parents=True, exist_ok=True) + fig.savefig(output_path, dpi=150) + plt.close(fig) + return output_path + + +# ── Full comparison pipeline ───────────────────────────────────────────────── + + +def run_comparison( + results_dir: str, + conditions: List[str], + model_name: str = "", + sub_dir: str = "aggregate", + output_dir: Optional[str] = None, +) -> Dict: + """Run the full comparison pipeline. + + Parameters + ---------- + results_dir : str + Root directory containing per-condition sub-directories. + conditions : list of str + Conditions to compare. + model_name : str + For plot titles. + sub_dir : str + Sub-directory within each condition dir to find summary.json. + output_dir : str, optional + Where to write comparison outputs. Default: results_dir/comparison. + + Returns + ------- + dict + Comparison summary with tables and deltas. + """ + if output_dir is None: + output_dir = os.path.join(results_dir, "comparison") + os.makedirs(output_dir, exist_ok=True) + + summaries = load_all_condition_summaries(results_dir, conditions, sub_dir) + if not summaries: + logger.error("No condition summaries found in %s", results_dir) + return {} + + found = list(summaries.keys()) + logger.info("Loaded summaries for conditions: %s", found) + + # Comparison table + table = build_comparison_table(summaries) + table_path = os.path.join(output_dir, "accuracy_table.csv") + table.to_csv(table_path) + logger.info("Accuracy table -> %s", table_path) + + # Deltas + deltas = compute_deltas(summaries, baseline="plain") + deltas_path = os.path.join(output_dir, "deltas.csv") + deltas.to_csv(deltas_path, index=False) + logger.info("Deltas -> %s", deltas_path) + + # Plots + label = f"{model_name} – " if model_name else "" + plots_dir = os.path.join(output_dir, "plots") + + plot_condition_comparison( + summaries, + title=f"{label}Accuracy by Task × Condition", + output_path=Path(plots_dir) / "accuracy_by_condition.png", + ) + + plot_delta_bars( + deltas, + title=f"{label}Accuracy Δ (vs. plain)", + output_path=Path(plots_dir) / "accuracy_delta.png", + ) + + # Summary JSON + summary = { + "conditions": found, + "accuracy_table": table.to_dict(), + "deltas": deltas.to_dict(orient="records"), + } + summary_path = os.path.join(output_dir, "comparison_summary.json") + with open(summary_path, "w") as f: + json.dump(summary, f, indent=2, default=str) + logger.info("Comparison summary -> %s", summary_path) + + print(f"\nComparison table:\n{table.to_string()}") + print("\nDeltas (vs. plain):") + non_base = deltas[deltas["condition"] != "plain"] + if not non_base.empty: + print(non_base.to_string(index=False)) + + return summary + + +# ── CLI ────────────────────────────────────────────────────────────────────── + + +def main(): + parser = argparse.ArgumentParser( + description="Compare VLM results across image presentation conditions.", + ) + parser.add_argument( + "--results-dir", + required=True, + help="Root directory with per-condition sub-dirs (e.g. .../biomedclip).", + ) + parser.add_argument( + "--conditions", + nargs="+", + default=["plain", "bbox", "contour", "bbox_contour"], + help="Conditions to compare.", + ) + parser.add_argument( + "--model-name", + default="", + help="Model name for plot titles.", + ) + parser.add_argument( + "--sub-dir", + default="aggregate", + help="Sub-directory within each condition dir for summary.json.", + ) + parser.add_argument( + "--output-dir", + default=None, + help="Output directory for comparison results.", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s %(levelname)s %(name)s: %(message)s", + ) + + run_comparison( + results_dir=args.results_dir, + conditions=args.conditions, + model_name=args.model_name, + sub_dir=args.sub_dir, + output_dir=args.output_dir, + ) + + +if __name__ == "__main__": + main() diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/cross_model_comparison.py b/itrialspace/src/itrialspace/evaluation/vlm_eval/cross_model_comparison.py new file mode 100644 index 0000000000000000000000000000000000000000..6c4228fcd8846bb39c268a5ca1970ae932512d6d --- /dev/null +++ b/itrialspace/src/itrialspace/evaluation/vlm_eval/cross_model_comparison.py @@ -0,0 +1,471 @@ +""" +Cross-model, cross-condition comparison. + +Aggregates per-model comparison results (produced by comparison.py) across +all three VLMs and generates a unified summary table, cross-model plots, +and a combined deltas report. + +Reporting convention: accuracy is reported on the cases scored in *every* +(task x condition x model) so all numbers share one N. Use +``metrics.common_case_ids()`` on the result frames before aggregating. For the +released dataset this is the full case count (42,858 synthetic / 13,087 real); +the paper's 42,382 is the same rule at an earlier, pre-inference snapshot. See +``docs/vlm_eval.md`` (section "Reporting convention") and ``docs/dataset_card.md``. + +Usage +----- + python -m itrialspace.evaluation.vlm_eval.cross_model_comparison \\ + --eval-base $ITRIALSPACE_DATA_DIR/.../vlm_eval \\ + --models biomedclip llava_med medgemma \\ + --conditions plain bbox contour bbox_contour +""" + +from __future__ import annotations + +import argparse +import json +import logging +import os +from pathlib import Path +from typing import Dict, List, Optional + +import matplotlib + +matplotlib.use("Agg") +import matplotlib.pyplot as plt +import numpy as np +import pandas as pd +import seaborn as sns + +from itrialspace.evaluation.vlm_eval.comparison import ( + compute_deltas, + load_all_condition_summaries, +) + +logger = logging.getLogger(__name__) + +# Model display names for plot labels +_MODEL_LABELS = { + "biomedclip": "BiomedCLIP", + "llava_med": "LLaVA-Med", + "medgemma": "MedGemma", +} + +# Model → profile mapping +_MODEL_PROFILES = { + "biomedclip": "lung_axial", + "llava_med": "lung_axial", + "medgemma": "lung_axial_medgemma", +} + +_MODEL_COLORS = { + "biomedclip": "#4C72B0", + "llava_med": "#55A868", + "medgemma": "#C44E52", +} + +_COND_HATCHES = { + "plain": "", + "bbox": "//", + "contour": "\\\\", + "bbox_contour": "xx", +} + + +def load_all_model_summaries( + eval_base: str, + models: List[str], + conditions: List[str], + sub_dir: str = "aggregate", +) -> Dict[str, Dict[str, Dict]]: + """Load summaries for all models × conditions. + + Returns + ------- + dict + model -> condition -> {task: metrics} + """ + result = {} + for model in models: + profile = _MODEL_PROFILES.get(model, "lung_axial") + model_dir = os.path.join(eval_base, profile, model) + if not os.path.isdir(model_dir): + logger.warning("Model dir not found: %s", model_dir) + continue + summaries = load_all_condition_summaries(model_dir, conditions, sub_dir) + if summaries: + result[model] = summaries + return result + + +def build_cross_model_table( + all_summaries: Dict[str, Dict[str, Dict]], + metric_key: str = "accuracy", +) -> pd.DataFrame: + """Build a multi-index table: rows=model×condition, columns=tasks. + + Returns + ------- + pd.DataFrame + MultiIndex (model, condition), columns = tasks. + """ + records = [] + for model, cond_summaries in all_summaries.items(): + for cond, tasks in cond_summaries.items(): + for task, metrics in tasks.items(): + records.append( + { + "model": _MODEL_LABELS.get(model, model), + "condition": cond, + "task": task, + metric_key: metrics.get(metric_key, 0.0), + } + ) + if not records: + return pd.DataFrame() + df = pd.DataFrame(records) + pivot = df.pivot_table( + index=["model", "condition"], + columns="task", + values=metric_key, + ) + return pivot + + +def build_cross_model_deltas( + all_summaries: Dict[str, Dict[str, Dict]], + baseline: str = "plain", + metric_key: str = "accuracy", +) -> pd.DataFrame: + """Compute deltas for all models. + + Returns + ------- + pd.DataFrame + model | task | condition | accuracy | delta + """ + frames = [] + for model, cond_summaries in all_summaries.items(): + deltas = compute_deltas(cond_summaries, baseline=baseline, metric_key=metric_key) + deltas["model"] = _MODEL_LABELS.get(model, model) + frames.append(deltas) + if not frames: + return pd.DataFrame() + return pd.concat(frames, ignore_index=True) + + +# ── Plots ──────────────────────────────────────────────────────────────────── + + +def plot_cross_model_per_task( + all_summaries: Dict[str, Dict[str, Dict]], + output_dir: str, + metric_key: str = "accuracy", +) -> List[Path]: + """One chart per task: models on x-axis, grouped bars per condition.""" + # Collect all tasks + tasks = set() + for cond_summaries in all_summaries.values(): + for cond, task_metrics in cond_summaries.items(): + tasks |= set(task_metrics.keys()) + tasks = sorted(tasks) + + models = list(all_summaries.keys()) + conditions = set() + for cond_summaries in all_summaries.values(): + conditions |= set(cond_summaries.keys()) + conditions = sorted(conditions) + + os.makedirs(output_dir, exist_ok=True) + paths = [] + + for task in tasks: + n_models = len(models) + n_conds = len(conditions) + x = np.arange(n_models) + width = 0.8 / max(n_conds, 1) + + fig, ax = plt.subplots(figsize=(max(8, n_models * 2.5), 5)) + for j, cond in enumerate(conditions): + values = [] + for model in models: + val = 0.0 + if model in all_summaries and cond in all_summaries[model]: + val = all_summaries[model][cond].get(task, {}).get(metric_key, 0.0) + values.append(val) + + color = sns.color_palette("Set2", n_conds)[j] + hatch = _COND_HATCHES.get(cond, "") + bars = ax.bar( + x + j * width, + values, + width, + label=cond, + color=color, + hatch=hatch, + edgecolor="white", + ) + for bar, val in zip(bars, values): + ax.text( + bar.get_x() + bar.get_width() / 2, + bar.get_height() + 0.01, + f"{val:.1%}", + ha="center", + va="bottom", + fontsize=7, + ) + + labels = [_MODEL_LABELS.get(m, m) for m in models] + ax.set_xticks(x + width * (n_conds - 1) / 2) + ax.set_xticklabels(labels) + ax.set_ylabel("Accuracy") + ax.set_title(f"{task.title()} – All Models × Conditions") + ax.set_ylim(0, 1.15) + ax.legend(title="Condition", loc="upper right") + plt.tight_layout() + + out = Path(output_dir) / f"{task}_cross_model.png" + fig.savefig(out, dpi=150) + plt.close(fig) + paths.append(out) + + return paths + + +def plot_cross_model_deltas( + deltas_df: pd.DataFrame, + output_dir: str, + metric_key: str = "accuracy", +) -> List[Path]: + """One chart per task: model × condition delta bars.""" + if deltas_df.empty: + return [] + + non_base = deltas_df[deltas_df["condition"] != "plain"] + if non_base.empty: + return [] + + tasks = sorted(non_base["task"].unique()) + os.makedirs(output_dir, exist_ok=True) + paths = [] + + for task in tasks: + task_data = non_base[non_base["task"] == task] + models = sorted(task_data["model"].unique()) + conditions = sorted(task_data["condition"].unique()) + n_models = len(models) + n_conds = len(conditions) + + x = np.arange(n_models) + width = 0.8 / max(n_conds, 1) + + fig, ax = plt.subplots(figsize=(max(8, n_models * 2.5), 5)) + for j, cond in enumerate(conditions): + values = [] + for model in models: + row = task_data[(task_data["model"] == model) & (task_data["condition"] == cond)] + values.append(row["delta"].values[0] if len(row) > 0 else 0.0) + + color = sns.color_palette("Set2", n_conds)[j] + bars = ax.bar(x + j * width, values, width, label=cond, color=color) + for bar, val in zip(bars, values): + offset = 0.005 if val >= 0 else -0.015 + ax.text( + bar.get_x() + bar.get_width() / 2, + bar.get_height() + offset, + f"{val:+.1%}", + ha="center", + va="bottom" if val >= 0 else "top", + fontsize=7, + ) + + ax.set_xticks(x + width * (n_conds - 1) / 2) + ax.set_xticklabels(models) + ax.set_ylabel(f"Δ {metric_key}") + ax.set_title(f"{task.title()} – Accuracy Δ (vs. plain)") + ax.axhline(0, color="gray", linewidth=0.5, linestyle="--") + ax.legend(title="Condition") + plt.tight_layout() + + out = Path(output_dir) / f"{task}_delta_cross_model.png" + fig.savefig(out, dpi=150) + plt.close(fig) + paths.append(out) + + return paths + + +def plot_heatmap( + table: pd.DataFrame, + title: str, + output_path: Path, + figsize: tuple = (12, 6), +) -> Path: + """Model×condition heatmap showing accuracy per task.""" + if table.empty: + return output_path + + fig, ax = plt.subplots(figsize=figsize) + sns.heatmap( + table, + annot=True, + fmt=".1%", + cmap="RdYlGn", + vmin=0, + vmax=1, + ax=ax, + linewidths=0.5, + ) + ax.set_title(title) + plt.tight_layout() + + output_path = Path(output_path) + output_path.parent.mkdir(parents=True, exist_ok=True) + fig.savefig(output_path, dpi=150) + plt.close(fig) + return output_path + + +# ── Main pipeline ──────────────────────────────────────────────────────────── + + +def run_cross_model_comparison( + eval_base: str, + models: List[str], + conditions: List[str], + output_dir: Optional[str] = None, + sub_dir: str = "aggregate", +) -> Dict: + """Run the full cross-model comparison pipeline. + + Parameters + ---------- + eval_base : str + Root of vlm_eval/ (e.g. $ITRIALSPACE_DATA_DIR/.../iTrialSpace/vlm_eval). + models : list of str + Model names (biomedclip, llava_med, medgemma). + conditions : list of str + Image conditions to compare. + output_dir : str, optional + Where to write outputs. Default: eval_base/cross_model_comparison. + + Returns + ------- + dict + Summary with tables and deltas. + """ + if output_dir is None: + output_dir = os.path.join(eval_base, "cross_model_comparison") + os.makedirs(output_dir, exist_ok=True) + plots_dir = os.path.join(output_dir, "plots") + + # Load all summaries + all_summaries = load_all_model_summaries(eval_base, models, conditions, sub_dir) + if not all_summaries: + logger.error("No model summaries found in %s", eval_base) + return {} + + found_models = list(all_summaries.keys()) + logger.info("Loaded summaries for models: %s", found_models) + + # Cross-model table + table = build_cross_model_table(all_summaries) + table_path = os.path.join(output_dir, "cross_model_accuracy.csv") + table.to_csv(table_path) + logger.info("Cross-model table -> %s", table_path) + print(f"\nCross-model accuracy table:\n{table.to_string()}") + + # Cross-model deltas + deltas = build_cross_model_deltas(all_summaries) + deltas_path = os.path.join(output_dir, "cross_model_deltas.csv") + deltas.to_csv(deltas_path, index=False) + logger.info("Cross-model deltas -> %s", deltas_path) + non_base = deltas[deltas["condition"] != "plain"] + if not non_base.empty: + print(f"\nCross-model deltas (vs. plain):\n{non_base.to_string(index=False)}") + + # Heatmap + plot_heatmap( + table, + title="Accuracy: Model × Condition × Task", + output_path=Path(plots_dir) / "accuracy_heatmap.png", + ) + + # Per-task cross-model bar charts + plot_cross_model_per_task(all_summaries, plots_dir) + + # Per-task delta charts + plot_cross_model_deltas(deltas, plots_dir) + + # Summary JSON + summary = { + "models": found_models, + "conditions": conditions, + "cross_model_table": ( + table.reset_index().to_dict(orient="records") if not table.empty else [] + ), + "deltas": deltas.to_dict(orient="records") if not deltas.empty else [], + } + summary_path = os.path.join(output_dir, "cross_model_summary.json") + with open(summary_path, "w") as f: + json.dump(summary, f, indent=2, default=str) + logger.info("Summary -> %s", summary_path) + + return summary + + +# ── CLI ────────────────────────────────────────────────────────────────────── + + +def main(): + parser = argparse.ArgumentParser( + description=( + "Compare VLM condition results across all models. " + "Generates unified accuracy tables, delta reports, and plots." + ), + ) + parser.add_argument( + "--eval-base", + required=True, + help="Root of vlm_eval/ directory.", + ) + parser.add_argument( + "--models", + nargs="+", + default=["biomedclip", "llava_med", "medgemma"], + help="Models to compare.", + ) + parser.add_argument( + "--conditions", + nargs="+", + default=["plain", "bbox", "contour", "bbox_contour"], + help="Conditions to compare.", + ) + parser.add_argument( + "--output-dir", + default=None, + help="Output directory. Default: eval_base/cross_model_comparison.", + ) + parser.add_argument( + "--sub-dir", + default="aggregate", + help="Sub-dir within condition dir for summary.json.", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s %(levelname)s %(name)s: %(message)s", + ) + + run_cross_model_comparison( + eval_base=args.eval_base, + models=args.models, + conditions=args.conditions, + output_dir=args.output_dir, + sub_dir=args.sub_dir, + ) + + +if __name__ == "__main__": + main() diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/eval_analysis/__init__.py b/itrialspace/src/itrialspace/evaluation/vlm_eval/eval_analysis/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..780381646170c165291f1f776aebc71c9aeda439 --- /dev/null +++ b/itrialspace/src/itrialspace/evaluation/vlm_eval/eval_analysis/__init__.py @@ -0,0 +1,21 @@ +""" +VLM evaluation analysis suite. + +A reusable engine that turns VLM result CSVs into tables, figures, statistics, and +a markdown report. Auto-discovers whatever models/conditions/tasks are present, so +the same code serves the full released dataset and small demo runs. + +Modules +------- +- ``load`` : discover runs -> one tidy long DataFrame (results joined to metadata) +- ``tables`` : accuracy, Δ-vs-baseline, breakdowns, confusion, per-class +- ``stats`` : bootstrap CIs, McNemar significance +- ``plots`` : bars, deltas, confusion heatmaps, breakdowns +- ``report`` : orchestrate everything -> out/{tables,figures,report.md} + +CLI: ``python -m itrialspace.evaluation.vlm_eval.eval_analysis --results ... --out ...`` +""" + +from itrialspace.evaluation.vlm_eval.eval_analysis import load, plots, stats, tables # noqa: F401 + +__all__ = ["load", "tables", "stats", "plots"] diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/eval_analysis/__main__.py b/itrialspace/src/itrialspace/evaluation/vlm_eval/eval_analysis/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..f78166d3aae872c0286745ac6c18a623341f5f9c --- /dev/null +++ b/itrialspace/src/itrialspace/evaluation/vlm_eval/eval_analysis/__main__.py @@ -0,0 +1,4 @@ +from itrialspace.evaluation.vlm_eval.eval_analysis.report import main + +if __name__ == "__main__": + main() diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/eval_analysis/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/evaluation/vlm_eval/eval_analysis/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..77afd8343e307bb7a93e59e9b2e57088c4a0b5ca Binary files /dev/null and b/itrialspace/src/itrialspace/evaluation/vlm_eval/eval_analysis/__pycache__/__init__.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/eval_analysis/__pycache__/__main__.cpython-310.pyc b/itrialspace/src/itrialspace/evaluation/vlm_eval/eval_analysis/__pycache__/__main__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bad4019fe33fcc4816e6f867ab3f540f71f60c3e Binary files /dev/null and b/itrialspace/src/itrialspace/evaluation/vlm_eval/eval_analysis/__pycache__/__main__.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/eval_analysis/__pycache__/load.cpython-310.pyc b/itrialspace/src/itrialspace/evaluation/vlm_eval/eval_analysis/__pycache__/load.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a0c7b4ba5f7bd5d63f56b376dcc1c60a09380b23 Binary files /dev/null and b/itrialspace/src/itrialspace/evaluation/vlm_eval/eval_analysis/__pycache__/load.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/eval_analysis/__pycache__/plots.cpython-310.pyc b/itrialspace/src/itrialspace/evaluation/vlm_eval/eval_analysis/__pycache__/plots.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..424f64519544caab98c0c57a47d8166ec004e14f Binary files /dev/null and b/itrialspace/src/itrialspace/evaluation/vlm_eval/eval_analysis/__pycache__/plots.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/eval_analysis/__pycache__/report.cpython-310.pyc b/itrialspace/src/itrialspace/evaluation/vlm_eval/eval_analysis/__pycache__/report.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c3d3b816f0f52c77a007a13cab656522d697770b Binary files /dev/null and b/itrialspace/src/itrialspace/evaluation/vlm_eval/eval_analysis/__pycache__/report.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/eval_analysis/__pycache__/stats.cpython-310.pyc b/itrialspace/src/itrialspace/evaluation/vlm_eval/eval_analysis/__pycache__/stats.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ea6e2c48251b430c19b5bceacae567d03d77037 Binary files /dev/null and b/itrialspace/src/itrialspace/evaluation/vlm_eval/eval_analysis/__pycache__/stats.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/eval_analysis/__pycache__/tables.cpython-310.pyc b/itrialspace/src/itrialspace/evaluation/vlm_eval/eval_analysis/__pycache__/tables.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b9d48549e41758425e74edcf9cc4de8d112940e Binary files /dev/null and b/itrialspace/src/itrialspace/evaluation/vlm_eval/eval_analysis/__pycache__/tables.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/eval_analysis/load.py b/itrialspace/src/itrialspace/evaluation/vlm_eval/eval_analysis/load.py new file mode 100644 index 0000000000000000000000000000000000000000..1ebd3bb39abe672af898238fefed2f203f77bcb4 --- /dev/null +++ b/itrialspace/src/itrialspace/evaluation/vlm_eval/eval_analysis/load.py @@ -0,0 +1,199 @@ +""" +Discover VLM result runs and assemble a single tidy long DataFrame. + +The whole analysis suite operates on one normalised table with these columns:: + + set, profile, model, condition, task, uid, + prediction, ground_truth, correct, + mode, source_dataset, lobe, size_bucket, diam_mm, population + +so every table/plot/stat is just a group-by on this frame. The loader +*auto-discovers* whatever is present under the result root(s), so the identical +code path serves the full released dataset and a tiny demo run. + +Result-file convention (written by the runners):: + + //_results.csv # condition in CONDITIONS + +Per-mode and ``aggregate/`` copies are ignored (only the condition-level file is +read), so nothing is double-counted. +""" + +from __future__ import annotations + +import logging +from pathlib import Path +from typing import Dict, Iterable, List, Optional, Union + +import pandas as pd + +from itrialspace.evaluation.vlm_eval.splits import canonical_uid, load_split + +logger = logging.getLogger(__name__) + +CONDITIONS = ("plain", "bbox", "contour", "bbox_contour") +TASKS = ("presence", "lobe", "size") + +PathLike = Union[str, Path] + +# Standard breakdown columns -> candidate source columns in eval_dataset.csv. +_META_MAP = { + "mode": ["mode"], + "source_dataset": ["donor_dataset", "dataset", "dataset_name"], + "lobe": ["ground_truth_lobe", "lobe_name"], + "size_bucket": ["ground_truth_size_bucket"], + "diam_mm": ["effective_diam_mm", "nodule_mean_diam_mm"], + "population": ["population_type"], +} + + +def _truthy(v) -> bool: + return str(v).strip().lower() in ("true", "1", "yes") + + +def discover_result_files(roots: Iterable[PathLike]) -> List[Dict]: + """Find condition-level ``_results.csv`` files under the given roots.""" + records: List[Dict] = [] + seen = set() + for root in roots: + root = Path(root) + for task in TASKS: + for path in root.rglob(f"{task}_results.csv"): + if path.parent.name not in CONDITIONS: + continue # skip per-mode and aggregate/ copies + if path in seen: + continue + seen.add(path) + parts = path.parts + model_dir = path.parent.parent + records.append( + { + "path": path, + "task": task, + "condition": path.parent.name, + "model": model_dir.name, + "profile": next( + (p for p in parts if p in ("lung_axial", "lung_axial_medgemma")), None + ), + "set": next((p for p in parts if p in ("synthetic", "real")), "default"), + "model_dir": model_dir, + } + ) + logger.info("Discovered %d result files under %s", len(records), list(roots)) + return records + + +def _find_eval_csv(model_dir: Path) -> Optional[Path]: + """Locate the eval_dataset.csv that produced a model's results.""" + for cand in (model_dir.parent / "eval_dataset.csv", model_dir / "eval_dataset.csv"): + if cand.is_file(): + return cand + return None + + +def load_metadata(eval_csv: PathLike) -> pd.DataFrame: + """Per-uid metadata frame with standardised breakdown columns.""" + df = pd.read_csv(eval_csv) + path_col = "png_path" if "png_path" in df.columns else "image_path" + out = pd.DataFrame({"uid": df[path_col].astype(str).map(canonical_uid)}) + for std, cands in _META_MAP.items(): + src = next((c for c in cands if c in df.columns), None) + out[std] = df[src].values if src else pd.NA + return out.drop_duplicates("uid").set_index("uid") + + +def load_long( + roots: Union[PathLike, Iterable[PathLike]], + split: Optional[Union[PathLike, Dict[str, str]]] = None, + eval_csvs: Optional[Dict[str, PathLike]] = None, +) -> pd.DataFrame: + """Build the tidy long results frame. + + Parameters + ---------- + roots : path or iterable of paths + Result root(s) to scan (e.g. ``vlm_dataset`` or a demo output dir). + split : path or {set: path}, optional + Frozen split file(s) to restrict to. A single path applies to every set; + a dict maps set name -> split file. + eval_csvs : {set: path}, optional + Explicit eval_dataset.csv per set (overrides auto-discovery). + + Returns + ------- + pd.DataFrame + One row per (model, condition, task, uid). + """ + if isinstance(roots, (str, Path)): + roots = [roots] + records = discover_result_files(roots) + if not records: + raise FileNotFoundError(f"no *_results.csv found under {list(roots)}") + + # Resolve split files per set. + split_ids: Dict[str, set] = {} + if split is not None: + if isinstance(split, dict): + split_ids = {k: load_split(v) for k, v in split.items()} + else: + ids = load_split(split) + split_ids = {r["set"]: ids for r in records} + + # Metadata cache per (set, eval_csv). + meta_cache: Dict[Path, pd.DataFrame] = {} + frames: List[pd.DataFrame] = [] + for rec in records: + df = pd.read_csv(rec["path"]) + col = "image_path" if "image_path" in df.columns else "png_path" + df = df.assign( + uid=df[col].astype(str).map(canonical_uid), + set=rec["set"], + profile=rec["profile"], + model=rec["model"], + condition=rec["condition"], + task=rec["task"], + ) + df["correct"] = ( + df["correct"].map(_truthy) + if "correct" in df.columns + else (df["prediction"].astype(str) == df["ground_truth"].astype(str)) + ) + keep = [ + "uid", + "set", + "profile", + "model", + "condition", + "task", + "prediction", + "ground_truth", + "correct", + ] + df = df[[c for c in keep if c in df.columns]].drop_duplicates("uid") + + if rec["set"] in split_ids: + df = df[df["uid"].isin(split_ids[rec["set"]])] + + # Attach metadata. + eval_csv = None + if eval_csvs and rec["set"] in eval_csvs: + eval_csv = Path(eval_csvs[rec["set"]]) + else: + eval_csv = _find_eval_csv(rec["model_dir"]) + if eval_csv is not None: + if eval_csv not in meta_cache: + meta_cache[eval_csv] = load_metadata(eval_csv) + df = df.join(meta_cache[eval_csv], on="uid") + + frames.append(df) + + long = pd.concat(frames, ignore_index=True) + logger.info( + "Long frame: %d rows | sets=%s models=%s conditions=%s tasks=%s", + len(long), + sorted(long["set"].unique()), + sorted(long["model"].unique()), + sorted(long["condition"].unique()), + sorted(long["task"].unique()), + ) + return long diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/eval_analysis/plots.py b/itrialspace/src/itrialspace/evaluation/vlm_eval/eval_analysis/plots.py new file mode 100644 index 0000000000000000000000000000000000000000..014a9864c58ec8355d92bcecd37564051f6bb5af --- /dev/null +++ b/itrialspace/src/itrialspace/evaluation/vlm_eval/eval_analysis/plots.py @@ -0,0 +1,219 @@ +""" +Figures for the VLM benchmark, drawn from the tidy tables. + +Publication style: top/right spines removed, subplots share the y-axis with tick +labels only on the first panel, sequential **shades of blue** for series. Every +function takes already-aggregated tables (from ``tables.py``) and writes a PNG +(+ PDF), degrading gracefully so demo runs still produce valid (smaller) figures. +""" + +from __future__ import annotations + +from pathlib import Path +from typing import List, Optional + +import matplotlib + +matplotlib.use("Agg") +import matplotlib.pyplot as plt # noqa: E402 +import numpy as np # noqa: E402 +import pandas as pd # noqa: E402 + +# Sequential blues (ColorBrewer), light -> dark. +_BLUES5 = ["#c6dbef", "#9ecae1", "#6baed6", "#3182bd", "#08306b"] +# Conditions in canonical order get progressively darker blues. +_COND_ORDER = ["plain", "bbox", "contour", "bbox_contour"] +_COND_COLORS = { + "plain": "#c6dbef", + "bbox": "#6baed6", + "contour": "#3182bd", + "bbox_contour": "#08306b", +} +_CHANCE = {"presence": 0.5, "lobe": 0.2, "size": 0.25} + +plt.rcParams.update( + { + "axes.spines.top": False, + "axes.spines.right": False, + "font.size": 9, + } +) + + +def _blues(n: int) -> List[str]: + """n evenly-spaced shades of blue.""" + if n <= 1: + return ["#3182bd"] + import matplotlib.cm as cm + + return [matplotlib.colors.to_hex(cm.Blues(x)) for x in np.linspace(0.35, 0.92, n)] + + +def _despine(ax) -> None: + ax.spines["top"].set_visible(False) + ax.spines["right"].set_visible(False) + + +def _order_conditions(conds) -> List[str]: + present = list(conds) + return [c for c in _COND_ORDER if c in present] + [c for c in present if c not in _COND_ORDER] + + +def _save(fig, out_path: Path) -> Path: + out_path = Path(out_path) + out_path.parent.mkdir(parents=True, exist_ok=True) + fig.savefig(out_path, dpi=300, bbox_inches="tight") + fig.savefig(out_path.with_suffix(".pdf"), bbox_inches="tight") + plt.close(fig) + return out_path + + +def bar_accuracy_by_condition(acc: pd.DataFrame, set_name: str, out_path: Path) -> Optional[Path]: + """Per-model subplot; x = tasks, bars = conditions (shared y; labels on first).""" + sub = acc[acc["set"] == set_name] + if sub.empty: + return None + models = sorted(sub["model"].unique()) + tasks = sorted(sub["task"].unique()) + conds = _order_conditions(sub["condition"].unique()) + fig, axes = plt.subplots( + 1, len(models), figsize=(3.6 * len(models), 3.6), squeeze=False, sharey=True + ) + for ax_i, (ax, model) in enumerate(zip(axes[0], models)): + msub = sub[sub["model"] == model] + x = np.arange(len(tasks)) + w = 0.8 / max(len(conds), 1) + for i, c in enumerate(conds): + vals = [ + msub[(msub["task"] == t) & (msub["condition"] == c)]["accuracy"].mean() + for t in tasks + ] + ax.bar(x + i * w, vals, w, label=c, color=_COND_COLORS.get(c, _blues(len(conds))[i])) + ax.set_xticks(x + w * (len(conds) - 1) / 2) + ax.set_xticklabels(tasks) + ax.set_ylim(0, 1.0) + ax.set_title(model) + _despine(ax) + if ax_i == 0: + ax.set_ylabel("accuracy") + else: + ax.tick_params(labelleft=False) + axes[0][-1].legend(frameon=False, fontsize=7, title="condition") + fig.suptitle(f"{set_name}: accuracy by task × condition") + fig.tight_layout() + return _save(fig, out_path) + + +def bar_delta_vs_baseline( + delta: pd.DataFrame, set_name: str, baseline: str, out_path: Path +) -> Optional[Path]: + col = f"delta_vs_{baseline}" + sub = delta[(delta["set"] == set_name) & (delta["condition"] != baseline)] + if sub.empty or col not in sub.columns: + return None + models = sorted(sub["model"].unique()) + tasks = sorted(sub["task"].unique()) + conds = _order_conditions(sub["condition"].unique()) + fig, axes = plt.subplots( + 1, len(models), figsize=(3.6 * len(models), 3.6), squeeze=False, sharey=True + ) + for ax_i, (ax, model) in enumerate(zip(axes[0], models)): + msub = sub[sub["model"] == model] + x = np.arange(len(tasks)) + w = 0.8 / max(len(conds), 1) + for i, c in enumerate(conds): + vals = [msub[(msub["task"] == t) & (msub["condition"] == c)][col].mean() for t in tasks] + ax.bar(x + i * w, vals, w, label=c, color=_COND_COLORS.get(c, _blues(len(conds))[i])) + ax.axhline(0, color="0.4", lw=0.8) + ax.set_xticks(x + w * (len(conds) - 1) / 2) + ax.set_xticklabels(tasks) + ax.set_title(model) + _despine(ax) + if ax_i == 0: + ax.set_ylabel(f"Δ accuracy vs {baseline}") + else: + ax.tick_params(labelleft=False) + axes[0][-1].legend(frameon=False, fontsize=7, title="condition") + fig.suptitle(f"{set_name}: Δ accuracy vs {baseline}") + fig.tight_layout() + return _save(fig, out_path) + + +def heatmap_confusion( + conf_long: pd.DataFrame, set_name: str, model: str, condition: str, task: str, out_path: Path +) -> Optional[Path]: + sub = conf_long[ + (conf_long["set"] == set_name) + & (conf_long["model"] == model) + & (conf_long["condition"] == condition) + & (conf_long["task"] == task) + ] + if sub.empty: + return None + mat = sub.pivot_table( + index="ground_truth", columns="prediction", values="count", aggfunc="sum", fill_value=0 + ) + labels = sorted(set(mat.index) | set(mat.columns)) + mat = mat.reindex(index=labels, columns=labels, fill_value=0) + norm = mat.div(mat.sum(axis=1).replace(0, 1), axis=0) + fig, ax = plt.subplots(figsize=(1.1 * len(labels) + 2, 1.1 * len(labels) + 1)) + im = ax.imshow(norm.values, cmap="Blues", vmin=0, vmax=1) + ax.set_xticks(range(len(labels))) + ax.set_yticks(range(len(labels))) + ax.set_xticklabels(labels, rotation=45, ha="right", fontsize=7) + ax.set_yticklabels(labels, fontsize=7) + for i in range(len(labels)): + for j in range(len(labels)): + ax.text( + j, + i, + f"{int(mat.values[i, j])}", + ha="center", + va="center", + fontsize=6, + color="black" if norm.values[i, j] < 0.5 else "white", + ) + ax.set_xlabel("prediction") + ax.set_ylabel("ground truth") + ax.set_title(f"{set_name} {model} {task} ({condition})", fontsize=9) + for s in ax.spines.values(): + s.set_visible(False) + fig.colorbar(im, ax=ax, fraction=0.046, pad=0.04) + return _save(fig, out_path) + + +def bar_breakdown( + bd: pd.DataFrame, set_name: str, task: str, condition: str, out_path: Path +) -> Optional[Path]: + """Accuracy across a breakdown's group values; bars grouped by model (blue shades).""" + sub = bd[(bd["set"] == set_name) & (bd["task"] == task) & (bd["condition"] == condition)] + if sub.empty: + return None + by = sub["group_by"].iloc[0] + groups = sorted(sub["group_value"].astype(str).unique()) + models = sorted(sub["model"].unique()) + colors = _blues(len(models)) + x = np.arange(len(groups)) + w = 0.8 / max(len(models), 1) + fig, ax = plt.subplots(figsize=(max(6, 0.5 * len(groups) + 2), 3.8)) + for i, model in enumerate(models): + msub = sub[sub["model"] == model].copy() + msub.index = msub["group_value"].astype(str) + vals = [float(msub.loc[g, "accuracy"]) if g in msub.index else np.nan for g in groups] + ax.bar(x + i * w, vals, w, label=model, color=colors[i]) + ax.axhline( + _CHANCE.get(task, 0), + color="0.5", + ls=":", + lw=0.8, + label=f"chance ({_CHANCE.get(task, 0):.0%})", + ) + ax.set_xticks(x + w * (len(models) - 1) / 2) + ax.set_xticklabels(groups, rotation=45, ha="right", fontsize=7) + ax.set_ylim(0, 1.0) + ax.set_ylabel("accuracy") + ax.set_title(f"{set_name}: {task} accuracy by {by} ({condition})") + _despine(ax) + ax.legend(frameon=False, fontsize=7) + fig.tight_layout() + return _save(fig, out_path) diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/eval_analysis/report.py b/itrialspace/src/itrialspace/evaluation/vlm_eval/eval_analysis/report.py new file mode 100644 index 0000000000000000000000000000000000000000..8cc9140230b856c3391ee297c030cee15f61f66f --- /dev/null +++ b/itrialspace/src/itrialspace/evaluation/vlm_eval/eval_analysis/report.py @@ -0,0 +1,222 @@ +""" +Orchestrate the full VLM analysis: one call -> tables/ + figures/ + report.md. + + python -m itrialspace.evaluation.vlm_eval.eval_analysis \\ + --results $ITRIALSPACE_DATA_DIR/vlm_dataset \\ + --split release_v1_full \\ + --out analysis_full/ + +Everything is auto-discovered, so the same command analyses the full dataset or a +small demo run (just point ``--results`` at the demo output dir and omit +``--split``). +""" + +from __future__ import annotations + +import argparse +import logging +from datetime import date +from pathlib import Path +from typing import Dict, List, Optional + +import pandas as pd + +from itrialspace.evaluation.vlm_eval.eval_analysis import load, plots, stats, tables + +logger = logging.getLogger(__name__) + +_BREAKDOWNS = ["mode", "source_dataset", "lobe", "size_bucket"] +# (by, task) pairs rendered as figures; CSV always holds every condition. +_BREAKDOWN_FIGS = [ + ("source_dataset", "presence"), + ("source_dataset", "lobe"), + ("source_dataset", "size"), + ("size_bucket", "size"), + ("lobe", "lobe"), + ("mode", "presence"), +] +_CONF_TASKS = ["lobe", "size"] + + +def _resolve_split(results: List[str], split: Optional[str]) -> Optional[Dict[str, str]]: + """Map a split *name* to per-set files under /splits, if present.""" + if not split: + return None + if Path(split).is_file(): + return split # explicit file -> applied to all sets + for root in results: + sd = Path(root) / "splits" + cand = {s: sd / f"{split}.{s}.txt" for s in ("synthetic", "real")} + found = {s: str(p) for s, p in cand.items() if p.is_file()} + if found: + return found + logger.warning("Split %r not found under any results/splits; using all cases.", split) + return None + + +def run( + results: List[str], + out: str, + split: Optional[str] = None, + n_boot: int = 1000, + baseline: str = "plain", +) -> None: + out_dir = Path(out) + tdir, fdir = out_dir / "tables", out_dir / "figures" + tdir.mkdir(parents=True, exist_ok=True) + fdir.mkdir(parents=True, exist_ok=True) + + split_arg = _resolve_split(results, split) + long = load.load_long(results, split=split_arg) + long.to_parquet(tdir / "long_results.parquet") if _has_parquet() else None + + sets = sorted(long["set"].unique()) + ns = {s: int(long[long["set"] == s]["uid"].nunique()) for s in sets} + conds_present = [c for c in load.CONDITIONS if c in long["condition"].unique()] + + # ── tables ──────────────────────────────────────────────────────────────── + acc = tables.accuracy_table(long) + acc.to_csv(tdir / "accuracy.csv", index=False) + delta = tables.delta_table(long, baseline=baseline) + delta.to_csv(tdir / "deltas.csv", index=False) + tables.confusion_long(long).to_csv(tdir / "confusion.csv", index=False) + tables.per_class_accuracy(long).to_csv(tdir / "per_class_accuracy.csv", index=False) + + bd_all = [] + for by in _BREAKDOWNS: + bd = tables.breakdown_table(long, by) + if not bd.empty: + bd_all.append(bd) + breakdowns = pd.concat(bd_all, ignore_index=True) if bd_all else pd.DataFrame() + if not breakdowns.empty: + breakdowns.to_csv(tdir / "breakdowns.csv", index=False) + + # ── stats ───────────────────────────────────────────────────────────────-- + ci = stats.bootstrap_ci(long, n_boot=n_boot) + ci.to_csv(tdir / "bootstrap_ci.csv", index=False) + mc = stats.mcnemar_vs_baseline(long, baseline=baseline) + if not mc.empty: + mc.to_csv(tdir / "mcnemar_vs_baseline.csv", index=False) + + # ── figures ─────────────────────────────────────────────────────────────── + fig_index: List[str] = [] + + def _log(p): + if p: + fig_index.append(str(Path(p).relative_to(out_dir))) + + for s in sets: + _log(plots.bar_accuracy_by_condition(acc, s, fdir / f"accuracy_by_condition_{s}.png")) + _log(plots.bar_delta_vs_baseline(delta, s, baseline, fdir / f"delta_vs_{baseline}_{s}.png")) + if not breakdowns.empty: + for by, task in _BREAKDOWN_FIGS: + sl = breakdowns[(breakdowns["group_by"] == by) & (breakdowns["set"] == s)] + if sl.empty or task not in sl["task"].unique(): + continue + _log( + plots.bar_breakdown( + breakdowns, s, task, baseline, fdir / f"breakdown_{by}_{task}_{s}.png" + ) + ) + conf = tables.confusion_long(long) + for model in sorted(long[long["set"] == s]["model"].unique()): + for task in _CONF_TASKS: + if task not in long["task"].unique(): + continue + _log( + plots.heatmap_confusion( + conf, + s, + model, + baseline, + task, + fdir / f"confusion_{s}_{model}_{task}_{baseline}.png", + ) + ) + + # ── report.md ───────────────────────────────────────────────────────────-- + _write_markdown(out_dir, split, baseline, sets, ns, conds_present, acc, mc, fig_index, n_boot) + print(f"[eval_analysis] wrote {out_dir}/report.md (+ tables/ + {len(fig_index)} figures)") + + +def _write_markdown(out_dir, split, baseline, sets, ns, conds, acc, mc, fig_index, n_boot): + L = [ + "# VLM evaluation analysis", + "", + f"> Generated {date.today().isoformat()}" + + (f" · split `{split}`" if split else " · all available cases") + + f" · baseline `{baseline}`.", + "", + "Every number is computed on the same fixed cases per set (one N), keyed by the canonical " + "slice uid. Accuracy = mean(`prediction == ground_truth`).", + "", + "**Cases:** " + " · ".join(f"{s} N={ns[s]:,}" for s in sets), + "Chance: presence 50% · lobe 20% · size 25%.", + "", + ] + for s in sets: + L += [ + f"## {s.capitalize()} (N = {ns[s]:,})", + "", + tables.accuracy_markdown(acc, s, conds), + "", + f"![accuracy](figures/accuracy_by_condition_{s}.png)", + f"![delta](figures/delta_vs_{baseline}_{s}.png)", + "", + ] + + if mc is not None and not mc.empty: + sig = mc[mc.get("significant_0.05", False)] + L += [ + "## Significance (McNemar vs baseline)", + "", + f"{len(sig)}/{len(mc)} condition effects significant at p<0.05. " + "Largest accuracy gains (paired):", + "", + ] + top = mc.sort_values("acc_delta", ascending=False).head(8) + L += ["| set | model | task | condition | Δacc | p |", "|---|---|---|---|---:|---:|"] + for _, r in top.iterrows(): + L.append( + f"| {r['set']} | {r['model']} | {r['task']} | {r['condition']} " + f"| {r['acc_delta']*100:+.1f} | {r['p_value']:.1e} |" + ) + L.append("") + + L += ["## All figures", ""] + [f"- `{p}`" for p in fig_index] + [""] + L += [ + "## Outputs", + "", + "- `tables/` — accuracy, deltas, breakdowns, confusion, per_class, bootstrap_ci, mcnemar (CSV)", + "- `figures/` — PNG + PDF", + f"- Bootstrap: {n_boot} resamples (`tables/bootstrap_ci.csv`).", + "", + ] + (out_dir / "report.md").write_text("\n".join([x for x in L if x is not None])) + + +def _has_parquet() -> bool: + try: + import pyarrow # noqa: F401 + + return True + except Exception: + return False + + +def main(): + ap = argparse.ArgumentParser(description="Full VLM evaluation analysis suite.") + ap.add_argument("--results", nargs="+", required=True, help="Result root(s) to analyse.") + ap.add_argument("--out", required=True, help="Output directory.") + ap.add_argument( + "--split", default=None, help="Split name (under results/splits) or a file path." + ) + ap.add_argument("--n-boot", type=int, default=1000, help="Bootstrap resamples (0 to skip).") + ap.add_argument("--baseline", default="plain", help="Baseline condition for deltas/McNemar.") + args = ap.parse_args() + logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s") + run(args.results, args.out, split=args.split, n_boot=args.n_boot, baseline=args.baseline) + + +if __name__ == "__main__": + main() diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/eval_analysis/stats.py b/itrialspace/src/itrialspace/evaluation/vlm_eval/eval_analysis/stats.py new file mode 100644 index 0000000000000000000000000000000000000000..e13a1709acc91e721ab090a737b968d3bb61b33e --- /dev/null +++ b/itrialspace/src/itrialspace/evaluation/vlm_eval/eval_analysis/stats.py @@ -0,0 +1,104 @@ +""" +Uncertainty and significance for the VLM benchmark. + +- ``bootstrap_ci``: case-resampled confidence interval on accuracy per + set x model x task x condition. +- ``mcnemar_vs_baseline``: paired McNemar test of each condition against the + baseline (``plain``) on the cases both scored -- the right test for "did the + overlay change accuracy?" because the same cases are compared. +""" + +from __future__ import annotations + +from typing import List + +import numpy as np +import pandas as pd + +_GROUP = ["set", "model", "task", "condition"] + + +def bootstrap_ci( + long: pd.DataFrame, + n_boot: int = 1000, + alpha: float = 0.05, + seed: int = 0, +) -> pd.DataFrame: + """Percentile bootstrap CI on accuracy per set x model x task x condition.""" + rng = np.random.default_rng(seed) + rows: List[dict] = [] + for keys, grp in long.groupby(_GROUP, dropna=False): + c = grp["correct"].to_numpy(dtype=float) + n = len(c) + if n == 0: + continue + acc = float(c.mean()) + if n_boot > 0: + idx = rng.integers(0, n, size=(n_boot, n)) + boot = c[idx].mean(axis=1) + lo, hi = np.percentile(boot, [100 * alpha / 2, 100 * (1 - alpha / 2)]) + else: + lo = hi = acc + rows.append( + dict(zip(_GROUP, keys)) + | { + "accuracy": round(acc, 4), + "ci_low": round(float(lo), 4), + "ci_high": round(float(hi), 4), + "n": n, + } + ) + return pd.DataFrame(rows) + + +def _mcnemar(b: int, c: int) -> float: + """Two-sided McNemar p-value (exact binomial for small discordant counts).""" + n = b + c + if n == 0: + return 1.0 + if n < 25: + from math import comb + + k = min(b, c) + tail = sum(comb(n, i) for i in range(0, k + 1)) * (0.5**n) + return min(1.0, 2 * tail) + # chi-square with continuity correction + from math import erfc, sqrt + + chi = (abs(b - c) - 1) ** 2 / n + return erfc(sqrt(chi / 2)) # survival of chi2_1 == erfc(sqrt(x/2)) + + +def mcnemar_vs_baseline(long: pd.DataFrame, baseline: str = "plain") -> pd.DataFrame: + """Paired McNemar test of each condition vs the baseline, per set x model x task.""" + rows: List[dict] = [] + for (s, m, t), grp in long.groupby(["set", "model", "task"], dropna=False): + base = grp[grp["condition"] == baseline].set_index("uid")["correct"] + if base.empty: + continue + for cond, cg in grp.groupby("condition"): + if cond == baseline: + continue + cur = cg.set_index("uid")["correct"] + common = base.index.intersection(cur.index) + if len(common) == 0: + continue + b = int((base.loc[common] & ~cur.loc[common]).sum()) # base right, cond wrong + c = int((~base.loc[common] & cur.loc[common]).sum()) # base wrong, cond right + rows.append( + { + "set": s, + "model": m, + "task": t, + "condition": cond, + "n_paired": len(common), + "base_only_correct": b, + "cond_only_correct": c, + "acc_delta": round(float(cur.loc[common].mean() - base.loc[common].mean()), 4), + "p_value": round(_mcnemar(b, c), 6), + } + ) + out = pd.DataFrame(rows) + if not out.empty: + out["significant_0.05"] = out["p_value"] < 0.05 + return out diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/eval_analysis/tables.py b/itrialspace/src/itrialspace/evaluation/vlm_eval/eval_analysis/tables.py new file mode 100644 index 0000000000000000000000000000000000000000..0a28187ac785268dd24fae6716919a46d9fc7cdc --- /dev/null +++ b/itrialspace/src/itrialspace/evaluation/vlm_eval/eval_analysis/tables.py @@ -0,0 +1,102 @@ +""" +Tables from the tidy long results frame (see ``load.load_long``). + +Every function returns a tidy ``pd.DataFrame`` and is a pure group-by, so the +same code serves the full dataset and a demo run. ``accuracy`` is +``mean(correct)``; ``n`` is the case count behind each cell. +""" + +from __future__ import annotations + +from typing import List, Optional + +import pandas as pd + +_GROUP = ["set", "model", "task", "condition"] + + +def _acc(df: pd.DataFrame, group: List[str]) -> pd.DataFrame: + g = df.groupby(group, dropna=False)["correct"] + out = g.agg(accuracy="mean", n="size", n_correct="sum").reset_index() + out["accuracy"] = out["accuracy"].astype(float).round(4) + out["n_correct"] = out["n_correct"].astype(int) + return out + + +def accuracy_table(long: pd.DataFrame) -> pd.DataFrame: + """Accuracy per set x model x task x condition.""" + return _acc(long, _GROUP) + + +def delta_table(long: pd.DataFrame, baseline: str = "plain") -> pd.DataFrame: + """Accuracy and Δ-vs-baseline per condition.""" + acc = accuracy_table(long) + base = ( + acc[acc["condition"] == baseline] + .set_index(["set", "model", "task"])["accuracy"] + .rename("baseline_accuracy") + ) + out = acc.join(base, on=["set", "model", "task"]) + out["delta_vs_" + baseline] = (out["accuracy"] - out["baseline_accuracy"]).round(4) + return out + + +def breakdown_table(long: pd.DataFrame, by: str) -> pd.DataFrame: + """Accuracy broken down by a metadata column (mode / source_dataset / lobe / size_bucket). + + Rows with a missing value for ``by`` are dropped (e.g. ``mode`` is empty for + the real set). + """ + if by not in long.columns: + return pd.DataFrame() + sub = long[long[by].notna()].copy() + if sub.empty: + return pd.DataFrame() + return _acc(sub, _GROUP + [by]).rename(columns={by: "group_value"}).assign(group_by=by) + + +def confusion_long(long: pd.DataFrame) -> pd.DataFrame: + """Confusion counts per set x model x condition x task (ground_truth x prediction).""" + g = ( + long.groupby( + ["set", "model", "condition", "task", "ground_truth", "prediction"], + dropna=False, + ) + .size() + .reset_index(name="count") + ) + return g + + +def per_class_accuracy(long: pd.DataFrame) -> pd.DataFrame: + """Recall per ground-truth class (set x model x condition x task x class).""" + g = long.groupby(["set", "model", "condition", "task", "ground_truth"], dropna=False)["correct"] + out = g.agg(accuracy="mean", n="size", n_correct="sum").reset_index() + out = out.rename(columns={"ground_truth": "class"}) + out["accuracy"] = out["accuracy"].astype(float).round(4) + out["n_correct"] = out["n_correct"].astype(int) + return out + + +# ── Markdown rendering ──────────────────────────────────────────────────────── + + +def accuracy_markdown( + acc: pd.DataFrame, set_name: str, conditions: Optional[List[str]] = None +) -> str: + """Render a model x task table (conditions as columns) for one set.""" + sub = acc[acc["set"] == set_name] + if sub.empty: + return "" + conds = conditions or sorted(sub["condition"].unique()) + pivot = sub.pivot_table(index=["model", "task"], columns="condition", values="accuracy") + header = "| Model | Task | " + " | ".join(conds) + " | best |" + sep = "|---|---|" + "---:|" * len(conds) + "---|" + lines = [header, sep] + for (model, task), row in pivot.iterrows(): + vals = {c: row.get(c) for c in conds} + cells = [f"{vals[c]*100:.1f}" if pd.notna(vals[c]) else "–" for c in conds] + numeric = {c: v for c, v in vals.items() if pd.notna(v)} + best = max(numeric, key=numeric.get) if numeric else "–" + lines.append(f"| {model} | {task} | " + " | ".join(cells) + f" | {best} |") + return "\n".join(lines) diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/inference_cache.py b/itrialspace/src/itrialspace/evaluation/vlm_eval/inference_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..6daeb077cfe7611fe0a2998ea0da84d0ea061b82 --- /dev/null +++ b/itrialspace/src/itrialspace/evaluation/vlm_eval/inference_cache.py @@ -0,0 +1,102 @@ +"""Shared skip-existing logic for VLM inference runners. + +When ``--skip-existing`` is enabled, each ``run_task`` call checks whether a +results CSV from a previous run already exists. Rows whose ``(case_id, +image_path)`` pair matches an entry in the current eval dataset are reused; +only genuinely new or changed rows are sent through the model. +""" + +from __future__ import annotations + +import logging +import os +from typing import Optional, Tuple + +import pandas as pd + +logger = logging.getLogger(__name__) + + +def load_cached_results( + output_dir: str, + task_name: str, + current_df: pd.DataFrame, +) -> Tuple[Optional[pd.DataFrame], pd.DataFrame]: + """Load cached inference results and partition the dataset. + + Parameters + ---------- + output_dir : str + Directory containing ``{task_name}_results.csv`` from a prior run. + task_name : str + Task name (``presence``, ``lobe``, ``size``). + current_df : pd.DataFrame + Current eval dataset (already condition-remapped by run_conditions). + + Returns + ------- + (cached_df, todo_df) + *cached_df*: rows from the existing results that are still valid + (``None`` if no cache file found). + *todo_df*: rows from *current_df* that need fresh inference. + """ + csv_path = os.path.join(output_dir, f"{task_name}_results.csv") + + if not os.path.isfile(csv_path): + logger.info("skip-existing: no cached results for task '%s'", task_name) + return None, current_df + + existing = pd.read_csv(csv_path) + if existing.empty: + return None, current_df + + # Build lookup of (case_id, image_path) from the cached results + cached_keys = set( + zip( + existing["case_id"].astype(str), + existing["image_path"].astype(str), + ) + ) + + # Determine which rows in the current dataset already have results + current_keys = list( + zip( + current_df["case_id"].astype(str), + current_df["png_path"].astype(str), + ) + ) + is_cached = pd.Series([k in cached_keys for k in current_keys], index=current_df.index) + todo_df = current_df[~is_cached] + + # Retain only cached rows whose key is still in the current dataset + current_key_set = set(current_keys) + existing_keys = list( + zip( + existing["case_id"].astype(str), + existing["image_path"].astype(str), + ) + ) + valid_mask = pd.Series([k in current_key_set for k in existing_keys]) + cached_df = existing[valid_mask.values].copy() + + n_reuse = len(cached_df) + n_todo = len(todo_df) + logger.info( + "skip-existing [%s]: reusing %d cached, %d to infer (%d total)", + task_name, + n_reuse, + n_todo, + len(current_df), + ) + + return cached_df, todo_df + + +def merge_results( + cached_df: Optional[pd.DataFrame], + new_df: pd.DataFrame, +) -> pd.DataFrame: + """Merge cached rows with freshly inferred rows.""" + if cached_df is not None and not cached_df.empty: + return pd.concat([cached_df, new_df], ignore_index=True) + return new_df diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/make_split.py b/itrialspace/src/itrialspace/evaluation/vlm_eval/make_split.py new file mode 100644 index 0000000000000000000000000000000000000000..7071fb66614e1f7da7a2ecbb626a11e3b7106332 --- /dev/null +++ b/itrialspace/src/itrialspace/evaluation/vlm_eval/make_split.py @@ -0,0 +1,144 @@ +""" +Generate a frozen, checksummed evaluation split from result CSVs. + +Computes the canonical-uid intersection across the chosen per-model/condition/task +result CSVs (the reporting-N convention) and writes:: + + /..txt # sorted canonical uids, one per line + /splits.json # manifest: per split -> {n, sha256, source, ...} + +The split is reproducible and verifiable: anyone can re-run this tool over the +released results and confirm the ``sha256`` in ``splits.json`` matches. + +Examples +-------- +# release_v1 (plain scope) for the synthetic set: cases scored by every model on +# the plain condition, all 3 tasks. +python -m itrialspace.evaluation.vlm_eval.make_split \\ + --name release_v1 --set synthetic \\ + --out-dir $ITRIALSPACE_DATA_DIR/vlm_dataset/splits \\ + --results-glob \\ + "$ITRIALSPACE_DATA_DIR/vlm_dataset/synthetic/lung_axial/biomedclip/plain/*_results.csv" \\ + "$ITRIALSPACE_DATA_DIR/vlm_dataset/synthetic/lung_axial/llava_med/plain/*_results.csv" \\ + "$ITRIALSPACE_DATA_DIR/vlm_dataset/synthetic/lung_axial_medgemma/medgemma/plain/*_results.csv" \\ + --description "Cases scored by all 3 models on plain, all 3 tasks." + +# release_v1_full: strict intersection across all 4 conditions too (use */*_results.csv). +""" + +from __future__ import annotations + +import argparse +import glob +import json +import logging +import subprocess +from datetime import datetime, timezone +from pathlib import Path +from typing import List, Optional + +import pandas as pd + +from itrialspace.evaluation.vlm_eval.splits import canonical_uid, write_split + +logger = logging.getLogger(__name__) + + +def _git_commit(start: Path) -> Optional[str]: + try: + out = subprocess.run( + ["git", "-C", str(start), "rev-parse", "--short", "HEAD"], + capture_output=True, + text=True, + timeout=5, + ) + return out.stdout.strip() or None + except Exception: + return None + + +def _uids_in_csv(path: str) -> set: + """Canonical uids present in one result CSV (uses image_path / png_path).""" + df = pd.read_csv(path) + col = "image_path" if "image_path" in df.columns else "png_path" + return set(df[col].astype(str).map(canonical_uid)) + + +def build_split(result_globs: List[str]) -> set: + """Intersection of canonical uids across every CSV matched by the globs.""" + files: List[str] = [] + for g in result_globs: + files.extend(glob.glob(g)) + files = sorted(set(files)) + if not files: + raise FileNotFoundError(f"no result CSVs matched: {result_globs}") + logger.info("Intersecting %d result CSVs", len(files)) + common: Optional[set] = None + for f in files: + ids = _uids_in_csv(f) + common = ids if common is None else (common & ids) + logger.debug(" %-70s n=%d running∩=%d", f, len(ids), len(common)) + return common or set() + + +def make_split( + name: str, + set_name: str, + out_dir: str, + result_globs: List[str], + description: str = "", +) -> dict: + out = Path(out_dir) + ids = build_split(result_globs) + txt = out / f"{name}.{set_name}.txt" + meta = write_split(ids, txt) + + entry = { + **meta, + "set": set_name, + "file": txt.name, + "source_globs": result_globs, + "description": description, + "created_at": datetime.now(timezone.utc).isoformat(timespec="seconds"), + "git_commit": _git_commit(Path(__file__).resolve().parent), + } + + manifest_path = out / "splits.json" + manifest = {} + if manifest_path.is_file(): + manifest = json.loads(manifest_path.read_text()) + manifest.setdefault(name, {})[set_name] = entry + manifest_path.write_text(json.dumps(manifest, indent=2) + "\n") + + print(f"[make_split] {name}.{set_name}: N={meta['n']} sha256={meta['sha256'][:16]}…") + print(f" split -> {txt}") + print(f" manifest -> {manifest_path}") + return entry + + +def main(): + ap = argparse.ArgumentParser(description="Generate a frozen evaluation split.") + ap.add_argument("--name", required=True, help="Split name, e.g. release_v1.") + ap.add_argument("--set", dest="set_name", required=True, help="synthetic | real.") + ap.add_argument("--out-dir", required=True, help="Splits directory (vlm_dataset/splits).") + ap.add_argument( + "--results-glob", + nargs="+", + required=True, + help="One or more quoted globs matching the result CSVs to intersect.", + ) + ap.add_argument("--description", default="", help="Human-readable provenance note.") + args = ap.parse_args() + + logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s") + make_split( + name=args.name, + set_name=args.set_name, + out_dir=args.out_dir, + result_globs=args.results_glob, + description=args.description, + ) + + +if __name__ == "__main__": + main() diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/metrics.py b/itrialspace/src/itrialspace/evaluation/vlm_eval/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..a5b36f20d81ec1ec33ec66f852baf6471db2f360 --- /dev/null +++ b/itrialspace/src/itrialspace/evaluation/vlm_eval/metrics.py @@ -0,0 +1,150 @@ +""" +Evaluation metrics for VLM tasks. + +Computes accuracy, precision, recall, F1, and confusion matrices. + +Reporting convention (evaluation N) +----------------------------------- +Accuracy is reported on the set of cases that have a completed prediction in +*every* (task x condition x model), so all reported numbers share one N -- the +same cases are scored for presence, lobe, and size. Use ``common_case_ids()`` to +take that intersection before aggregating. + +For the released dataset this equals the full case count (42,858 synthetic / +13,087 real): every ``eval_dataset.csv`` row is complete for all three tasks. The +original paper reported a smaller synthetic N (42,382) under the *same* rule, +because at analysis time 334 mode-13 cases had slices extracted but inference not +yet run and were excluded to keep N consistent. See +``docs/vlm_eval.md`` (section "Reporting convention") and +``docs/dataset_card.md`` for the full reconciliation. +""" + +from __future__ import annotations + +from typing import Any, Dict, Iterable, List, Optional, Set + +import pandas as pd +from sklearn.metrics import ( + accuracy_score, + confusion_matrix, + f1_score, + precision_score, + recall_score, +) + + +def common_case_ids( + frames: Iterable[pd.DataFrame], + use_canonical: bool = True, + id_col: str = "case_id", +) -> Set[str]: + """Intersection of case ids across result frames -- the reporting N. + + Enforces the evaluation-N convention (see module docstring): given one result + DataFrame per (task x condition x model) you want to compare, return the set + of cases present in *all* of them. Aggregate accuracy only over these cases so + every reported table shares the same N, instead of silently averaging a + different case set per task. + + By default the case identity is the **canonical uid** derived from the slice + path (``splits.canonical_uid``) -- the ``case_id`` column is a non-unique + positional index and must not be used as a key. Pass ``use_canonical=False`` + only if you have a genuinely unique ``id_col``. + + Parameters + ---------- + frames : iterable of pd.DataFrame + Result frames (each with a slice-path column, or ``id_col``). + use_canonical : bool + Key on the canonical uid from the slice path (default, correct). + id_col : str + Fallback identifier column when ``use_canonical`` is False. + + Returns + ------- + set of str + Cases scored in every frame. Empty set if no frames are given. + """ + from itrialspace.evaluation.vlm_eval.splits import uid_series + + common: Optional[Set[str]] = None + for df in frames: + if use_canonical: + ids = set(uid_series(df)) + else: + if id_col not in df.columns: + raise KeyError(f"frame is missing the id column {id_col!r}") + ids = set(df[id_col].astype(str)) + common = ids if common is None else (common & ids) + return common or set() + + +def compute_binary_metrics( + y_true: List[str], + y_pred: List[str], + positive_label: str = "present", +) -> Dict[str, Any]: + """Compute binary classification metrics for the presence task.""" + acc = accuracy_score(y_true, y_pred) + prec = precision_score(y_true, y_pred, pos_label=positive_label, zero_division=0) + rec = recall_score(y_true, y_pred, pos_label=positive_label, zero_division=0) + f1 = f1_score(y_true, y_pred, pos_label=positive_label, zero_division=0) + cm = confusion_matrix(y_true, y_pred, labels=[positive_label, "absent"]) + + return { + "accuracy": float(acc), + "precision": float(prec), + "recall": float(rec), + "f1": float(f1), + "confusion_matrix": cm.tolist(), + "n_samples": len(y_true), + } + + +def compute_multiclass_metrics( + y_true: List[str], + y_pred: List[str], + labels: Optional[List[str]] = None, +) -> Dict[str, Any]: + """Compute multiclass metrics (accuracy + confusion matrix).""" + if labels is None: + labels = sorted(set(y_true) | set(y_pred)) + + acc = accuracy_score(y_true, y_pred) + cm = confusion_matrix(y_true, y_pred, labels=labels) + + # Per-class accuracy + per_class = {} + for i, lbl in enumerate(labels): + mask = [t == lbl for t in y_true] + if sum(mask) > 0: + class_preds = [p for p, m in zip(y_pred, mask) if m] + class_acc = sum(1 for p in class_preds if p == lbl) / len(class_preds) + per_class[lbl] = {"accuracy": float(class_acc), "n_samples": sum(mask)} + + return { + "accuracy": float(acc), + "confusion_matrix": cm.tolist(), + "labels": labels, + "per_class": per_class, + "n_samples": len(y_true), + } + + +def compute_grouped_accuracy( + df: pd.DataFrame, + pred_col: str, + gt_col: str, + group_col: str, +) -> Dict[str, Dict[str, Any]]: + """Compute accuracy grouped by a categorical column.""" + result = {} + for group_val, grp in df.groupby(group_col): + correct = (grp[pred_col] == grp[gt_col]).sum() + total = len(grp) + result[str(group_val)] = { + "accuracy": float(correct / total) if total > 0 else 0.0, + "n_samples": int(total), + "n_correct": int(correct), + } + return result diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/models/__init__.py b/itrialspace/src/itrialspace/evaluation/vlm_eval/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/models/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/evaluation/vlm_eval/models/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..532e6595b56e37873203357bb1d9a148e8474f8b Binary files /dev/null and b/itrialspace/src/itrialspace/evaluation/vlm_eval/models/__pycache__/__init__.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/models/__pycache__/llava_med.cpython-310.pyc b/itrialspace/src/itrialspace/evaluation/vlm_eval/models/__pycache__/llava_med.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c55e7022ee58b65c2c8b693987aed947d0285a4f Binary files /dev/null and b/itrialspace/src/itrialspace/evaluation/vlm_eval/models/__pycache__/llava_med.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/models/__pycache__/medgemma.cpython-310.pyc b/itrialspace/src/itrialspace/evaluation/vlm_eval/models/__pycache__/medgemma.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0d419298419ffcc73cd6b971664a10e5aa13005f Binary files /dev/null and b/itrialspace/src/itrialspace/evaluation/vlm_eval/models/__pycache__/medgemma.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/models/llava_med.py b/itrialspace/src/itrialspace/evaluation/vlm_eval/models/llava_med.py new file mode 100644 index 0000000000000000000000000000000000000000..463c3553e84defb40a0886c1ba8782a956485cc4 --- /dev/null +++ b/itrialspace/src/itrialspace/evaluation/vlm_eval/models/llava_med.py @@ -0,0 +1,177 @@ +""" +LLaVA-Med model adapter for generative VLM evaluation. + +Uses the HuggingFace ``LlavaForConditionalGeneration`` class. +Default model: ``llava-hf/llava-1.5-7b-hf`` (LLaVA-1.5 7B, fully HF-native). +Override ``model_id`` with a local LLaVA-Med checkpoint when available. + +Key differences from BiomedCLIP: +- Generative (autoregressive) rather than contrastive +- Takes a chat-formatted prompt with ```` token +- Processor resizes images to 336×336 and normalises via CLIPImageProcessor +- Output is free-form text that must be parsed into canonical labels +""" + +from __future__ import annotations + +from typing import Dict, Optional + +import torch +from PIL import Image + + +class LLaVAMedModel: + """Generative VLM adapter around HuggingFace LLaVA. + + Loads lazily on first call. Produces free-text answers for a given + image + text prompt which are then normalised by ``parsers.py``. + """ + + DEFAULT_MODEL_ID = "llava-hf/llava-1.5-7b-hf" + + def __init__( + self, + model_id: Optional[str] = None, + device: Optional[str] = None, + cache_dir: Optional[str] = None, + torch_dtype: Optional[str] = None, + max_new_tokens: int = 64, + ): + self.model_id = model_id or self.DEFAULT_MODEL_ID + self._device_str = device + self._cache_dir = cache_dir + self._torch_dtype_str = torch_dtype + self.max_new_tokens = max_new_tokens + + self._model = None + self._processor = None + self._device: Optional[torch.device] = None + + # ── lazy loading ───────────────────────────────────────────────────── + + def _load(self): + if self._model is not None: + return + + from transformers import AutoProcessor, LlavaForConditionalGeneration + + if self._device_str: + self._device = torch.device(self._device_str) + else: + self._device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + + dtype_map = { + "float16": torch.float16, + "bfloat16": torch.bfloat16, + "float32": torch.float32, + } + torch_dtype = dtype_map.get( + self._torch_dtype_str or "", + torch.float16 if self._device.type == "cuda" else torch.float32, + ) + + print(f"Loading LLaVA from {self.model_id} ...") + print(f" Device: {self._device} dtype: {torch_dtype}") + + # Access token read from the environment (.env -> HF_TOKEN); some LLaVA-Med + # checkpoints are gated. Never hardcoded — see settings.hf_token / .env.example. + from itrialspace.config.settings import hf_token + + token = hf_token() + + kwargs: Dict = {"torch_dtype": torch_dtype} + if self._cache_dir: + kwargs["cache_dir"] = self._cache_dir + if token: + kwargs["token"] = token + + # Try Flash Attention 2 for faster inference + try: + import flash_attn # noqa: F401 + + kwargs["attn_implementation"] = "flash_attention_2" + print(" Using Flash Attention 2") + except ImportError: + pass + + self._processor = AutoProcessor.from_pretrained( + self.model_id, + trust_remote_code=True, + **({"cache_dir": self._cache_dir} if self._cache_dir else {}), + **({"token": token} if token else {}), + ) + self._model = LlavaForConditionalGeneration.from_pretrained( + self.model_id, + trust_remote_code=True, + **kwargs, + ) + self._model.eval() + self._model.to(self._device) + print(" LLaVA loaded.") + + @property + def device(self) -> torch.device: + self._load() + return self._device + + # ── prompt formatting ──────────────────────────────────────────────── + + def _format_prompt(self, question: str) -> str: + """Build a chat-template prompt with an image placeholder.""" + conversation = [ + { + "role": "user", + "content": [ + {"type": "image"}, + {"type": "text", "text": question}, + ], + } + ] + return self._processor.apply_chat_template(conversation, add_generation_prompt=True) + + # ── image preprocessing ────────────────────────────────────────────── + + @staticmethod + def load_image(image_path: str) -> Image.Image: + """Load an image as RGB (LLaVA expects RGB input).""" + return Image.open(image_path).convert("RGB") + + # ── inference ──────────────────────────────────────────────────────── + + def generate(self, image_path: str, question: str) -> str: + """Generate a free-text answer for one image + question pair. + + Parameters + ---------- + image_path : str + Path to PNG slice. + question : str + The instruction / question text. + + Returns + ------- + str + Raw generated text (decoded, prompt stripped). + """ + self._load() + + image = self.load_image(image_path) + prompt = self._format_prompt(question) + + inputs = self._processor( + text=prompt, + images=image, + return_tensors="pt", + ).to(self._device) + + with torch.no_grad(): + output_ids = self._model.generate( + **inputs, + max_new_tokens=self.max_new_tokens, + do_sample=False, + ) + + # Strip input tokens from output to get only generated text + generated_ids = output_ids[0, inputs["input_ids"].shape[1] :] + answer = self._processor.tokenizer.decode(generated_ids, skip_special_tokens=True).strip() + return answer diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/models/medgemma.py b/itrialspace/src/itrialspace/evaluation/vlm_eval/models/medgemma.py new file mode 100644 index 0000000000000000000000000000000000000000..a4ae0ec94aaabf29727d42a97eeacb7990eeb132 --- /dev/null +++ b/itrialspace/src/itrialspace/evaluation/vlm_eval/models/medgemma.py @@ -0,0 +1,239 @@ +""" +MedGemma 1.5 4B model adapter for generative VLM evaluation. + +Uses the HuggingFace ``AutoModelForImageTextToText`` class with the +``google/medgemma-1.5-4b-it`` checkpoint (instruction-tuned MedGemma 1.5 4B). + +MedGemma 1.5 is built on Gemma 3 with a medical-domain SigLIP vision encoder. +For CT imaging, MedGemma 1.5 expects a specific 3-channel RGB encoding where +each channel is a different HU window: + R = wide (-1024, 1024) + G = soft tissue (-135, 215) + B = brain (0, 80) + +The adapter supports multi-slice input: the centre slice + context slices +(e.g. _z-1, _z+1) are auto-discovered and passed as separate images in the +prompt, matching the official MedGemma CT notebook pattern. + +Key characteristics: +- Built on Gemma 3 + SigLIP medical vision encoder +- Images resized to 896×896 and encoded to 256 tokens each by the processor +- Chat-style prompting with user role +- Multi-image support for multi-slice CT input +- ~4B parameters, ~8 GB VRAM in bfloat16 +""" + +from __future__ import annotations + +import os +import re +from typing import Dict, List, Optional + +import torch +from PIL import Image + + +class MedGemmaModel: + """Generative VLM adapter for MedGemma 1.5 4B. + + Loads lazily on first call. Produces free-text answers for a given + image + text prompt which are then normalised by ``parsers.py``. + """ + + DEFAULT_MODEL_ID = "google/medgemma-1.5-4b-it" + + def __init__( + self, + model_id: Optional[str] = None, + device: Optional[str] = None, + cache_dir: Optional[str] = None, + torch_dtype: Optional[str] = None, + max_new_tokens: int = 64, + ): + self.model_id = model_id or self.DEFAULT_MODEL_ID + self._device_str = device + self._cache_dir = cache_dir + self._torch_dtype_str = torch_dtype + self.max_new_tokens = max_new_tokens + + self._model = None + self._processor = None + self._device: Optional[torch.device] = None + + # ── lazy loading ───────────────────────────────────────────────────── + + def _load(self): + if self._model is not None: + return + + from transformers import AutoModelForImageTextToText, AutoProcessor + + if self._device_str: + self._device = torch.device(self._device_str) + else: + self._device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + + dtype_map = { + "float16": torch.float16, + "bfloat16": torch.bfloat16, + "float32": torch.float32, + } + torch_dtype = dtype_map.get( + self._torch_dtype_str or "", + torch.bfloat16 if self._device.type == "cuda" else torch.float32, + ) + + print(f"Loading MedGemma from {self.model_id} ...") + print(f" Device: {self._device} dtype: {torch_dtype}") + + # MedGemma is a GATED model: the access token is read from the environment + # (.env -> HF_TOKEN), never hardcoded. See settings.hf_token / .env.example. + from itrialspace.config.settings import hf_token + + token = hf_token() + if token is None: + print( + " WARN: no HF_TOKEN in environment/.env — MedGemma is gated and will " + "fail to download unless you are already logged in (huggingface-cli login)." + ) + + kwargs: Dict = {"torch_dtype": torch_dtype} + if self._cache_dir: + kwargs["cache_dir"] = self._cache_dir + if token: + kwargs["token"] = token + + # `device_map="auto"` needs `accelerate`. Use it for multi-GPU sharding when + # available; otherwise load normally and move to the device ourselves, so a + # single-GPU run works without accelerate (and without crashing the job). + try: + from transformers.utils import is_accelerate_available + + use_device_map = is_accelerate_available() + except Exception: + use_device_map = False + if use_device_map: + kwargs["device_map"] = "auto" + else: + print(" accelerate not available — loading on a single device (no device_map).") + + # Try Flash Attention 2 for faster inference + try: + import flash_attn # noqa: F401 + + kwargs["attn_implementation"] = "flash_attention_2" + print(" Using Flash Attention 2") + except ImportError: + pass + + self._processor = AutoProcessor.from_pretrained( + self.model_id, + use_fast=True, + **({"cache_dir": self._cache_dir} if self._cache_dir else {}), + **({"token": token} if token else {}), + ) + self._model = AutoModelForImageTextToText.from_pretrained( + self.model_id, + **kwargs, + ) + if not use_device_map: + self._model = self._model.to(self._device) + self._model.eval() + print(" MedGemma loaded.") + + @property + def device(self) -> torch.device: + self._load() + return self._device + + # ── image handling ─────────────────────────────────────────────────── + + @staticmethod + def load_image(image_path: str) -> Image.Image: + """Load an image as RGB. + + For png_medgemma_rgb slices the PNG is already 3-channel RGB + (each channel = different HU window). For grayscale PNGs this + converts to RGB by duplicating the single channel. + """ + return Image.open(image_path).convert("RGB") + + @staticmethod + def discover_context_slices(center_path: str) -> List[str]: + """Find the centre + context slice paths in sorted z-order. + + Given ``/dir/name.png`` looks for ``/dir/name_z-N.png`` and + ``/dir/name_z+N.png`` siblings. Returns the complete ordered + list ``[..., _z-1, centre, _z+1, ...]``. + """ + base, ext = os.path.splitext(center_path) + pattern = re.compile( + re.escape(os.path.basename(base)) + r"_z([+-]\d+)" + re.escape(ext) + "$" + ) + parent = os.path.dirname(center_path) or "." + neighbours: Dict[int, str] = {} + for fname in os.listdir(parent): + m = pattern.match(fname) + if m: + offset = int(m.group(1)) + neighbours[offset] = os.path.join(parent, fname) + # Centre slice is offset 0 + neighbours[0] = center_path + return [neighbours[k] for k in sorted(neighbours)] + + # ── inference ──────────────────────────────────────────────────────── + + def generate(self, image_path: str, question: str) -> str: + """Generate a free-text answer for CT slice(s) + question. + + Automatically discovers context slices (``_z-1``, ``_z+1``, etc.) + stored alongside *image_path* and sends them all as separate + images in the prompt, matching the MedGemma 1.5 CT protocol. + + Parameters + ---------- + image_path : str + Path to the **centre** slice PNG. + question : str + The instruction / question text. + + Returns + ------- + str + Raw generated text (decoded, prompt stripped). + """ + self._load() + + # Collect ordered slice paths + slice_paths = self.discover_context_slices(image_path) + images = [self.load_image(p) for p in slice_paths] + + # Build multi-image chat prompt (official MedGemma CT pattern) + content: List[Dict] = [] + for i, img in enumerate(images, 1): + content.append({"type": "image", "image": img}) + if len(images) > 1: + content.append({"type": "text", "text": f"SLICE {i}"}) + content.append({"type": "text", "text": question}) + + messages = [{"role": "user", "content": content}] + + inputs = self._processor.apply_chat_template( + messages, + add_generation_prompt=True, + tokenize=True, + return_dict=True, + return_tensors="pt", + ).to(self._model.device, dtype=torch.bfloat16) + + with torch.inference_mode(): + output_ids = self._model.generate( + **inputs, + max_new_tokens=self.max_new_tokens, + do_sample=False, + ) + + # Decode only the generated tokens (strip the input prompt) + generated_ids = output_ids[0, inputs["input_ids"].shape[1] :] + answer = self._processor.tokenizer.decode(generated_ids, skip_special_tokens=True).strip() + return answer diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/overlay.py b/itrialspace/src/itrialspace/evaluation/vlm_eval/overlay.py new file mode 100644 index 0000000000000000000000000000000000000000..ef7d3ce4c751f073e2bbae9500bd936c54ae47fd --- /dev/null +++ b/itrialspace/src/itrialspace/evaluation/vlm_eval/overlay.py @@ -0,0 +1,354 @@ +""" +Generate bounding-box and contour overlay images from plain slices + masks. + +Given a plain CT slice PNG and the corresponding lesion mask, produces: +- bbox overlay: plain slice with a bright bounding-box rectangle around the lesion +- contour overlay: plain slice with the lesion boundary drawn as a contour +- bbox_contour overlay: both combined + +All overlays keep the same spatial dimensions and orientation as the input +plain slice so model preprocessors (resize, crop, normalize) handle them +identically. +""" + +from __future__ import annotations + +import logging +import os +from typing import List, Optional, Tuple + +import nibabel as nib +import numpy as np +from PIL import Image, ImageDraw + +from itrialspace.evaluation.vlm_eval.slice_extractor import ( + _clean_artifact_slices, + _to_radiological, +) + +logger = logging.getLogger(__name__) + +# Valid image conditions +VALID_CONDITIONS = ("plain", "bbox", "contour", "bbox_contour") + +# Overlay colours (RGB) +BBOX_COLOR = (0, 255, 0) # bright green +CONTOUR_COLOR = (255, 50, 50) # red +BBOX_WIDTH = 2 # pixels +CONTOUR_WIDTH = 2 # pixels +# Padding (pixels) around bounding box +BBOX_PAD = 3 + + +def _get_mask_slice_2d( + mask_path: str, + slice_index: int, + slice_plane: str = "axial", + nodule_label: Optional[int] = None, +) -> Optional[np.ndarray]: + """Extract a 2D binary lesion mask at the given slice, radiologically oriented. + + Returns a boolean 2D array matching the orientation of + ``_extract_plane_slice`` output, or None if mask cannot be loaded + or has no lesion voxels on that slice. + + Parameters + ---------- + nodule_label : int or None + Label value to threshold. ``None`` (default) means *any non-zero* + voxel — suitable for per-nodule binary masks. An explicit integer + (e.g. 23) selects only that label from a multi-label mask. + """ + if not mask_path or not os.path.isfile(mask_path): + return None + try: + mask_nii = nib.load(mask_path) + mask_data = nib.as_closest_canonical(mask_nii).get_fdata(dtype=np.float32) + _clean_artifact_slices(mask_data, nodule_label=nodule_label) + except Exception as e: + logger.warning("Cannot load mask %s: %s", mask_path, e) + return None + + _axis_map = {"axial": 2, "coronal": 1, "sagittal": 0} + axis = _axis_map.get(slice_plane, 2) + max_idx = mask_data.shape[axis] - 1 + if slice_index < 0 or slice_index > max_idx: + return None + + # Extract 2D mask at that index + slicing: List = [slice(None)] * 3 + slicing[axis] = slice_index + raw_slice = mask_data[tuple(slicing)] + if nodule_label is None: + binary = (raw_slice > 0).astype(np.uint8) + else: + binary = (raw_slice == nodule_label).astype(np.uint8) + + if binary.sum() == 0: + return None + + # Orient to match the plain slice PNG + if slice_plane == "axial": + oriented = _to_radiological(binary) + elif slice_plane == "coronal": + oriented = np.flipud(binary.T) + else: # sagittal + oriented = np.flipud(binary.T) + + return oriented.astype(bool) + + +def _mask_to_bbox(binary_mask: np.ndarray, pad: int = BBOX_PAD) -> Tuple[int, int, int, int]: + """Compute (x0, y0, x1, y1) bounding box from a 2D boolean mask. + + Returns coordinates in (col_min, row_min, col_max, row_max) order + suitable for ``ImageDraw.rectangle``. + """ + rows, cols = np.nonzero(binary_mask) + r_min, r_max = int(rows.min()), int(rows.max()) + c_min, c_max = int(cols.min()), int(cols.max()) + h, w = binary_mask.shape + x0 = max(c_min - pad, 0) + y0 = max(r_min - pad, 0) + x1 = min(c_max + pad, w - 1) + y1 = min(r_max + pad, h - 1) + return x0, y0, x1, y1 + + +def _mask_to_contour(binary_mask: np.ndarray) -> np.ndarray: + """Extract single-pixel boundary contour from a 2D boolean mask. + + Uses morphological erosion to find boundary pixels. + Returns a boolean 2D array where True = contour pixel. + """ + from scipy.ndimage import binary_erosion + + if binary_mask.sum() == 0: + return np.zeros_like(binary_mask, dtype=bool) + + eroded = binary_erosion(binary_mask, iterations=1) + contour = binary_mask & ~eroded + return contour + + +def _plain_to_rgb(img: Image.Image) -> Image.Image: + """Ensure image is RGB (convert grayscale if needed).""" + if img.mode == "L": + return img.convert("RGB") + if img.mode == "RGB": + return img + return img.convert("RGB") + + +def draw_bbox_overlay( + plain_img: Image.Image, + binary_mask: np.ndarray, + color: Tuple[int, int, int] = BBOX_COLOR, + width: int = BBOX_WIDTH, +) -> Image.Image: + """Draw a bounding-box rectangle on a copy of the plain image.""" + rgb = _plain_to_rgb(plain_img).copy() + x0, y0, x1, y1 = _mask_to_bbox(binary_mask) + draw = ImageDraw.Draw(rgb) + for i in range(width): + draw.rectangle([x0 - i, y0 - i, x1 + i, y1 + i], outline=color) + return rgb + + +def draw_contour_overlay( + plain_img: Image.Image, + binary_mask: np.ndarray, + color: Tuple[int, int, int] = CONTOUR_COLOR, + width: int = CONTOUR_WIDTH, +) -> Image.Image: + """Draw the lesion contour on a copy of the plain image.""" + from scipy.ndimage import binary_dilation + + rgb = _plain_to_rgb(plain_img).copy() + contour = _mask_to_contour(binary_mask) + + # Thicken contour if width > 1 + if width > 1: + contour = binary_dilation(contour, iterations=width - 1) + + arr = np.array(rgb) + arr[contour, 0] = color[0] + arr[contour, 1] = color[1] + arr[contour, 2] = color[2] + return Image.fromarray(arr) + + +def draw_bbox_contour_overlay( + plain_img: Image.Image, + binary_mask: np.ndarray, + bbox_color: Tuple[int, int, int] = BBOX_COLOR, + contour_color: Tuple[int, int, int] = CONTOUR_COLOR, +) -> Image.Image: + """Draw both bounding box and contour on a copy of the plain image.""" + img = draw_bbox_overlay(plain_img, binary_mask, color=bbox_color) + img = draw_contour_overlay(img, binary_mask, color=contour_color) + return img + + +def generate_overlays( + plain_png_path: str, + mask_path: str, + slice_index: int, + slice_plane: str = "axial", + conditions: Tuple[str, ...] = ("bbox", "contour", "bbox_contour"), + nodule_label: Optional[int] = None, +) -> dict: + """Generate overlay PNGs for a single case. + + Parameters + ---------- + plain_png_path : str + Path to the existing plain slice PNG. + mask_path : str + Path to the lesion mask NIfTI (input_mask.nii.gz or per-nodule mask). + slice_index : int + Slice index along the extraction axis. + slice_plane : str + "axial", "coronal", or "sagittal". + conditions : tuple of str + Which overlays to generate ("bbox", "contour", "bbox_contour"). + nodule_label : int or None + Label value to threshold in the mask. ``None`` (default) means + *any non-zero* voxel. Use 23 for synthetic iTrialSpace masks. + + Returns + ------- + dict + Mapping condition name -> output path (or None if generation failed). + """ + result = {} + for cond in conditions: + if cond not in ("bbox", "contour", "bbox_contour"): + continue + result[cond] = None + + if not os.path.isfile(plain_png_path): + logger.warning("Plain PNG missing: %s", plain_png_path) + return result + + binary_mask = _get_mask_slice_2d(mask_path, slice_index, slice_plane, nodule_label=nodule_label) + if binary_mask is None: + logger.warning( + "No lesion mask on slice %d for %s — skipping overlays", + slice_index, + plain_png_path, + ) + return result + + plain_img = Image.open(plain_png_path) + parent_dir = os.path.dirname(plain_png_path) or "." + filename = os.path.basename(plain_png_path) + base_name, ext = os.path.splitext(filename) + + # Discover plain context slices (e.g. _z-1, _z+1) for multi-slice models. + # We draw overlays on context slices too (if the lesion is visible there) + # so MedGemma sees consistent visual guidance across all input slices. + import re as _re + + ctx_pattern = _re.compile(_re.escape(base_name) + r"_z([+-]\d+)" + _re.escape(ext) + "$") + context_siblings: List[tuple] = [] # (z_offset, full_path) + for fname in os.listdir(parent_dir): + m = ctx_pattern.match(fname) + if m: + z_offset = int(m.group(1)) + context_siblings.append((z_offset, os.path.join(parent_dir, fname))) + + for cond in conditions: + if cond == "bbox": + overlay_img = draw_bbox_overlay(plain_img, binary_mask) + elif cond == "contour": + overlay_img = draw_contour_overlay(plain_img, binary_mask) + elif cond == "bbox_contour": + overlay_img = draw_bbox_contour_overlay(plain_img, binary_mask) + else: + continue + + # Save into a condition sub-folder: {parent}/{condition}/{filename} + cond_dir = os.path.join(parent_dir, cond) + os.makedirs(cond_dir, exist_ok=True) + out_path = os.path.join(cond_dir, filename) + overlay_img.save(out_path) + result[cond] = out_path + + # Generate overlays for context slices too. If the lesion mask + # has data on the neighbouring slice we draw the overlay; otherwise + # copy the plain slice so the file still exists for discovery. + for z_offset, ctx_path in context_siblings: + ctx_filename = os.path.basename(ctx_path) + ctx_out = os.path.join(cond_dir, ctx_filename) + if os.path.exists(ctx_out): + continue + + ctx_slice_idx = slice_index + z_offset + ctx_mask = _get_mask_slice_2d( + mask_path, ctx_slice_idx, slice_plane, nodule_label=nodule_label + ) + + if ctx_mask is not None: + # Lesion visible on this slice — draw overlay + ctx_plain = Image.open(ctx_path) + if cond == "bbox": + ctx_overlay = draw_bbox_overlay(ctx_plain, ctx_mask) + elif cond == "contour": + ctx_overlay = draw_contour_overlay(ctx_plain, ctx_mask) + else: # bbox_contour + ctx_overlay = draw_bbox_contour_overlay(ctx_plain, ctx_mask) + ctx_overlay.save(ctx_out) + else: + # No lesion on this slice — copy the plain version + import shutil + + shutil.copy2(ctx_path, ctx_out) + + return result + + +def generate_qc_grid( + plain_path: str, + bbox_path: Optional[str], + contour_path: Optional[str], + bbox_contour_path: Optional[str], + output_path: str, +) -> Optional[str]: + """Save a side-by-side QC grid of all conditions for one case. + + Returns the output path or None on failure. + """ + paths = [ + ("plain", plain_path), + ("bbox", bbox_path), + ("contour", contour_path), + ("bbox+contour", bbox_contour_path), + ] + images = [] + labels = [] + for label, p in paths: + if p and os.path.isfile(p): + images.append(Image.open(p).convert("RGB")) + labels.append(label) + + if len(images) < 2: + return None + + # Create horizontal grid + widths = [img.width for img in images] + max_h = max(img.height for img in images) + label_h = 20 + total_w = sum(widths) + grid = Image.new("RGB", (total_w, max_h + label_h), color=(0, 0, 0)) + + draw = ImageDraw.Draw(grid) + x_offset = 0 + for img, label in zip(images, labels): + grid.paste(img, (x_offset, label_h)) + draw.text((x_offset + 4, 2), label, fill=(255, 255, 255)) + x_offset += img.width + + os.makedirs(os.path.dirname(output_path) or ".", exist_ok=True) + grid.save(output_path) + return output_path diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/parsers.py b/itrialspace/src/itrialspace/evaluation/vlm_eval/parsers.py new file mode 100644 index 0000000000000000000000000000000000000000..4dadd9824b9052e79a80bfd1b5c83bc990a0fde4 --- /dev/null +++ b/itrialspace/src/itrialspace/evaluation/vlm_eval/parsers.py @@ -0,0 +1,173 @@ +""" +Answer normalisation for generative VLM outputs. + +Maps free-text model responses to canonical task labels. +Handles common variants, abbreviations, and verbose answers. +""" + +from __future__ import annotations + +import re +from dataclasses import dataclass + + +@dataclass(frozen=True) +class ParseResult: + """Result of parsing a raw model output.""" + + label: str # canonical label or "unparsed" + status: str # "ok" | "unparsed" + raw: str # original text + + +# ── Presence parsing ───────────────────────────────────────────────────────── + +_YES_PATTERNS = re.compile( + r"\b(yes|yeah|yep|present|contains|detected|visible|seen|found|positive)\b", + re.IGNORECASE, +) +_NO_PATTERNS = re.compile( + r"\b(no|nope|absent|none|not\s+present|not\s+detected|negative" + r"|no\s+nodule|does\s+not\s+contain|without)\b", + re.IGNORECASE, +) + + +def parse_presence(raw: str) -> ParseResult: + """Parse a generative answer into present/absent.""" + text = raw.strip() + if not text: + return ParseResult(label="unparsed", status="unparsed", raw=raw) + + # Check for explicit "no" first (must come before "yes" to handle + # "No, there is no nodule" correctly) + if _NO_PATTERNS.search(text): + # Make sure it's not a double-negative situation + # e.g. "not absent" → present + if re.search(r"\bnot\s+(absent|negative)\b", text, re.IGNORECASE): + return ParseResult(label="present", status="ok", raw=raw) + return ParseResult(label="absent", status="ok", raw=raw) + + if _YES_PATTERNS.search(text): + return ParseResult(label="present", status="ok", raw=raw) + + return ParseResult(label="unparsed", status="unparsed", raw=raw) + + +# ── Lobe parsing ───────────────────────────────────────────────────────────── + +_LOBE_MAP = { + # Canonical labels (underscore form) + "right_lung_upper_lobe": "right_lung_upper_lobe", + "right_lung_middle_lobe": "right_lung_middle_lobe", + "right_lung_lower_lobe": "right_lung_lower_lobe", + "left_lung_upper_lobe": "left_lung_upper_lobe", + "left_lung_lower_lobe": "left_lung_lower_lobe", + # Human-readable forms + "right upper lobe": "right_lung_upper_lobe", + "right middle lobe": "right_lung_middle_lobe", + "right lower lobe": "right_lung_lower_lobe", + "left upper lobe": "left_lung_upper_lobe", + "left lower lobe": "left_lung_lower_lobe", + # Abbreviations + "rul": "right_lung_upper_lobe", + "rml": "right_lung_middle_lobe", + "rll": "right_lung_lower_lobe", + "lul": "left_lung_upper_lobe", + "lll": "left_lung_lower_lobe", +} + +# Ordered by specificity (check "right middle" before "right") +_LOBE_SEARCH_ORDER = [ + ("right middle lobe", "right_lung_middle_lobe"), + ("right upper lobe", "right_lung_upper_lobe"), + ("right lower lobe", "right_lung_lower_lobe"), + ("left upper lobe", "left_lung_upper_lobe"), + ("left lower lobe", "left_lung_lower_lobe"), + ("right middle", "right_lung_middle_lobe"), + ("right upper", "right_lung_upper_lobe"), + ("right lower", "right_lung_lower_lobe"), + ("left upper", "left_lung_upper_lobe"), + ("left lower", "left_lung_lower_lobe"), + ("rml", "right_lung_middle_lobe"), + ("rul", "right_lung_upper_lobe"), + ("rll", "right_lung_lower_lobe"), + ("lul", "left_lung_upper_lobe"), + ("lll", "left_lung_lower_lobe"), +] + + +def parse_lobe(raw: str) -> ParseResult: + """Parse a generative answer into a canonical lobe label.""" + text = raw.strip() + if not text: + return ParseResult(label="unparsed", status="unparsed", raw=raw) + + text_lower = text.lower() + + # Direct match of canonical underscore form (e.g. "right_lung_lower_lobe") + if text_lower.replace(" ", "_") in _LOBE_MAP: + return ParseResult(label=_LOBE_MAP[text_lower.replace(" ", "_")], status="ok", raw=raw) + + # Exact match after normalisation (underscores → spaces) + normalised = text_lower.replace("_", " ").strip() + if normalised in _LOBE_MAP: + return ParseResult(label=_LOBE_MAP[normalised], status="ok", raw=raw) + + # Substring search in order of specificity + for pattern, canonical in _LOBE_SEARCH_ORDER: + if re.search(r"\b" + re.escape(pattern) + r"\b", text_lower): + return ParseResult(label=canonical, status="ok", raw=raw) + + # Abbreviation as standalone word (case-insensitive) + for abbrev in ["rul", "rml", "rll", "lul", "lll"]: + if re.search(r"\b" + abbrev + r"\b", text_lower): + return ParseResult(label=_LOBE_MAP[abbrev], status="ok", raw=raw) + + return ParseResult(label="unparsed", status="unparsed", raw=raw) + + +# ── Size bucket parsing ────────────────────────────────────────────────────── + +_SIZE_PATTERNS = [ + # Order: most specific first + (re.compile(r"<\s*5\s*mm|less\s+than\s+5|smaller\s+than\s+5|under\s+5", re.I), "<5mm"), + ( + re.compile( + r">\s*20\s*mm|larger\s+than\s+20|greater\s+than\s+20|over\s+20|above\s+20", re.I + ), + ">20mm", + ), + (re.compile(r"10\s*[-–—to]+\s*20\s*mm|between\s+10\s+and\s+20", re.I), "10-20mm"), + (re.compile(r"5\s*[-–—to]+\s*10\s*mm|between\s+5\s+and\s+10", re.I), "5-10mm"), +] + + +def parse_size_bucket(raw: str) -> ParseResult: + """Parse a generative answer into a canonical size bucket.""" + text = raw.strip() + if not text: + return ParseResult(label="unparsed", status="unparsed", raw=raw) + + for pattern, label in _SIZE_PATTERNS: + if pattern.search(text): + return ParseResult(label=label, status="ok", raw=raw) + + return ParseResult(label="unparsed", status="unparsed", raw=raw) + + +# ── Dispatcher ─────────────────────────────────────────────────────────────── + +_TASK_PARSERS = { + "presence": parse_presence, + "lobe": parse_lobe, + "size": parse_size_bucket, +} + + +def parse_answer(task_name: str, raw: str) -> ParseResult: + """Route to the correct parser for a given task name.""" + parser_fn = _TASK_PARSERS.get(task_name) + if parser_fn is None: + raise ValueError(f"No parser for task '{task_name}'") + return parser_fn(raw) diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/plots.py b/itrialspace/src/itrialspace/evaluation/vlm_eval/plots.py new file mode 100644 index 0000000000000000000000000000000000000000..0ff8b11a80edb456d924d9c242f9d9a3ad8680fa --- /dev/null +++ b/itrialspace/src/itrialspace/evaluation/vlm_eval/plots.py @@ -0,0 +1,112 @@ +""" +Plotting utilities for VLM evaluation results. + +Generates confusion matrix heatmaps and accuracy bar charts. +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Dict, List + +import matplotlib + +matplotlib.use("Agg") +import matplotlib.pyplot as plt +import numpy as np +import seaborn as sns + + +def plot_confusion_matrix( + cm: List[List[int]], + labels: List[str], + title: str, + output_path: Path, + figsize: tuple = (8, 6), +) -> Path: + """Save a confusion matrix heatmap to disk.""" + cm_arr = np.array(cm) + fig, ax = plt.subplots(figsize=figsize) + sns.heatmap( + cm_arr, + annot=True, + fmt="d", + cmap="Blues", + xticklabels=labels, + yticklabels=labels, + ax=ax, + ) + ax.set_xlabel("Predicted") + ax.set_ylabel("Ground Truth") + ax.set_title(title) + plt.tight_layout() + output_path.parent.mkdir(parents=True, exist_ok=True) + fig.savefig(output_path, dpi=150) + plt.close(fig) + return output_path + + +def plot_accuracy_bar( + task_accuracies: Dict[str, float], + title: str, + output_path: Path, + figsize: tuple = (8, 5), +) -> Path: + """Save an accuracy bar chart across tasks.""" + tasks = list(task_accuracies.keys()) + accs = [task_accuracies[t] for t in tasks] + + fig, ax = plt.subplots(figsize=figsize) + bars = ax.bar(tasks, accs, color=sns.color_palette("muted", len(tasks))) + ax.set_ylabel("Accuracy") + ax.set_title(title) + ax.set_ylim(0, 1.05) + for bar, acc in zip(bars, accs): + ax.text( + bar.get_x() + bar.get_width() / 2, + bar.get_height() + 0.02, + f"{acc:.2%}", + ha="center", + va="bottom", + fontsize=10, + ) + plt.tight_layout() + output_path.parent.mkdir(parents=True, exist_ok=True) + fig.savefig(output_path, dpi=150) + plt.close(fig) + return output_path + + +def plot_grouped_accuracy( + grouped: Dict[str, Dict], + group_name: str, + title: str, + output_path: Path, + figsize: tuple = (10, 5), +) -> Path: + """Save a grouped accuracy bar chart (e.g. accuracy by mode or dataset).""" + keys = sorted(grouped.keys()) + accs = [grouped[k]["accuracy"] for k in keys] + counts = [grouped[k]["n_samples"] for k in keys] + + fig, ax = plt.subplots(figsize=figsize) + bars = ax.bar(keys, accs, color=sns.color_palette("Set2", len(keys))) + ax.set_ylabel("Accuracy") + ax.set_xlabel(group_name) + ax.set_title(title) + ax.set_ylim(0, 1.05) + for bar, acc, n in zip(bars, accs, counts): + ax.text( + bar.get_x() + bar.get_width() / 2, + bar.get_height() + 0.02, + f"{acc:.1%}\n(n={n})", + ha="center", + va="bottom", + fontsize=8, + ) + plt.xticks(rotation=45, ha="right") + plt.tight_layout() + output_path.parent.mkdir(parents=True, exist_ok=True) + fig.savefig(output_path, dpi=150) + plt.close(fig) + return output_path diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/preprocess_profiles.py b/itrialspace/src/itrialspace/evaluation/vlm_eval/preprocess_profiles.py new file mode 100644 index 0000000000000000000000000000000000000000..06d1b73ce7f2c877a87129ed80a966afa0dcd060 --- /dev/null +++ b/itrialspace/src/itrialspace/evaluation/vlm_eval/preprocess_profiles.py @@ -0,0 +1,123 @@ +""" +Preprocessing profiles for VLM evaluation dataset extraction. + +Each profile defines how 2D slices are extracted from 3D CT volumes. +Models declare which profile they need; the dataset build step applies it. + +Usage in SLURM: + python -m itrialspace.evaluation.vlm_eval.build_dataset --profile lung_axial ... + +To add a new profile, define it in PROFILES below. The SLURM sub file +just passes --profile and the extraction pipeline adapts. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Dict + + +@dataclass(frozen=True) +class PreprocessProfile: + """Configuration for CT slice extraction and preprocessing.""" + + name: str + + # CT windowing + window_center: float = -600.0 + window_width: float = 1500.0 + + # Slice orientation: "axial", "coronal", "sagittal" + slice_plane: str = "axial" + + # Output format: "png_gray", "png_rgb", "png_medgemma_rgb", "npy" + output_format: str = "png_gray" + + # How many extra slices on each side of the centre (0 = centre only) + num_context_slices: int = 1 + + # Whether to save QC overlay PNGs alongside slices + save_overlay: bool = False + + +# ── Named profiles ─────────────────────────────────────────────────────────── +# Each entry is usable via --profile in the CLI. + +PROFILES: Dict[str, PreprocessProfile] = { + "lung_axial": PreprocessProfile( + name="lung_axial", + window_center=-600.0, + window_width=1500.0, + slice_plane="axial", + output_format="png_gray", + num_context_slices=1, + ), + "mediastinal_axial": PreprocessProfile( + name="mediastinal_axial", + window_center=40.0, + window_width=400.0, + slice_plane="axial", + output_format="png_gray", + num_context_slices=1, + ), + "bone_axial": PreprocessProfile( + name="bone_axial", + window_center=400.0, + window_width=1800.0, + slice_plane="axial", + output_format="png_gray", + num_context_slices=1, + ), + "lung_coronal": PreprocessProfile( + name="lung_coronal", + window_center=-600.0, + window_width=1500.0, + slice_plane="coronal", + output_format="png_gray", + num_context_slices=1, + ), + "lung_sagittal": PreprocessProfile( + name="lung_sagittal", + window_center=-600.0, + window_width=1500.0, + slice_plane="sagittal", + output_format="png_gray", + num_context_slices=1, + ), + "lung_axial_npy": PreprocessProfile( + name="lung_axial_npy", + window_center=-600.0, + window_width=1500.0, + slice_plane="axial", + output_format="npy", + num_context_slices=1, + ), + "lung_axial_medgemma": PreprocessProfile( + name="lung_axial_medgemma", + # window_center/width are ignored for png_medgemma_rgb; the format + # uses fixed 3-channel encoding: R=wide(-1024,1024), G=soft(-135,215), + # B=brain(0,80) per the MedGemma 1.5 CT training protocol. + window_center=-600.0, + window_width=1500.0, + slice_plane="axial", + output_format="png_medgemma_rgb", + num_context_slices=1, + ), +} + +DEFAULT_PROFILE = "lung_axial" + + +def get_profile(name: str) -> PreprocessProfile: + """Look up a profile by name. Raises ValueError if not found.""" + if name not in PROFILES: + available = ", ".join(sorted(PROFILES)) + raise ValueError( + f"Unknown preprocessing profile '{name}'. " f"Available profiles: {available}" + ) + return PROFILES[name] + + +def list_profiles() -> list[str]: + """Return sorted list of available profile names.""" + return sorted(PROFILES) diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/prompt_templates.py b/itrialspace/src/itrialspace/evaluation/vlm_eval/prompt_templates.py new file mode 100644 index 0000000000000000000000000000000000000000..2731d31f6e99cfce300acd6caf112a3231055fda --- /dev/null +++ b/itrialspace/src/itrialspace/evaluation/vlm_eval/prompt_templates.py @@ -0,0 +1,166 @@ +""" +Prompt templates for VLM evaluation tasks. + +Each task defines a set of text prompts and a mapping from prompt labels +to ground-truth column values in the iTrialSpace manifest. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Dict, List + + +@dataclass(frozen=True) +class TaskDefinition: + """A single evaluation task with its text prompts and label mapping.""" + + name: str + prompts: Dict[str, str] # label -> text prompt + manifest_column: str # column name in the eval dataset CSV + description: str = "" + + @property + def labels(self) -> List[str]: + return list(self.prompts.keys()) + + @property + def texts(self) -> List[str]: + return list(self.prompts.values()) + + +# ── Task 1: Nodule Presence ────────────────────────────────────────────────── + +PRESENCE_TASK = TaskDefinition( + name="presence", + prompts={ + "present": "A CT scan containing a pulmonary nodule.", + "absent": "A CT scan without a pulmonary nodule.", + }, + manifest_column="ground_truth_presence", + description="Binary classification: does the CT slice contain a nodule?", +) + +# ── Task 2: Lobe Localisation ──────────────────────────────────────────────── + +LOBE_TASK = TaskDefinition( + name="lobe", + prompts={ + "right_lung_upper_lobe": "A pulmonary nodule in the right upper lobe.", + "right_lung_middle_lobe": "A pulmonary nodule in the right middle lobe.", + "right_lung_lower_lobe": "A pulmonary nodule in the right lower lobe.", + "left_lung_upper_lobe": "A pulmonary nodule in the left upper lobe.", + "left_lung_lower_lobe": "A pulmonary nodule in the left lower lobe.", + }, + manifest_column="ground_truth_lobe", + description="5-class lobe localisation from text-image similarity.", +) + +# ── Task 3: Size Bucket ───────────────────────────────────────────────────── + +SIZE_TASK = TaskDefinition( + name="size", + prompts={ + "<5mm": "A pulmonary nodule smaller than 5 millimeters.", + "5-10mm": "A pulmonary nodule between 5 and 10 millimeters.", + "10-20mm": "A pulmonary nodule between 10 and 20 millimeters.", + ">20mm": "A pulmonary nodule larger than 20 millimeters.", + }, + manifest_column="ground_truth_size_bucket", + description="4-class size bucket classification from text-image similarity.", +) + +# ── Registry ───────────────────────────────────────────────────────────────── + +ALL_TASKS: Dict[str, TaskDefinition] = { + "presence": PRESENCE_TASK, + "lobe": LOBE_TASK, + "size": SIZE_TASK, +} + + +def get_task(name: str) -> TaskDefinition: + """Retrieve a task definition by name.""" + if name not in ALL_TASKS: + raise ValueError(f"Unknown task '{name}'. Available: {list(ALL_TASKS.keys())}") + return ALL_TASKS[name] + + +# ── Size-bucket helper ─────────────────────────────────────────────────────── + + +def diameter_to_size_bucket(diam_mm: float) -> str: + """Map effective diameter (mm) to a size bucket label.""" + if diam_mm < 5.0: + return "<5mm" + elif diam_mm < 10.0: + return "5-10mm" + elif diam_mm < 20.0: + return "10-20mm" + else: + return ">20mm" + + +# ── Lobe normalisation ─────────────────────────────────────────────────────── + +_LOBE_ALIASES = { + "right upper lobe": "right_lung_upper_lobe", + "right middle lobe": "right_lung_middle_lobe", + "right lower lobe": "right_lung_lower_lobe", + "left upper lobe": "left_lung_upper_lobe", + "left lower lobe": "left_lung_lower_lobe", + "rul": "right_lung_upper_lobe", + "rml": "right_lung_middle_lobe", + "rll": "right_lung_lower_lobe", + "lul": "left_lung_upper_lobe", + "lll": "left_lung_lower_lobe", +} + + +def normalise_lobe(lobe: str) -> str: + """Normalise a lobe name to the canonical form used in prompt labels.""" + lobe_lower = str(lobe).strip().lower().replace("_", " ") + # Direct match after replacing underscores + canonical = lobe_lower.replace(" ", "_") + if canonical in LOBE_TASK.prompts: + return canonical + # Alias lookup + if lobe_lower in _LOBE_ALIASES: + return _LOBE_ALIASES[lobe_lower] + # Partial match + for alias, canon in _LOBE_ALIASES.items(): + if alias in lobe_lower: + return canon + return str(lobe) # return as-is if no match + + +# ── Generative prompts (for instruction-following VLMs) ────────────────────── +# These are used by generative models like LLaVA-Med that produce free text +# rather than computing image-text similarity scores. + +GENERATIVE_PROMPTS: Dict[str, str] = { + "presence": ( + "Does this CT slice contain a pulmonary nodule? " "Answer using only one word: Yes or No." + ), + "lobe": ( + "Which lung lobe contains the nodule? " + "Answer using only one option: " + "Right upper lobe, Right middle lobe, Right lower lobe, " + "Left upper lobe, Left lower lobe." + ), + "size": ( + "What is the approximate diameter category of the nodule? " + "Answer using only one option: " + "<5 mm, 5-10 mm, 10-20 mm, >20 mm." + ), +} + + +def get_generative_prompt(task_name: str) -> str: + """Get the generative (instruction-following) prompt for a task.""" + if task_name not in GENERATIVE_PROMPTS: + raise ValueError( + f"No generative prompt for task '{task_name}'. " + f"Available: {list(GENERATIVE_PROMPTS.keys())}" + ) + return GENERATIVE_PROMPTS[task_name] diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/report.py b/itrialspace/src/itrialspace/evaluation/vlm_eval/report.py new file mode 100644 index 0000000000000000000000000000000000000000..7c4970a4136bfa47be2b13524021115fa09cd6aa --- /dev/null +++ b/itrialspace/src/itrialspace/evaluation/vlm_eval/report.py @@ -0,0 +1,160 @@ +""" +Generate the headline VLM evaluation report on a fixed case split. + +Computes accuracy for every (model x condition x task) **restricted to one frozen +split**, so every number in the report shares a single N (the reporting-N +convention; see ``docs/vlm_eval.md``). Emits a tidy CSV and a markdown report. + +Example +------- +python -m itrialspace.evaluation.vlm_eval.report \\ + --data-base $ITRIALSPACE_DATA_DIR/vlm_dataset \\ + --split release_v1_full \\ + --out docs/vlm_results.md \\ + --out-csv $ITRIALSPACE_DATA_DIR/vlm_dataset/vlm_accuracy_release_v1_full.csv +""" + +from __future__ import annotations + +import argparse +import csv +import os +from datetime import date +from pathlib import Path +from typing import Dict, List, Optional, Tuple + +from itrialspace.evaluation.vlm_eval.splits import canonical_uid, load_split + +MODELS = [("BiomedCLIP", "biomedclip"), ("LLaVA-Med", "llava_med"), ("MedGemma", "medgemma")] +PROFILE = {"biomedclip": "lung_axial", "llava_med": "lung_axial", "medgemma": "lung_axial_medgemma"} +CONDS = ["plain", "bbox", "contour", "bbox_contour"] +TASKS = ["presence", "lobe", "size"] +CHANCE = {"presence": 0.50, "lobe": 0.20, "size": 0.25} + + +def _accuracy(csv_path: str, keep: set) -> Tuple[Optional[float], int, int]: + """Accuracy over rows whose canonical uid is in ``keep`` (deduped by uid).""" + seen: Dict[str, bool] = {} + with open(csv_path) as f: + for r in csv.DictReader(f): + ip = r.get("image_path") or r.get("png_path") or "" + u = canonical_uid(ip) + if u in keep: + seen[u] = str(r.get("correct", "")).lower() in ("true", "1") + if not seen: + return None, 0, 0 + n_correct = sum(seen.values()) + return n_correct / len(seen), len(seen), n_correct + + +def build_rows(data_base: str, split: str, set_name: str) -> Tuple[int, List[dict]]: + keep = load_split(f"{data_base}/splits/{split}.{set_name}.txt") + rows: List[dict] = [] + for disp, m in MODELS: + base = f"{data_base}/{set_name}/{PROFILE[m]}/{m}" + for t in TASKS: + for c in CONDS: + fp = f"{base}/{c}/{t}_results.csv" + acc, n, nc = _accuracy(fp, keep) if os.path.isfile(fp) else (None, 0, 0) + rows.append( + { + "set": set_name, + "model": disp, + "task": t, + "condition": c, + "accuracy": "" if acc is None else round(acc, 4), + "n": n, + "n_correct": nc, + } + ) + return len(keep), rows + + +def _md_table(rows: List[dict]) -> str: + by: Dict[Tuple[str, str], Dict[str, float]] = {} + for r in rows: + by.setdefault((r["model"], r["task"]), {})[r["condition"]] = r["accuracy"] + out = [ + "| Model | Task | plain | bbox | contour | bbox_contour | best |", + "|-------|------|------:|-----:|--------:|-------------:|------|", + ] + for disp, _ in MODELS: + for t in TASKS: + cells = by.get((disp, t), {}) + vals = {c: cells.get(c) for c in CONDS} + fmt = {c: (f"{vals[c]*100:.1f}" if isinstance(vals[c], float) else "–") for c in CONDS} + numeric = {c: v for c, v in vals.items() if isinstance(v, float)} + best = max(numeric, key=numeric.get) if numeric else "–" + out.append( + f"| {disp} | {t} | {fmt['plain']} | {fmt['bbox']} | {fmt['contour']} " + f"| {fmt['bbox_contour']} | {best} |" + ) + return "\n".join(out) + + +def write_report(data_base: str, split: str, out_md: str, out_csv: Optional[str]) -> None: + sections, all_rows, ns = [], [], {} + for set_name in ("synthetic", "real"): + n, rows = build_rows(data_base, split, set_name) + ns[set_name] = n + all_rows.extend(rows) + sections.append((set_name, n, rows)) + + if out_csv: + Path(out_csv).parent.mkdir(parents=True, exist_ok=True) + with open(out_csv, "w", newline="") as f: + w = csv.DictWriter( + f, fieldnames=["set", "model", "task", "condition", "accuracy", "n", "n_correct"] + ) + w.writeheader() + w.writerows(all_rows) + + lines = [ + "# VLM evaluation results", + "", + f"> Generated {date.today().isoformat()} from `{split}` · accuracy (%) · " + "three zero-shot tasks × four image conditions × three models.", + "", + "**Reporting set.** Every number below is computed on the **same fixed cases** — the " + f"`{split}` split: only cases that have **all four image conditions** (plain, bbox, " + "contour, bbox_contour), so every model/condition/task is scored on an identical N and " + "the columns are directly comparable. Accuracy = mean(`prediction == ground_truth`); " + "the case key is the canonical slice uid (not the `case_id` index).", + "", + f"- **Synthetic:** N = **{ns['synthetic']:,}** cases · **Real:** N = **{ns['real']:,}** cases", + "- Chance: presence 50% · lobe (5-class) 20% · size (4-class) 25%", + "", + ] + for set_name, n, rows in sections: + lines += [f"## {set_name.capitalize()} (N = {n:,})", "", _md_table(rows), ""] + lines += [ + "## Notes", + "", + "- Split, checksums, and provenance: `vlm_dataset/splits/` (`splits.json`).", + "- Reproduce: `python -m itrialspace.evaluation.vlm_eval.report --data-base " + f"$ITRIALSPACE_DATA_DIR/vlm_dataset --split {split} --out {out_md}`.", + "- The conference submission reported synthetic N = 42,382 on the plain set; this report " + "uses the all-conditions split for strict apples-to-apples condition comparison.", + "", + ] + Path(out_md).parent.mkdir(parents=True, exist_ok=True) + Path(out_md).write_text("\n".join(lines)) + print(f"[report] {out_md} (synthetic N={ns['synthetic']:,}, real N={ns['real']:,})") + if out_csv: + print(f"[report] {out_csv}") + + +def main(): + ap = argparse.ArgumentParser(description="VLM evaluation report on a fixed split.") + ap.add_argument("--data-base", required=True, help="Path to vlm_dataset/.") + ap.add_argument( + "--split", default="release_v1_full", help="Split name (default: release_v1_full)." + ) + ap.add_argument("--out", required=True, help="Output markdown report path.") + ap.add_argument("--out-csv", default=None, help="Optional tidy CSV path.") + args = ap.parse_args() + write_report(args.data_base, args.split, args.out, args.out_csv) + + +if __name__ == "__main__": + main() diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/run_all.py b/itrialspace/src/itrialspace/evaluation/vlm_eval/run_all.py new file mode 100644 index 0000000000000000000000000000000000000000..b2a5a0c3b4271253e3a349b87e2ab9f01c149e4d --- /dev/null +++ b/itrialspace/src/itrialspace/evaluation/vlm_eval/run_all.py @@ -0,0 +1,208 @@ +""" +End-to-end convenience runner: build dataset -> infer -> metrics -> plots. + +Supports multiple models via --model flag. + +Usage: + python -m itrialspace.evaluation.vlm_eval.run_all \ + --manifest /path/to/mode1/manifest.csv \ + --manifest /path/to/mode2/manifest.csv \ + --output-dir outputs/vlm_eval \ + --model biomedclip + + python -m itrialspace.evaluation.vlm_eval.run_all \ + --manifest /path/to/mode1/manifest.csv \ + --output-dir outputs/vlm_eval \ + --model llava_med +""" + +from __future__ import annotations + +import argparse +import logging +import os +import sys +from typing import List, Optional + +from itrialspace.evaluation.vlm_eval.build_dataset import build_dataset + +logger = logging.getLogger(__name__) + + +SUPPORTED_MODELS = ["biomedclip", "llava_med"] + + +def run_all( + manifest_paths: List[str], + output_dir: str, + model_name: str = "biomedclip", + task_names: Optional[List[str]] = None, + device: Optional[str] = None, + cache_dir: Optional[str] = None, + ct_base: str = os.path.join( + os.environ.get("ITRIALSPACE_OUTPUT_DIR") + or os.environ.get("ITRIALSPACE_DATA_DIR") + or os.path.expanduser("~/.itrialspace/data"), + "generated_cts", + ), + mask_base: str = os.path.join( + os.environ.get("ITRIALSPACE_OUTPUT_DIR") + or os.environ.get("ITRIALSPACE_DATA_DIR") + or os.path.expanduser("~/.itrialspace/data"), + "inserted_masks", + ), + max_cases: Optional[int] = None, + save_overlay: bool = False, +): + """Run the full pipeline: build dataset, infer, evaluate.""" + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s %(name)-30s %(levelname)-8s %(message)s", + ) + + # Step 1: Build evaluation dataset + logger.info("STEP 1: Building evaluation dataset") + dataset_dir = os.path.join(output_dir, "dataset") + eval_df = build_dataset( + manifest_paths=manifest_paths, + output_dir=dataset_dir, + ct_base=ct_base, + mask_base=mask_base, + max_cases=max_cases, + save_overlay=save_overlay, + ) + + if eval_df.empty: + logger.error("No cases in eval dataset. Check manifest paths and CT paths.") + sys.exit(1) + + dataset_csv = os.path.join(dataset_dir, "eval_dataset.csv") + + # Step 2: Run model-specific inference + metrics + plots + logger.info("STEP 2: Running %s inference", model_name) + + if model_name == "biomedclip": + from itrialspace.evaluation.vlm_eval.run_biomedclip import run_biomedclip + + results_dir = os.path.join(output_dir, "biomedclip") + all_metrics = run_biomedclip( + dataset_csv=dataset_csv, + output_dir=results_dir, + task_names=task_names, + device=device, + cache_dir=cache_dir, + ) + elif model_name == "llava_med": + from itrialspace.evaluation.vlm_eval.runners.run_llava_med import run_llava_med + + results_dir = os.path.join(output_dir, "llava_med") + all_metrics = run_llava_med( + dataset_csv=dataset_csv, + output_dir=results_dir, + task_names=task_names, + device=device, + cache_dir=cache_dir, + max_cases=max_cases, + ) + else: + logger.error("Unknown model '%s'. Supported: %s", model_name, SUPPORTED_MODELS) + sys.exit(1) + + # Summary + logger.info("SUMMARY (%s)", model_name) + if all_metrics: + for task_name, metrics in all_metrics.items(): + logger.info( + " %-12s accuracy=%.4f (n=%d)", + task_name, + metrics["accuracy"], + metrics["n_samples"], + ) + + logger.info("All outputs in: %s", output_dir) + + +# ── CLI ────────────────────────────────────────────────────────────────────── + + +def main(): + from itrialspace.evaluation.vlm_eval.prompt_templates import ALL_TASKS + + parser = argparse.ArgumentParser( + description="End-to-end VLM evaluation: build -> infer -> evaluate.", + ) + parser.add_argument( + "--manifest", + action="append", + required=True, + dest="manifests", + help="Path to manifest CSV (can be repeated).", + ) + parser.add_argument( + "--output-dir", + required=True, + help="Root output directory for all artifacts.", + ) + parser.add_argument( + "--model", + default="biomedclip", + choices=SUPPORTED_MODELS, + help="Model to run. Default: biomedclip.", + ) + parser.add_argument( + "--tasks", + nargs="+", + default=None, + choices=list(ALL_TASKS.keys()), + help="Task(s) to evaluate. Default: all.", + ) + parser.add_argument("--device", default=None, help="PyTorch device.") + parser.add_argument("--cache-dir", default=None, help="HuggingFace cache dir.") + parser.add_argument( + "--ct-base", + default=os.path.join( + os.environ.get("ITRIALSPACE_OUTPUT_DIR") + or os.environ.get("ITRIALSPACE_DATA_DIR") + or os.path.expanduser("~/.itrialspace/data"), + "generated_cts", + ), + ) + parser.add_argument( + "--mask-base", + default=os.path.join( + os.environ.get("ITRIALSPACE_OUTPUT_DIR") + or os.environ.get("ITRIALSPACE_DATA_DIR") + or os.path.expanduser("~/.itrialspace/data"), + "inserted_masks", + ), + ) + parser.add_argument( + "--max-cases", + type=int, + default=None, + help="Limit total cases for quick testing.", + ) + parser.add_argument( + "--save-overlay", + action="store_true", + default=False, + help="Save QC overlay PNGs (lesion mask outline on CT slice).", + ) + args = parser.parse_args() + + run_all( + manifest_paths=args.manifests, + output_dir=args.output_dir, + model_name=args.model, + task_names=args.tasks, + device=args.device, + cache_dir=args.cache_dir, + ct_base=args.ct_base, + mask_base=args.mask_base, + max_cases=args.max_cases, + save_overlay=args.save_overlay, + ) + + +if __name__ == "__main__": + main() diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/run_biomedclip.py b/itrialspace/src/itrialspace/evaluation/vlm_eval/run_biomedclip.py new file mode 100644 index 0000000000000000000000000000000000000000..263da4430d340389c79b747088dd68d650a3291e --- /dev/null +++ b/itrialspace/src/itrialspace/evaluation/vlm_eval/run_biomedclip.py @@ -0,0 +1,360 @@ +""" +Run BiomedCLIP inference on an evaluation dataset for one or more tasks. + +Produces per-mode result directories: + output_dir/ + mode1_controlled_prevalence/ + presence_results.csv + lobe_results.csv + size_results.csv + summary.json + plots/ + mode2_size_detection_curve/ + ... + aggregate/ + summary.json + plots/ + +Usage: + python -m itrialspace.evaluation.vlm_eval.run_biomedclip \\ + --dataset-csv outputs/eval_dataset.csv \\ + --output-dir outputs/biomedclip \\ + --tasks presence lobe size +""" + +from __future__ import annotations + +import argparse +import json +import logging +import os +import time +from pathlib import Path +from typing import Dict, List, Optional + +import pandas as pd + +from itrialspace.evaluation.vlm_eval.biomedclip_model import BiomedCLIPModel +from itrialspace.evaluation.vlm_eval.inference_cache import load_cached_results, merge_results +from itrialspace.evaluation.vlm_eval.metrics import ( + compute_binary_metrics, + compute_grouped_accuracy, + compute_multiclass_metrics, +) +from itrialspace.evaluation.vlm_eval.plots import ( + plot_accuracy_bar, + plot_confusion_matrix, + plot_grouped_accuracy, +) +from itrialspace.evaluation.vlm_eval.prompt_templates import ALL_TASKS, TaskDefinition, get_task + +_BATCH_SIZE = 64 + +logger = logging.getLogger(__name__) + + +def run_task( + model: BiomedCLIPModel, + df: pd.DataFrame, + task: TaskDefinition, + output_dir: str, + skip_existing: bool = False, +) -> pd.DataFrame: + """Run inference for a single task across all rows in the eval dataset. + + Parameters + ---------- + model : BiomedCLIPModel + df : pd.DataFrame + Must contain columns: png_path, and task.manifest_column for GT. + task : TaskDefinition + output_dir : str + skip_existing : bool + If True, reuse results from a prior run for unchanged rows. + + Returns + ------- + pd.DataFrame + Results with predictions, scores, and correctness. + """ + os.makedirs(output_dir, exist_ok=True) + + cached_df = None + if skip_existing: + cached_df, df = load_cached_results(output_dir, task.name, df) + if df.empty: + logger.info(" %s: all %d rows cached, skipping inference", task.name, len(cached_df)) + return cached_df + + labels = task.labels + texts = task.texts + gt_col = task.manifest_column + + # Pre-filter rows with valid PNGs for batching + valid_rows = [] + for idx, row in df.iterrows(): + png_path = row["png_path"] + if not os.path.isfile(png_path): + print(f" WARN: missing PNG {png_path}, skipping") + continue + valid_rows.append(row) + + results = [] + t0 = time.time() + + # Process in batches + for batch_start in range(0, len(valid_rows), _BATCH_SIZE): + batch = valid_rows[batch_start : batch_start + _BATCH_SIZE] + batch_paths = [row["png_path"] for row in batch] + + batch_predictions = model.predict_batch(batch_paths, labels, texts, batch_size=_BATCH_SIZE) + + for row, (best_label, scores) in zip(batch, batch_predictions): + gt_label = str(row.get(gt_col, "")) + result = { + "case_id": row["case_id"], + "mode": row.get("mode", row.get("dataset", "")), + "image_path": row["png_path"], + "task": task.name, + "prediction": best_label, + "ground_truth": gt_label, + "correct": best_label == gt_label, + } + for lbl, score in zip(labels, scores): + result[f"score_{lbl}"] = float(score) + results.append(result) + + done = min(batch_start + _BATCH_SIZE, len(valid_rows)) + elapsed = time.time() - t0 + print(f" [{task.name}] {done} / {len(valid_rows)} ({elapsed:.1f}s)") + + result_df = pd.DataFrame(results) + result_df = merge_results(cached_df, result_df) + csv_path = os.path.join(output_dir, f"{task.name}_results.csv") + result_df.to_csv(csv_path, index=False) + print(f" {task.name}: {len(result_df)} results -> {csv_path}") + return result_df + + +def evaluate_and_plot( + result_df: pd.DataFrame, + task: TaskDefinition, + output_dir: str, +) -> Dict: + """Compute metrics and generate plots for a completed task.""" + plots_dir = os.path.join(output_dir, "plots") + os.makedirs(plots_dir, exist_ok=True) + + y_true = result_df["ground_truth"].tolist() + y_pred = result_df["prediction"].tolist() + + if task.name == "presence": + metrics = compute_binary_metrics(y_true, y_pred, positive_label="present") + cm_labels = ["present", "absent"] + else: + cm_labels = task.labels + metrics = compute_multiclass_metrics(y_true, y_pred, labels=cm_labels) + + # Confusion matrix plot + plot_confusion_matrix( + cm=metrics["confusion_matrix"], + labels=cm_labels, + title=f"BiomedCLIP – {task.name} confusion matrix", + output_path=Path(plots_dir) / f"{task.name}_confusion_matrix.png", + ) + + # Grouped accuracy by mode (if mode column exists) + if "mode" in result_df.columns and result_df["mode"].nunique() > 1: + grouped = compute_grouped_accuracy(result_df, "prediction", "ground_truth", "mode") + metrics["accuracy_by_mode"] = grouped + plot_grouped_accuracy( + grouped, + group_name="Mode", + title=f"BiomedCLIP – {task.name} accuracy by mode", + output_path=Path(plots_dir) / f"{task.name}_accuracy_by_mode.png", + ) + + return metrics + + +def run_biomedclip( + dataset_csv: str, + output_dir: str, + task_names: Optional[List[str]] = None, + device: Optional[str] = None, + cache_dir: Optional[str] = None, + skip_existing: bool = False, + case_ids: Optional[str] = None, +) -> Dict[str, Dict]: + """Full inference + evaluation pipeline with per-mode output. + + Parameters + ---------- + case_ids : str, optional + Path to a frozen split file (see ``splits.py``). If given, only cases + whose canonical uid is in the split are scored -- use it to reproduce a + published result on exactly its case set. + + Returns + ------- + dict + task_name -> aggregate metrics dict + """ + df = pd.read_csv(dataset_csv) + logger.info("Eval dataset: %d rows from %s", len(df), dataset_csv) + if case_ids: + from itrialspace.evaluation.vlm_eval.splits import filter_to_split + + n0 = len(df) + df = filter_to_split(df, case_ids) + logger.info("Restricted to split %s: %d / %d rows", case_ids, len(df), n0) + + if task_names is None: + task_names = list(ALL_TASKS.keys()) + + model = BiomedCLIPModel(device=device, cache_dir=cache_dir) + + # Run inference on the full dataset (tasks x all cases) + full_results: Dict[str, pd.DataFrame] = {} + for tname in task_names: + task = get_task(tname) + logger.info("Task: %s (%s)", task.name, task.description) + result_df = run_task(model, df, task, output_dir, skip_existing=skip_existing) + full_results[tname] = result_df + + # ── Per-mode output ────────────────────────────────────────────────── + aggregate_metrics: Dict[str, Dict] = {} + + # result DFs always have "mode" (populated from dataset col for real CTs) + first_results = next((v for v in full_results.values() if not v.empty), None) + if ( + first_results is not None + and "mode" in first_results.columns + and first_results["mode"].str.len().any() + ): + modes = sorted(first_results["mode"].unique()) + else: + modes = [] + + for mode_name in modes: + mode_dir = os.path.join(output_dir, mode_name) + os.makedirs(mode_dir, exist_ok=True) + logger.info("Writing per-mode results: %s", mode_name) + + mode_metrics: Dict[str, Dict] = {} + for tname in task_names: + task = get_task(tname) + mode_results = full_results[tname] + if mode_results.empty: + continue + mode_slice = mode_results[mode_results["mode"] == mode_name].copy() + if mode_slice.empty: + continue + + # Save per-mode results CSV + csv_path = os.path.join(mode_dir, f"{tname}_results.csv") + mode_slice.to_csv(csv_path, index=False) + + # Per-mode metrics and plots + metrics = evaluate_and_plot(mode_slice, task, mode_dir) + mode_metrics[tname] = metrics + + # Per-mode summary + summary_path = os.path.join(mode_dir, "summary.json") + with open(summary_path, "w") as f: + json.dump(mode_metrics, f, indent=2, default=str) + + # ── Aggregate output ───────────────────────────────────────────────── + agg_dir = os.path.join(output_dir, "aggregate") + os.makedirs(agg_dir, exist_ok=True) + + for tname in task_names: + task = get_task(tname) + result_df = full_results[tname] + if result_df.empty: + continue + + # Full results CSV + csv_path = os.path.join(agg_dir, f"{tname}_results.csv") + result_df.to_csv(csv_path, index=False) + + metrics = evaluate_and_plot(result_df, task, agg_dir) + aggregate_metrics[tname] = metrics + logger.info(" %s aggregate accuracy: %.4f", tname, metrics["accuracy"]) + + # Accuracy bar chart + accs = {t: m["accuracy"] for t, m in aggregate_metrics.items()} + if accs: + plot_accuracy_bar( + accs, + title="BiomedCLIP – Accuracy by Task (aggregate)", + output_path=Path(agg_dir) / "plots" / "accuracy_by_task.png", + ) + + # Aggregate summary + summary_path = os.path.join(agg_dir, "summary.json") + with open(summary_path, "w") as f: + json.dump(aggregate_metrics, f, indent=2, default=str) + logger.info("Summary -> %s", summary_path) + + return aggregate_metrics + + +# ── CLI ────────────────────────────────────────────────────────────────────── + + +def main(): + parser = argparse.ArgumentParser( + description="Run BiomedCLIP inference on an iTrialSpace eval dataset.", + ) + parser.add_argument( + "--dataset-csv", + required=True, + help="Path to eval_dataset.csv from build_dataset.", + ) + parser.add_argument( + "--output-dir", + required=True, + help="Directory for result CSVs, plots, and summary.", + ) + parser.add_argument( + "--tasks", + nargs="+", + default=None, + choices=list(ALL_TASKS.keys()), + help="Task(s) to evaluate. Default: all tasks.", + ) + parser.add_argument( + "--device", + default=None, + help="PyTorch device (e.g. cuda, cpu). Auto-detected if omitted.", + ) + parser.add_argument( + "--cache-dir", + default=None, + help="HuggingFace cache directory.", + ) + parser.add_argument( + "--skip-existing", + action="store_true", + help="Reuse results from a prior run for unchanged rows.", + ) + parser.add_argument( + "--case-ids", + default=None, + help="Frozen split file (e.g. splits/release_v1.synthetic.txt): score only these cases.", + ) + args = parser.parse_args() + run_biomedclip( + dataset_csv=args.dataset_csv, + output_dir=args.output_dir, + task_names=args.tasks, + device=args.device, + cache_dir=args.cache_dir, + skip_existing=args.skip_existing, + case_ids=args.case_ids, + ) + + +if __name__ == "__main__": + main() diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/runners/__init__.py b/itrialspace/src/itrialspace/evaluation/vlm_eval/runners/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/runners/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/evaluation/vlm_eval/runners/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1d79617b899849c2dce69d421926d53b83a61b21 Binary files /dev/null and b/itrialspace/src/itrialspace/evaluation/vlm_eval/runners/__pycache__/__init__.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/runners/__pycache__/run_conditions.cpython-310.pyc b/itrialspace/src/itrialspace/evaluation/vlm_eval/runners/__pycache__/run_conditions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..88abe668403665a722dbec3871b3a26233b07c50 Binary files /dev/null and b/itrialspace/src/itrialspace/evaluation/vlm_eval/runners/__pycache__/run_conditions.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/runners/__pycache__/run_llava_med.cpython-310.pyc b/itrialspace/src/itrialspace/evaluation/vlm_eval/runners/__pycache__/run_llava_med.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9c86b828195a5886b71eb95171b8ee13a82a1b92 Binary files /dev/null and b/itrialspace/src/itrialspace/evaluation/vlm_eval/runners/__pycache__/run_llava_med.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/runners/__pycache__/run_medgemma.cpython-310.pyc b/itrialspace/src/itrialspace/evaluation/vlm_eval/runners/__pycache__/run_medgemma.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..02b4a5ce6697deef9a42c21b5a684fc165ad9c12 Binary files /dev/null and b/itrialspace/src/itrialspace/evaluation/vlm_eval/runners/__pycache__/run_medgemma.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/runners/run_conditions.py b/itrialspace/src/itrialspace/evaluation/vlm_eval/runners/run_conditions.py new file mode 100644 index 0000000000000000000000000000000000000000..571278947123553ff4613c888836579a9608e4a9 --- /dev/null +++ b/itrialspace/src/itrialspace/evaluation/vlm_eval/runners/run_conditions.py @@ -0,0 +1,370 @@ +""" +Run VLM inference under different image presentation conditions. + +Wraps the existing per-model runners (BiomedCLIP, LLaVA-Med, MedGemma) and +remaps the image path column in the dataset CSV to point to the appropriate +overlay variant before invoking the runner. + +Image conditions: + plain — original extracted slice (default, existing behaviour) + bbox — plain slice + bounding-box overlay + contour — plain slice + segmentation contour overlay + bbox_contour — plain slice + both overlays + +Usage +----- + +Single condition: + python -m itrialspace.evaluation.vlm_eval.runners.run_conditions \\ + --model biomedclip \\ + --dataset-csv outputs/vlm_eval/lung_axial/eval_dataset.csv \\ + --output-dir outputs/vlm_eval/lung_axial/biomedclip \\ + --image-condition bbox + +All conditions: + python -m itrialspace.evaluation.vlm_eval.runners.run_conditions \\ + --model biomedclip \\ + --dataset-csv outputs/vlm_eval/lung_axial/eval_dataset.csv \\ + --output-dir outputs/vlm_eval/lung_axial/biomedclip \\ + --run-all-conditions +""" + +from __future__ import annotations + +import argparse +import logging +import os +from typing import Dict, List, Optional + +import pandas as pd + +from itrialspace.evaluation.vlm_eval.overlay import VALID_CONDITIONS +from itrialspace.evaluation.vlm_eval.prompt_templates import ALL_TASKS + +logger = logging.getLogger(__name__) + +# Column mapping: condition -> column in eval_dataset.csv +_CONDITION_COLUMNS = { + "plain": "png_path", + "bbox": "png_bbox_path", + "contour": "png_contour_path", + "bbox_contour": "png_bbox_contour_path", +} + + +def _prepare_condition_csv( + dataset_csv: str, + condition: str, + output_dir: str, + case_ids: Optional[str] = None, +) -> Optional[str]: + """Create a copy of the dataset CSV with png_path remapped to the condition column. + + Rows where the condition image is missing are dropped. If ``case_ids`` (a + frozen split file) is given, the dataset is first restricted to that case set. + Returns the path to the new CSV, or None if no valid rows. + """ + df = pd.read_csv(dataset_csv) + + if case_ids: + from itrialspace.evaluation.vlm_eval.splits import filter_to_split + + n0 = len(df) + df = filter_to_split(df, case_ids) + logger.info("Restricted to split %s: %d / %d rows", case_ids, len(df), n0) + + source_col = _CONDITION_COLUMNS.get(condition) + if source_col is None: + raise ValueError( + f"Unknown condition '{condition}'. " f"Valid: {list(_CONDITION_COLUMNS.keys())}" + ) + + if condition == "plain": + if not case_ids: + # No remapping or filtering needed — png_path already points to the plain slice + return dataset_csv + # Filtered plain set — write it out so the runner reads the restricted cases + os.makedirs(output_dir, exist_ok=True) + out_csv = os.path.join(output_dir, "eval_dataset_plain.csv") + df.to_csv(out_csv, index=False) + logger.info("Condition CSV: %s (%d rows)", out_csv, len(df)) + return out_csv + + if source_col not in df.columns: + logger.error( + "Column '%s' not found in dataset CSV. " "Did you run build_dataset with --overlays?", + source_col, + ) + return None + + # Filter to rows where the overlay exists + valid_mask = df[source_col].notna() & (df[source_col].astype(str).str.len() > 0) + valid_df = df[valid_mask].copy() + + if valid_df.empty: + logger.warning("No valid rows for condition '%s'", condition) + return None + + n_dropped = len(df) - len(valid_df) + if n_dropped > 0: + logger.info( + "Condition '%s': dropped %d/%d rows (missing overlay)", + condition, + n_dropped, + len(df), + ) + + # Remap png_path to the condition-specific path + valid_df["png_path_original"] = valid_df["png_path"] + valid_df["png_path"] = valid_df[source_col] + valid_df["image_condition"] = condition + + os.makedirs(output_dir, exist_ok=True) + out_csv = os.path.join(output_dir, f"eval_dataset_{condition}.csv") + valid_df.to_csv(out_csv, index=False) + logger.info("Condition CSV: %s (%d rows)", out_csv, len(valid_df)) + return out_csv + + +def _run_model( + model_name: str, + dataset_csv: str, + output_dir: str, + task_names: Optional[List[str]] = None, + device: Optional[str] = None, + cache_dir: Optional[str] = None, + max_cases: Optional[int] = None, + skip_existing: bool = False, + **extra_kwargs, +) -> Dict: + """Dispatch to the appropriate model runner.""" + if model_name == "biomedclip": + from itrialspace.evaluation.vlm_eval.run_biomedclip import run_biomedclip + + return run_biomedclip( + dataset_csv=dataset_csv, + output_dir=output_dir, + task_names=task_names, + device=device, + cache_dir=cache_dir, + skip_existing=skip_existing, + ) + elif model_name == "llava_med": + from itrialspace.evaluation.vlm_eval.runners.run_llava_med import run_llava_med + + return run_llava_med( + dataset_csv=dataset_csv, + output_dir=output_dir, + task_names=task_names, + device=device, + cache_dir=cache_dir, + max_cases=max_cases, + skip_existing=skip_existing, + **{ + k: v + for k, v in extra_kwargs.items() + if k in ("model_id", "torch_dtype", "max_new_tokens") + }, + ) + elif model_name == "medgemma": + from itrialspace.evaluation.vlm_eval.runners.run_medgemma import run_medgemma + + return run_medgemma( + dataset_csv=dataset_csv, + output_dir=output_dir, + task_names=task_names, + device=device, + cache_dir=cache_dir, + max_cases=max_cases, + skip_existing=skip_existing, + **{ + k: v + for k, v in extra_kwargs.items() + if k in ("model_id", "torch_dtype", "max_new_tokens") + }, + ) + else: + raise ValueError( + f"Unknown model '{model_name}'. " f"Valid: biomedclip, llava_med, medgemma" + ) + + +def run_with_conditions( + model_name: str, + dataset_csv: str, + output_dir: str, + conditions: List[str], + task_names: Optional[List[str]] = None, + device: Optional[str] = None, + cache_dir: Optional[str] = None, + max_cases: Optional[int] = None, + skip_existing: bool = False, + case_ids: Optional[str] = None, + **extra_kwargs, +) -> Dict[str, Dict]: + """Run a model across multiple image conditions. + + Output structure: + output_dir/ + plain/ + {mode}/ ... + aggregate/ ... + bbox/ + {mode}/ ... + aggregate/ ... + contour/ + ... + + Returns + ------- + dict + condition_name -> task_metrics dict + """ + all_results = {} + + for condition in conditions: + print(f"\n{'='*60}") + print(f" Condition: {condition}") + print(f"{'='*60}\n") + + cond_output_dir = os.path.join(output_dir, condition) + + cond_csv = _prepare_condition_csv( + dataset_csv, condition, cond_output_dir, case_ids=case_ids + ) + if cond_csv is None: + logger.warning("Skipping condition '%s' (no valid data)", condition) + continue + + metrics = _run_model( + model_name=model_name, + dataset_csv=cond_csv, + output_dir=cond_output_dir, + task_names=task_names, + device=device, + cache_dir=cache_dir, + max_cases=max_cases, + skip_existing=skip_existing, + **extra_kwargs, + ) + all_results[condition] = metrics + + return all_results + + +# ── CLI ────────────────────────────────────────────────────────────────────── + + +def main(): + parser = argparse.ArgumentParser( + description=( + "Run VLM inference under different image presentation conditions " + "(plain / bbox / contour / bbox_contour)." + ), + ) + parser.add_argument( + "--model", + required=True, + choices=["biomedclip", "llava_med", "medgemma"], + help="Which model to run.", + ) + parser.add_argument( + "--dataset-csv", + required=True, + help="Path to eval_dataset.csv (must have overlay columns if not plain).", + ) + parser.add_argument( + "--output-dir", + required=True, + help="Root output directory. Sub-dirs created per condition.", + ) + parser.add_argument( + "--image-condition", + nargs="+", + choices=list(VALID_CONDITIONS), + default=None, + help="Image condition(s) to evaluate. Default: plain.", + ) + parser.add_argument( + "--run-all-conditions", + action="store_true", + help="Run all conditions: plain, bbox, contour, bbox_contour.", + ) + parser.add_argument( + "--tasks", + nargs="+", + default=None, + choices=list(ALL_TASKS.keys()), + help="Task(s) to evaluate. Default: all.", + ) + parser.add_argument("--device", default=None, help="PyTorch device.") + parser.add_argument("--cache-dir", default=None, help="HF cache directory.") + parser.add_argument( + "--max-cases", + type=int, + default=None, + help="Limit total cases (smoke test).", + ) + parser.add_argument( + "--torch-dtype", + default=None, + choices=["float16", "bfloat16", "float32"], + ) + parser.add_argument( + "--max-new-tokens", + type=int, + default=64, + ) + parser.add_argument( + "--skip-existing", + action="store_true", + help="Reuse inference results from prior runs for unchanged rows.", + ) + parser.add_argument( + "--case-ids", + default=None, + help="Frozen split file (e.g. splits/release_v1.synthetic.txt): score only these cases.", + ) + args = parser.parse_args() + + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s %(levelname)s %(name)s: %(message)s", + ) + + if args.run_all_conditions: + conditions = list(VALID_CONDITIONS) + elif args.image_condition: + conditions = args.image_condition + else: + conditions = ["plain"] + + results = run_with_conditions( + model_name=args.model, + dataset_csv=args.dataset_csv, + output_dir=args.output_dir, + conditions=conditions, + task_names=args.tasks, + device=args.device, + cache_dir=args.cache_dir, + max_cases=args.max_cases, + skip_existing=args.skip_existing, + case_ids=args.case_ids, + torch_dtype=args.torch_dtype, + max_new_tokens=args.max_new_tokens, + ) + + # Print summary + print("\n" + "=" * 60) + print(" CONDITION SUMMARY") + print("=" * 60) + for cond, metrics in results.items(): + print(f"\n {cond}:") + for task, m in metrics.items(): + acc = m.get("accuracy", 0) + n = m.get("n_samples", 0) + print(f" {task}: accuracy={acc:.4f} (n={n})") + + +if __name__ == "__main__": + main() diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/runners/run_llava_med.py b/itrialspace/src/itrialspace/evaluation/vlm_eval/runners/run_llava_med.py new file mode 100644 index 0000000000000000000000000000000000000000..bf56d4be53b042529fc756f1fc722ec43c1de1ca --- /dev/null +++ b/itrialspace/src/itrialspace/evaluation/vlm_eval/runners/run_llava_med.py @@ -0,0 +1,383 @@ +""" +Run LLaVA-Med inference on an evaluation dataset for one or more tasks. + +Reuses the shared evaluation dataset, task definitions, metrics, and plots +from the vlm_evaluation framework. The key difference from the BiomedCLIP +runner is that LLaVA-Med is *generative*: it produces free-text answers that +are normalised into canonical labels via ``parsers.py``. + +Usage +----- + python -m itrialspace.evaluation.vlm_eval.runners.run_llava_med \\ + --dataset-csv outputs/vlm_eval/dataset/eval_dataset.csv \\ + --output-dir outputs/vlm_eval/llava_med \\ + --tasks presence lobe size + +Smoke test (50 cases): + python -m itrialspace.evaluation.vlm_eval.runners.run_llava_med \\ + --dataset-csv outputs/vlm_eval/dataset/eval_dataset.csv \\ + --output-dir outputs/vlm_eval/llava_med_smoke \\ + --max-cases 50 +""" + +from __future__ import annotations + +import argparse +import json +import logging +import os +import time +from pathlib import Path +from typing import Dict, List, Optional + +import pandas as pd + +logger = logging.getLogger(__name__) + +from itrialspace.evaluation.vlm_eval.inference_cache import load_cached_results, merge_results +from itrialspace.evaluation.vlm_eval.metrics import ( + compute_binary_metrics, + compute_grouped_accuracy, + compute_multiclass_metrics, +) +from itrialspace.evaluation.vlm_eval.models.llava_med import LLaVAMedModel +from itrialspace.evaluation.vlm_eval.parsers import parse_answer +from itrialspace.evaluation.vlm_eval.plots import ( + plot_accuracy_bar, + plot_confusion_matrix, + plot_grouped_accuracy, +) +from itrialspace.evaluation.vlm_eval.prompt_templates import ( + ALL_TASKS, + get_generative_prompt, + get_task, +) + +# ── Per-task inference ─────────────────────────────────────────────────────── + + +def run_task( + model: LLaVAMedModel, + df: pd.DataFrame, + task_name: str, + output_dir: str, + skip_existing: bool = False, +) -> pd.DataFrame: + """Run LLaVA-Med inference for a single task.""" + os.makedirs(output_dir, exist_ok=True) + + cached_df = None + if skip_existing: + cached_df, df = load_cached_results(output_dir, task_name, df) + if df.empty: + logger.info(" %s: all %d rows cached, skipping inference", task_name, len(cached_df)) + return cached_df + + task = get_task(task_name) + question = get_generative_prompt(task_name) + gt_col = task.manifest_column + + results: List[Dict] = [] + t0 = time.time() + + for _, row in df.iterrows(): + png_path = row["png_path"] + gt_label = str(row.get(gt_col, "")) + + if not os.path.isfile(png_path): + print(f" WARN: missing PNG {png_path}, skipping") + continue + + raw_output = model.generate(png_path, question) + parsed = parse_answer(task_name, raw_output) + + results.append( + { + "case_id": row["case_id"], + "mode": row.get("mode", row.get("dataset", "")), + "image_path": png_path, + "task": task_name, + "prompt": question, + "raw_output": raw_output, + "prediction": parsed.label, + "parse_status": parsed.status, + "ground_truth": gt_label, + "correct": parsed.label == gt_label, + } + ) + + if len(results) % 20 == 0: + elapsed = time.time() - t0 + print(f" [{task_name}] {len(results)} / {len(df)} " f"({elapsed:.1f}s)") + + result_df = pd.DataFrame(results) + result_df = merge_results(cached_df, result_df) + csv_path = os.path.join(output_dir, f"{task_name}_results.csv") + result_df.to_csv(csv_path, index=False) + print(f" {task_name}: {len(result_df)} results -> {csv_path}") + return result_df + + +# ── Metrics + plots ────────────────────────────────────────────────────────── + + +def evaluate_and_plot( + result_df: pd.DataFrame, + task_name: str, + output_dir: str, +) -> Dict: + """Compute metrics and generate plots for one task.""" + task = get_task(task_name) + plots_dir = os.path.join(output_dir, "plots") + os.makedirs(plots_dir, exist_ok=True) + + # Filter to successfully parsed rows for metrics + valid = result_df[result_df["parse_status"] == "ok"] + n_unparsed = len(result_df) - len(valid) + + if valid.empty: + return { + "accuracy": 0.0, + "n_samples": 0, + "n_unparsed": n_unparsed, + } + + y_true = valid["ground_truth"].tolist() + y_pred = valid["prediction"].tolist() + + if task_name == "presence": + metrics = compute_binary_metrics(y_true, y_pred, positive_label="present") + cm_labels = ["present", "absent"] + else: + cm_labels = task.labels + metrics = compute_multiclass_metrics(y_true, y_pred, labels=cm_labels) + + metrics["n_unparsed"] = n_unparsed + metrics["parse_rate"] = float(len(valid) / len(result_df)) if len(result_df) > 0 else 0.0 + + # Confusion matrix plot + plot_confusion_matrix( + cm=metrics["confusion_matrix"], + labels=cm_labels, + title=f"LLaVA-Med – {task_name} confusion matrix", + output_path=Path(plots_dir) / f"{task_name}_confusion_matrix.png", + ) + + # Grouped accuracy by mode + if "mode" in valid.columns and valid["mode"].nunique() > 1: + grouped = compute_grouped_accuracy(valid, "prediction", "ground_truth", "mode") + metrics["accuracy_by_mode"] = grouped + plot_grouped_accuracy( + grouped, + group_name="Mode", + title=f"LLaVA-Med – {task_name} accuracy by mode", + output_path=Path(plots_dir) / f"{task_name}_accuracy_by_mode.png", + ) + + return metrics + + +# ── Main pipeline ──────────────────────────────────────────────────────────── + + +def run_llava_med( + dataset_csv: str, + output_dir: str, + task_names: Optional[List[str]] = None, + model_id: Optional[str] = None, + device: Optional[str] = None, + cache_dir: Optional[str] = None, + torch_dtype: Optional[str] = None, + max_new_tokens: int = 64, + max_cases: Optional[int] = None, + skip_existing: bool = False, + case_ids: Optional[str] = None, +) -> Dict[str, Dict]: + """Full LLaVA-Med inference + evaluation pipeline with per-mode output. + + ``case_ids`` (optional): path to a frozen split file (see ``splits.py``); when + set, only cases whose canonical uid is in the split are scored. + """ + df = pd.read_csv(dataset_csv) + logger.info("Eval dataset: %d rows from %s", len(df), dataset_csv) + if case_ids: + from itrialspace.evaluation.vlm_eval.splits import filter_to_split + + n0 = len(df) + df = filter_to_split(df, case_ids) + logger.info("Restricted to split %s: %d / %d rows", case_ids, len(df), n0) + + if max_cases is not None: + df = df.head(max_cases) + logger.info(" Limited to %d cases (--max-cases %d)", len(df), max_cases) + + if task_names is None: + task_names = list(ALL_TASKS.keys()) + + model = LLaVAMedModel( + model_id=model_id, + device=device, + cache_dir=cache_dir, + torch_dtype=torch_dtype, + max_new_tokens=max_new_tokens, + ) + + # Run inference on the full dataset (tasks × all cases) + full_results: Dict[str, pd.DataFrame] = {} + for tname in task_names: + logger.info("Task: %s", tname) + result_df = run_task(model, df, tname, output_dir, skip_existing=skip_existing) + full_results[tname] = result_df + + # ── Per-mode output ────────────────────────────────────────────────── + # result DFs always have "mode" (populated from dataset col for real CTs) + first_results = next((v for v in full_results.values() if not v.empty), None) + if ( + first_results is not None + and "mode" in first_results.columns + and first_results["mode"].str.len().any() + ): + modes = sorted(first_results["mode"].unique()) + else: + modes = [] + + for mode_name in modes: + mode_dir = os.path.join(output_dir, mode_name) + os.makedirs(mode_dir, exist_ok=True) + logger.info("Writing per-mode results: %s", mode_name) + + mode_metrics: Dict[str, Dict] = {} + for tname in task_names: + result_df = full_results[tname] + if result_df.empty: + continue + mode_slice = result_df[result_df["mode"] == mode_name].copy() + if mode_slice.empty: + continue + + csv_path = os.path.join(mode_dir, f"{tname}_results.csv") + mode_slice.to_csv(csv_path, index=False) + + metrics = evaluate_and_plot(mode_slice, tname, mode_dir) + mode_metrics[tname] = metrics + + summary_path = os.path.join(mode_dir, "summary.json") + with open(summary_path, "w") as f: + json.dump(mode_metrics, f, indent=2, default=str) + + # ── Aggregate output ───────────────────────────────────────────────── + agg_dir = os.path.join(output_dir, "aggregate") + os.makedirs(agg_dir, exist_ok=True) + aggregate_metrics: Dict[str, Dict] = {} + + for tname in task_names: + result_df = full_results[tname] + if result_df.empty: + continue + + csv_path = os.path.join(agg_dir, f"{tname}_results.csv") + result_df.to_csv(csv_path, index=False) + + metrics = evaluate_and_plot(result_df, tname, agg_dir) + aggregate_metrics[tname] = metrics + logger.info( + " %s aggregate accuracy: %.4f (parsed: %.1f%%, unparsed: %d)", + tname, + metrics["accuracy"], + metrics.get("parse_rate", 0) * 100, + metrics.get("n_unparsed", 0), + ) + + accs = {t: m["accuracy"] for t, m in aggregate_metrics.items() if m.get("n_samples", 0) > 0} + if accs: + plot_accuracy_bar( + accs, + title="LLaVA-Med – Accuracy by Task (aggregate)", + output_path=Path(agg_dir) / "plots" / "accuracy_by_task.png", + ) + + summary = { + "model": model.model_id, + "max_new_tokens": max_new_tokens, + "tasks": aggregate_metrics, + } + summary_path = os.path.join(agg_dir, "summary.json") + with open(summary_path, "w") as f: + json.dump(summary, f, indent=2, default=str) + logger.info("Summary -> %s", summary_path) + + return aggregate_metrics + + +# ── CLI ────────────────────────────────────────────────────────────────────── + + +def main(): + parser = argparse.ArgumentParser( + description="Run LLaVA-Med inference on an iTrialSpace eval dataset.", + ) + parser.add_argument( + "--dataset-csv", + required=True, + help="Path to eval_dataset.csv from build_dataset.", + ) + parser.add_argument( + "--output-dir", + required=True, + help="Directory for result CSVs, plots, and summary.", + ) + parser.add_argument( + "--tasks", + nargs="+", + default=None, + choices=list(ALL_TASKS.keys()), + help="Task(s) to evaluate. Default: all.", + ) + parser.add_argument( + "--model-id", + default=None, + help="HuggingFace model ID or local path. " f"Default: {LLaVAMedModel.DEFAULT_MODEL_ID}", + ) + parser.add_argument("--device", default=None, help="PyTorch device.") + parser.add_argument("--cache-dir", default=None, help="HF cache directory.") + parser.add_argument( + "--torch-dtype", + default=None, + choices=["float16", "bfloat16", "float32"], + help="Model precision. Default: float16 on GPU, float32 on CPU.", + ) + parser.add_argument( + "--max-new-tokens", + type=int, + default=64, + help="Max tokens to generate per answer.", + ) + parser.add_argument( + "--max-cases", + type=int, + default=None, + help="Limit total cases (smoke test).", + ) + parser.add_argument( + "--case-ids", + default=None, + help="Frozen split file (e.g. splits/release_v1.synthetic.txt): score only these cases.", + ) + args = parser.parse_args() + + run_llava_med( + dataset_csv=args.dataset_csv, + output_dir=args.output_dir, + task_names=args.tasks, + model_id=args.model_id, + device=args.device, + cache_dir=args.cache_dir, + torch_dtype=args.torch_dtype, + max_new_tokens=args.max_new_tokens, + max_cases=args.max_cases, + case_ids=args.case_ids, + ) + + +if __name__ == "__main__": + main() diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/runners/run_medgemma.py b/itrialspace/src/itrialspace/evaluation/vlm_eval/runners/run_medgemma.py new file mode 100644 index 0000000000000000000000000000000000000000..2395e5d372d390f81c347b749e41f7c82bfc80c8 --- /dev/null +++ b/itrialspace/src/itrialspace/evaluation/vlm_eval/runners/run_medgemma.py @@ -0,0 +1,382 @@ +""" +Run MedGemma 1.5 4B inference on an evaluation dataset for one or more tasks. + +Reuses the shared evaluation dataset, task definitions, metrics, and plots +from the vlm_evaluation framework. MedGemma is *generative*: it produces +free-text answers that are normalised into canonical labels via ``parsers.py``. + +Usage +----- + python -m itrialspace.evaluation.vlm_eval.runners.run_medgemma \\ + --dataset-csv outputs/vlm_eval/lung_axial/eval_dataset.csv \\ + --output-dir outputs/vlm_eval/lung_axial/medgemma \\ + --tasks presence lobe size + +Smoke test (50 cases): + python -m itrialspace.evaluation.vlm_eval.runners.run_medgemma \\ + --dataset-csv outputs/vlm_eval/lung_axial/eval_dataset.csv \\ + --output-dir outputs/vlm_eval/lung_axial/medgemma_smoke \\ + --max-cases 50 +""" + +from __future__ import annotations + +import argparse +import json +import logging +import os +import time +from pathlib import Path +from typing import Dict, List, Optional + +import pandas as pd + +logger = logging.getLogger(__name__) + +from itrialspace.evaluation.vlm_eval.inference_cache import load_cached_results, merge_results +from itrialspace.evaluation.vlm_eval.metrics import ( + compute_binary_metrics, + compute_grouped_accuracy, + compute_multiclass_metrics, +) +from itrialspace.evaluation.vlm_eval.models.medgemma import MedGemmaModel +from itrialspace.evaluation.vlm_eval.parsers import parse_answer +from itrialspace.evaluation.vlm_eval.plots import ( + plot_accuracy_bar, + plot_confusion_matrix, + plot_grouped_accuracy, +) +from itrialspace.evaluation.vlm_eval.prompt_templates import ( + ALL_TASKS, + get_generative_prompt, + get_task, +) + +# ── Per-task inference ─────────────────────────────────────────────────────── + + +def run_task( + model: MedGemmaModel, + df: pd.DataFrame, + task_name: str, + output_dir: str, + skip_existing: bool = False, +) -> pd.DataFrame: + """Run MedGemma inference for a single task.""" + os.makedirs(output_dir, exist_ok=True) + + cached_df = None + if skip_existing: + cached_df, df = load_cached_results(output_dir, task_name, df) + if df.empty: + logger.info(" %s: all %d rows cached, skipping inference", task_name, len(cached_df)) + return cached_df + + task = get_task(task_name) + question = get_generative_prompt(task_name) + gt_col = task.manifest_column + + results: List[Dict] = [] + t0 = time.time() + + for _, row in df.iterrows(): + png_path = row["png_path"] + gt_label = str(row.get(gt_col, "")) + + if not os.path.isfile(png_path): + print(f" WARN: missing PNG {png_path}, skipping") + continue + + raw_output = model.generate(png_path, question) + parsed = parse_answer(task_name, raw_output) + + results.append( + { + "case_id": row["case_id"], + "mode": row.get("mode", row.get("dataset", "")), + "image_path": png_path, + "task": task_name, + "prompt": question, + "raw_output": raw_output, + "prediction": parsed.label, + "parse_status": parsed.status, + "ground_truth": gt_label, + "correct": parsed.label == gt_label, + } + ) + + if len(results) % 20 == 0: + elapsed = time.time() - t0 + print(f" [{task_name}] {len(results)} / {len(df)} " f"({elapsed:.1f}s)") + + result_df = pd.DataFrame(results) + result_df = merge_results(cached_df, result_df) + csv_path = os.path.join(output_dir, f"{task_name}_results.csv") + result_df.to_csv(csv_path, index=False) + print(f" {task_name}: {len(result_df)} results -> {csv_path}") + return result_df + + +# ── Metrics + plots ────────────────────────────────────────────────────────── + + +def evaluate_and_plot( + result_df: pd.DataFrame, + task_name: str, + output_dir: str, +) -> Dict: + """Compute metrics and generate plots for one task.""" + task = get_task(task_name) + plots_dir = os.path.join(output_dir, "plots") + os.makedirs(plots_dir, exist_ok=True) + + # Filter to successfully parsed rows for metrics + valid = result_df[result_df["parse_status"] == "ok"] + n_unparsed = len(result_df) - len(valid) + + if valid.empty: + return { + "accuracy": 0.0, + "n_samples": 0, + "n_unparsed": n_unparsed, + } + + y_true = valid["ground_truth"].tolist() + y_pred = valid["prediction"].tolist() + + if task_name == "presence": + metrics = compute_binary_metrics(y_true, y_pred, positive_label="present") + cm_labels = ["present", "absent"] + else: + cm_labels = task.labels + metrics = compute_multiclass_metrics(y_true, y_pred, labels=cm_labels) + + metrics["n_unparsed"] = n_unparsed + metrics["parse_rate"] = float(len(valid) / len(result_df)) if len(result_df) > 0 else 0.0 + + # Confusion matrix plot + plot_confusion_matrix( + cm=metrics["confusion_matrix"], + labels=cm_labels, + title=f"MedGemma – {task_name} confusion matrix", + output_path=Path(plots_dir) / f"{task_name}_confusion_matrix.png", + ) + + # Grouped accuracy by mode + if "mode" in valid.columns and valid["mode"].nunique() > 1: + grouped = compute_grouped_accuracy(valid, "prediction", "ground_truth", "mode") + metrics["accuracy_by_mode"] = grouped + plot_grouped_accuracy( + grouped, + group_name="Mode", + title=f"MedGemma – {task_name} accuracy by mode", + output_path=Path(plots_dir) / f"{task_name}_accuracy_by_mode.png", + ) + + return metrics + + +# ── Main pipeline ──────────────────────────────────────────────────────────── + + +def run_medgemma( + dataset_csv: str, + output_dir: str, + task_names: Optional[List[str]] = None, + model_id: Optional[str] = None, + device: Optional[str] = None, + cache_dir: Optional[str] = None, + torch_dtype: Optional[str] = None, + max_new_tokens: int = 64, + max_cases: Optional[int] = None, + skip_existing: bool = False, + case_ids: Optional[str] = None, +) -> Dict[str, Dict]: + """Full MedGemma inference + evaluation pipeline with per-mode output. + + ``case_ids`` (optional): path to a frozen split file (see ``splits.py``); when + set, only cases whose canonical uid is in the split are scored. + """ + df = pd.read_csv(dataset_csv) + logger.info("Eval dataset: %d rows from %s", len(df), dataset_csv) + if case_ids: + from itrialspace.evaluation.vlm_eval.splits import filter_to_split + + n0 = len(df) + df = filter_to_split(df, case_ids) + logger.info("Restricted to split %s: %d / %d rows", case_ids, len(df), n0) + + if max_cases is not None: + df = df.head(max_cases) + logger.info(" Limited to %d cases (--max-cases %d)", len(df), max_cases) + + if task_names is None: + task_names = list(ALL_TASKS.keys()) + + model = MedGemmaModel( + model_id=model_id, + device=device, + cache_dir=cache_dir, + torch_dtype=torch_dtype, + max_new_tokens=max_new_tokens, + ) + + # Run inference on the full dataset (tasks × all cases) + full_results: Dict[str, pd.DataFrame] = {} + for tname in task_names: + logger.info("Task: %s", tname) + result_df = run_task(model, df, tname, output_dir, skip_existing=skip_existing) + full_results[tname] = result_df + + # ── Per-mode output ────────────────────────────────────────────────── + # result DFs always have "mode" (populated from dataset col for real CTs) + first_results = next((v for v in full_results.values() if not v.empty), None) + if ( + first_results is not None + and "mode" in first_results.columns + and first_results["mode"].str.len().any() + ): + modes = sorted(first_results["mode"].unique()) + else: + modes = [] + + for mode_name in modes: + mode_dir = os.path.join(output_dir, mode_name) + os.makedirs(mode_dir, exist_ok=True) + logger.info("Writing per-mode results: %s", mode_name) + + mode_metrics: Dict[str, Dict] = {} + for tname in task_names: + result_df = full_results[tname] + if result_df.empty: + continue + mode_slice = result_df[result_df["mode"] == mode_name].copy() + if mode_slice.empty: + continue + + csv_path = os.path.join(mode_dir, f"{tname}_results.csv") + mode_slice.to_csv(csv_path, index=False) + + metrics = evaluate_and_plot(mode_slice, tname, mode_dir) + mode_metrics[tname] = metrics + + summary_path = os.path.join(mode_dir, "summary.json") + with open(summary_path, "w") as f: + json.dump(mode_metrics, f, indent=2, default=str) + + # ── Aggregate output ───────────────────────────────────────────────── + agg_dir = os.path.join(output_dir, "aggregate") + os.makedirs(agg_dir, exist_ok=True) + aggregate_metrics: Dict[str, Dict] = {} + + for tname in task_names: + result_df = full_results[tname] + if result_df.empty: + continue + + csv_path = os.path.join(agg_dir, f"{tname}_results.csv") + result_df.to_csv(csv_path, index=False) + + metrics = evaluate_and_plot(result_df, tname, agg_dir) + aggregate_metrics[tname] = metrics + logger.info( + " %s aggregate accuracy: %.4f (parsed: %.1f%%, unparsed: %d)", + tname, + metrics["accuracy"], + metrics.get("parse_rate", 0) * 100, + metrics.get("n_unparsed", 0), + ) + + accs = {t: m["accuracy"] for t, m in aggregate_metrics.items() if m.get("n_samples", 0) > 0} + if accs: + plot_accuracy_bar( + accs, + title="MedGemma – Accuracy by Task (aggregate)", + output_path=Path(agg_dir) / "plots" / "accuracy_by_task.png", + ) + + summary = { + "model": model.model_id, + "max_new_tokens": max_new_tokens, + "tasks": aggregate_metrics, + } + summary_path = os.path.join(agg_dir, "summary.json") + with open(summary_path, "w") as f: + json.dump(summary, f, indent=2, default=str) + logger.info("Summary -> %s", summary_path) + + return aggregate_metrics + + +# ── CLI ────────────────────────────────────────────────────────────────────── + + +def main(): + parser = argparse.ArgumentParser( + description="Run MedGemma 1.5 4B inference on an iTrialSpace eval dataset.", + ) + parser.add_argument( + "--dataset-csv", + required=True, + help="Path to eval_dataset.csv from build_dataset.", + ) + parser.add_argument( + "--output-dir", + required=True, + help="Directory for result CSVs, plots, and summary.", + ) + parser.add_argument( + "--tasks", + nargs="+", + default=None, + choices=list(ALL_TASKS.keys()), + help="Task(s) to evaluate. Default: all.", + ) + parser.add_argument( + "--model-id", + default=None, + help="HuggingFace model ID or local path. " f"Default: {MedGemmaModel.DEFAULT_MODEL_ID}", + ) + parser.add_argument("--device", default=None, help="PyTorch device.") + parser.add_argument("--cache-dir", default=None, help="HF cache directory.") + parser.add_argument( + "--torch-dtype", + default=None, + choices=["float16", "bfloat16", "float32"], + help="Model precision. Default: bfloat16 on GPU, float32 on CPU.", + ) + parser.add_argument( + "--max-new-tokens", + type=int, + default=64, + help="Max tokens to generate per answer.", + ) + parser.add_argument( + "--max-cases", + type=int, + default=None, + help="Limit total cases (smoke test).", + ) + parser.add_argument( + "--case-ids", + default=None, + help="Frozen split file (e.g. splits/release_v1.synthetic.txt): score only these cases.", + ) + args = parser.parse_args() + + run_medgemma( + dataset_csv=args.dataset_csv, + output_dir=args.output_dir, + task_names=args.tasks, + model_id=args.model_id, + device=args.device, + cache_dir=args.cache_dir, + torch_dtype=args.torch_dtype, + max_new_tokens=args.max_new_tokens, + max_cases=args.max_cases, + case_ids=args.case_ids, + ) + + +if __name__ == "__main__": + main() diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/slice_extractor.py b/itrialspace/src/itrialspace/evaluation/vlm_eval/slice_extractor.py new file mode 100644 index 0000000000000000000000000000000000000000..ee07602ed430dffbc9722732c3e7af4afc5d3265 --- /dev/null +++ b/itrialspace/src/itrialspace/evaluation/vlm_eval/slice_extractor.py @@ -0,0 +1,593 @@ +""" +Extract 2D slices from 3D CT volumes for VLM evaluation. + +Slice selection priority: +1. Co-located input_mask.nii.gz label-23 centroid (same geometry as synthetic CT) +2. Inserted mask (_mask.nii.gz) label-23 centroid (needs resampling check) +3. Skip case (no arbitrary middle-slice fallback) + +Supports multiple slice planes (axial, coronal, sagittal), CT windows, and +output formats via PreprocessProfile. +""" + +from __future__ import annotations + +import logging +import os +from dataclasses import dataclass +from typing import Optional, Tuple + +import nibabel as nib +import numpy as np +from PIL import Image + +from itrialspace.evaluation.vlm_eval.preprocess_profiles import ( + PreprocessProfile, +) + +logger = logging.getLogger(__name__) + +# Nodule label in the iTrialSpace combined organ+nodule masks +NODULE_LABEL = 23 + +# Lung CT window: centre -600 HU, width 1500 HU → [-1350, 150] +_DEFAULT_WINDOW_CENTER = -600.0 +_DEFAULT_WINDOW_WIDTH = 1500.0 + + +def _to_radiological(arr_2d: np.ndarray) -> np.ndarray: + """Orient a raw axial slice (X, Y) → radiological display (rows=A→P, cols=R→L). + + Assumes the NIfTI data is in RAS+ orientation (axis-0→R, axis-1→A). + After .T the image rows follow axis-1 (A) and cols follow axis-0 (R). + flipud reverses rows so top = Anterior; fliplr reverses cols so left = Right. + """ + return np.fliplr(np.flipud(arr_2d.T)) + + +# Number of slices on each side of the centre for the mini-stack +_STACK_MARGIN = 1 + + +def _extract_plane_slice( + volume: np.ndarray, + plane: str, + index: int, +) -> np.ndarray: + """Extract a 2D slice from a 3D volume along the given plane. + + Parameters + ---------- + volume : ndarray (X, Y, Z) in RAS+ NIfTI convention + plane : "axial" | "coronal" | "sagittal" + index : slice index along that axis + + Returns + ------- + 2D ndarray (already oriented for radiological display) + """ + if plane == "axial": + return _to_radiological(volume[:, :, index]) + elif plane == "coronal": + # coronal = anterior–posterior axis (axis 1 in RAS) + raw = volume[:, index, :] # (X, Z) + return np.flipud(raw.T) # rows=Z (sup→inf), cols=X (R→L) + elif plane == "sagittal": + # sagittal = right–left axis (axis 0 in RAS) + raw = volume[index, :, :] # (Y, Z) + return np.flipud(raw.T) # rows=Z (sup→inf), cols=Y (A→P) + else: + raise ValueError(f"Unknown slice plane: '{plane}'. Use axial/coronal/sagittal.") + + +@dataclass +class SliceInfo: + """Metadata about how a slice was selected.""" + + center_z: int + method: str # "input_mask" | "inserted_mask" | "skipped" + mask_path: str = "" + n_nodule_voxels: int = 0 + + +def _apply_ct_window( + data: np.ndarray, + center: float = _DEFAULT_WINDOW_CENTER, + width: float = _DEFAULT_WINDOW_WIDTH, +) -> np.ndarray: + """Apply CT windowing and normalise to [0, 255] uint8.""" + lower = center - width / 2.0 + upper = center + width / 2.0 + data = np.clip(data, lower, upper) + data = ((data - lower) / (upper - lower) * 255.0).astype(np.uint8) + return data + + +# MedGemma 1.5 3-channel CT windowing protocol +# Source: https://github.com/Google-Health/medgemma/blob/main/notebooks/high_dimensional_ct_hugging_face.ipynb +_MEDGEMMA_WINDOW_CLIPS = [ + (-1024, 1024), # R: wide + (-135, 215), # G: soft tissue + (0, 80), # B: brain +] + + +def _apply_medgemma_ct_window(data: np.ndarray) -> np.ndarray: + """Apply MedGemma 1.5 3-channel CT windowing. + + Each RGB channel encodes a different HU window: + R = wide (-1024, 1024) + G = soft tissue (-135, 215) + B = brain (0, 80) + + Returns (H, W, 3) uint8 array. + """ + channels = [] + for lo, hi in _MEDGEMMA_WINDOW_CLIPS: + ch = np.clip(data, lo, hi).astype(np.float32) + ch = (ch - lo) / (hi - lo) * 255.0 + channels.append(np.round(ch).astype(np.uint8)) + return np.stack(channels, axis=-1) + + +def _clean_artifact_slices( + mask_data: np.ndarray, + threshold: float = 0.5, + nodule_label: Optional[int] = None, +) -> np.ndarray: + """Zero out artifact slices where the mask fills > *threshold* of the plane. + + Some real CT nodule masks (e.g. NSCLCR, IMDCT) have a last-slice artifact + where the entire z-plane is filled with non-zero values. This corrupts + centroid calculations and overlay generation. + + When *nodule_label* is ``None`` (binary-mask mode), any axial slice whose + total non-zero fraction exceeds *threshold* is zeroed out entirely. + + When *nodule_label* is set (multi-label segmentation mask, e.g. 23 for + nodule), only that label's fill-fraction is checked, and only that label + is zeroed on artifact slices. This prevents dense multi-organ masks from + accidentally wiping small nodule labels. + + Parameters + ---------- + mask_data : ndarray (X, Y, Z) + 3-D mask volume (modified **in-place** and returned). + threshold : float + Fraction of the plane area above which a slice is considered artifact. + nodule_label : int or None + If set, restrict artifact detection and cleaning to this label only. + + Returns + ------- + ndarray + The cleaned mask volume (same object, modified in-place). + """ + plane_area = mask_data.shape[0] * mask_data.shape[1] + for z in range(mask_data.shape[2]): + if nodule_label is None: + # Binary mask: check all non-zero voxels, zero entire slice + if np.count_nonzero(mask_data[:, :, z]) > plane_area * threshold: + logger.debug("Zeroing artifact slice z=%d (>%.0f%% filled)", z, threshold * 100) + mask_data[:, :, z] = 0 + else: + # Multi-label mask: check only the target label + label_count = np.count_nonzero(mask_data[:, :, z] == nodule_label) + if label_count > plane_area * threshold: + logger.debug( + "Zeroing label %d on artifact slice z=%d (>%.0f%% filled)", + nodule_label, + z, + threshold * 100, + ) + mask_data[:, :, z][mask_data[:, :, z] == nodule_label] = 0 + return mask_data + + +def _nodule_centroid_from_mask( + mask_path: str, + nodule_label: Optional[int] = None, +) -> Optional[Tuple[int, int, int]]: + """Return (x, y, z) voxel centroid of the nodule label in a mask, or None. + + Parameters + ---------- + mask_path : str + Path to the mask NIfTI file. + nodule_label : int or None + Label value to threshold. ``None`` means *any non-zero* voxel + (useful for per-nodule binary masks from real CT datasets). + An explicit integer (e.g. 23) selects only that label. + """ + if not mask_path or not os.path.isfile(mask_path): + return None + try: + mask_nii = nib.load(mask_path) + mask_data = nib.as_closest_canonical(mask_nii).get_fdata(dtype=np.float32) + # Remove artifact slices (e.g. full-plane fills) before centroid calc + _clean_artifact_slices(mask_data, nodule_label=nodule_label) + if nodule_label is None: + voxels = np.argwhere(mask_data > 0) + else: + voxels = np.argwhere(mask_data == nodule_label) + if len(voxels) == 0: + return None + cx, cy, cz = voxels.mean(axis=0) + return int(round(cx)), int(round(cy)), int(round(cz)) + except Exception as e: + logger.warning("Failed loading mask %s: %s", mask_path, e) + return None + + +def _resolve_input_mask(ct_path: str) -> Optional[str]: + """Find the input_mask.nii.gz co-located with the synthetic CT. + + This mask is in the same resampled geometry as the synthetic CT + (typically 512x512x256) and contains label 23 for the nodule. + """ + ct_dir = os.path.dirname(ct_path) + input_mask = os.path.join(ct_dir, "input_mask.nii.gz") + if os.path.isfile(input_mask): + return input_mask + return None + + +def extract_slice( + ct_path: str, + output_png: str, + input_mask_path: Optional[str] = None, + inserted_mask_path: Optional[str] = None, + window_center: float = _DEFAULT_WINDOW_CENTER, + window_width: float = _DEFAULT_WINDOW_WIDTH, + save_overlay: bool = False, + profile: Optional[PreprocessProfile] = None, + nodule_label: Optional[int] = NODULE_LABEL, +) -> Optional[SliceInfo]: + """Extract a lesion-centred slice from a CT volume and save. + + Parameters + ---------- + ct_path : str + Path to the 3D synthetic CT NIfTI file. + output_png : str + Where to save the output (PNG or .npy depending on profile). + input_mask_path : str, optional + Path to input_mask.nii.gz (co-located with synthetic CT, same geometry). + This is the preferred source for nodule localisation. + inserted_mask_path : str, optional + Path to the inserted mask (_mask.nii.gz). Used as fallback only if + it has the same shape as the CT. + window_center, window_width : float + CT windowing parameters. Overridden by *profile* if provided. + save_overlay : bool + If True, save a second PNG with the nodule mask overlaid. + Overridden by *profile* if provided. + profile : PreprocessProfile, optional + Full preprocessing profile. When given, its ``window_center``, + ``window_width``, ``save_overlay``, ``slice_plane``, + ``num_context_slices``, and ``output_format`` take precedence over + the individual keyword arguments. + + Returns + ------- + SliceInfo or None + Metadata about the extracted slice, or None if the case was skipped. + """ + # Resolve effective parameters from profile (if any) + if profile is not None: + window_center = profile.window_center + window_width = profile.window_width + save_overlay = profile.save_overlay + slice_plane = profile.slice_plane + num_context = profile.num_context_slices + output_format = profile.output_format + else: + slice_plane = "axial" + num_context = _STACK_MARGIN + output_format = "png_gray" + nii = nib.load(ct_path) + # Reorient to RAS+ canonical so _to_radiological() / _extract_plane_slice() + # produce correct radiological display regardless of native NIfTI orientation. + # Matches retriever/slicer.py convention. + nii = nib.as_closest_canonical(nii) + ct_data = nii.get_fdata(dtype=np.float32) + ct_shape = ct_data.shape + + # Determine which axis corresponds to the requested slice plane + _axis_map = {"axial": 2, "coronal": 1, "sagittal": 0} + slice_axis = _axis_map[slice_plane] + max_idx = ct_shape[slice_axis] - 1 + + # ── Strategy 1: input_mask.nii.gz (co-located, same geometry) ──────── + if input_mask_path is None: + input_mask_path = _resolve_input_mask(ct_path) + + centroid = _nodule_centroid_from_mask(input_mask_path, nodule_label=nodule_label) + if centroid is not None: + center_idx = int(np.clip(centroid[slice_axis], 0, max_idx)) + info = SliceInfo( + center_z=center_idx, + method="input_mask", + mask_path=input_mask_path, + n_nodule_voxels=_count_nodule_voxels(input_mask_path, nodule_label=nodule_label), + ) + logger.info( + "Case %s: %s slice idx=%d via input_mask centroid (%d nodule voxels)", + os.path.basename(output_png), + slice_plane, + center_idx, + info.n_nodule_voxels, + ) + _save_slice_stack( + ct_data, + center_idx, + output_png, + window_center, + window_width, + slice_plane, + num_context, + output_format, + ) + + if save_overlay and input_mask_path: + _save_overlay( + ct_data, + input_mask_path, + center_idx, + output_png, + window_center, + window_width, + slice_plane, + nodule_label=nodule_label, + ) + + return info + + # ── Strategy 2: inserted mask (only if same shape as CT) ───────────── + if inserted_mask_path and os.path.isfile(inserted_mask_path): + try: + imask_nii = nib.load(inserted_mask_path) + if imask_nii.shape == ct_shape: + centroid = _nodule_centroid_from_mask(inserted_mask_path, nodule_label=nodule_label) + if centroid is not None: + center_idx = int(np.clip(centroid[slice_axis], 0, max_idx)) + info = SliceInfo( + center_z=center_idx, + method="inserted_mask", + mask_path=inserted_mask_path, + n_nodule_voxels=_count_nodule_voxels( + inserted_mask_path, nodule_label=nodule_label + ), + ) + logger.info( + "Case %s: %s slice idx=%d via inserted_mask (same shape)", + os.path.basename(output_png), + slice_plane, + center_idx, + ) + _save_slice_stack( + ct_data, + center_idx, + output_png, + window_center, + window_width, + slice_plane, + num_context, + output_format, + ) + if save_overlay: + _save_overlay( + ct_data, + inserted_mask_path, + center_idx, + output_png, + window_center, + window_width, + slice_plane, + nodule_label=nodule_label, + ) + return info + else: + logger.debug( + "Case %s: inserted mask shape %s != CT shape %s, skipping", + os.path.basename(output_png), + imask_nii.shape, + ct_shape, + ) + except Exception as e: + logger.warning("Failed loading inserted mask %s: %s", inserted_mask_path, e) + + # ── No reliable localisation → skip ────────────────────────────────── + logger.warning( + "SKIP %s: no nodule localisation source available (no input_mask, " + "no compatible inserted_mask)", + os.path.basename(output_png), + ) + return None + + +def _count_nodule_voxels( + mask_path: str, + nodule_label: Optional[int] = None, +) -> int: + """Count nodule voxels without keeping full array in memory.""" + try: + data = nib.load(mask_path).get_fdata(dtype=np.float32) + if nodule_label is None: + return int(np.sum(data > 0)) + return int(np.sum(data == nodule_label)) + except Exception: + return 0 + + +def _save_slice_stack( + ct_data: np.ndarray, + center_idx: int, + output_png: str, + window_center: float, + window_width: float, + slice_plane: str = "axial", + num_context: int = _STACK_MARGIN, + output_format: str = "png_gray", +) -> None: + """Save the centre slice (+ optional neighbours) using the requested format.""" + os.makedirs(os.path.dirname(output_png) or ".", exist_ok=True) + _axis_map = {"axial": 2, "coronal": 1, "sagittal": 0} + max_idx = ct_data.shape[_axis_map[slice_plane]] - 1 + + # Centre slice + oriented = _extract_plane_slice(ct_data, slice_plane, center_idx) + + _save_single_slice(oriented, output_png, window_center, window_width, output_format) + + # Context slices (saved alongside for optional multi-slice analysis) + if num_context > 0: + base, ext = os.path.splitext(output_png) + for offset in range(-num_context, num_context + 1): + if offset == 0: + continue + idx = center_idx + offset + if 0 <= idx <= max_idx: + nb_oriented = _extract_plane_slice(ct_data, slice_plane, idx) + suffix_ext = ".npy" if output_format == "npy" else ext + nb_path = f"{base}_z{offset:+d}{suffix_ext}" + _save_single_slice(nb_oriented, nb_path, window_center, window_width, output_format) + + +def _save_single_slice( + oriented: np.ndarray, + out_path: str, + window_center: float, + window_width: float, + output_format: str, +) -> None: + """Window and save one 2D slice in the requested format.""" + if output_format == "png_medgemma_rgb": + rgb = _apply_medgemma_ct_window(oriented) + Image.fromarray(rgb, mode="RGB").save(out_path) + elif output_format == "npy": + img_arr = _apply_ct_window(oriented, window_center, window_width) + npy_path = os.path.splitext(out_path)[0] + ".npy" + np.save(npy_path, img_arr) + elif output_format == "png_rgb": + img_arr = _apply_ct_window(oriented, window_center, window_width) + rgb = np.stack([img_arr, img_arr, img_arr], axis=-1) + Image.fromarray(rgb, mode="RGB").save(out_path) + else: # png_gray (default) + img_arr = _apply_ct_window(oriented, window_center, window_width) + Image.fromarray(img_arr, mode="L").save(out_path) + + +def _save_overlay( + ct_data: np.ndarray, + mask_path: str, + center_idx: int, + output_png: str, + window_center: float, + window_width: float, + slice_plane: str = "axial", + nodule_label: Optional[int] = NODULE_LABEL, +) -> None: + """Save an overlay PNG with the nodule mask highlighted for QC.""" + try: + mask_data = nib.load(mask_path).get_fdata(dtype=np.float32) + + # Extract mask slice for the same plane + _axis_map = {"axial": 2, "coronal": 1, "sagittal": 0} + axis = _axis_map[slice_plane] + slicing = [slice(None)] * 3 + slicing[axis] = center_idx + raw_slice = mask_data[tuple(slicing)] + if nodule_label is None: + mask_slice = (raw_slice > 0).astype(np.uint8) + else: + mask_slice = (raw_slice == nodule_label).astype(np.uint8) + + ct_slice_raw = ct_data[tuple(slicing)] + ct_arr = _apply_ct_window(ct_slice_raw, window_center, window_width) + rgb = np.stack([ct_arr, ct_arr, ct_arr], axis=-1) + + # Red overlay where mask == 1, 50% opacity + overlay_mask = mask_slice > 0 + rgb[overlay_mask, 0] = np.clip(rgb[overlay_mask, 0].astype(int) + 100, 0, 255).astype( + np.uint8 + ) + rgb[overlay_mask, 1] = (rgb[overlay_mask, 1] * 0.5).astype(np.uint8) + rgb[overlay_mask, 2] = (rgb[overlay_mask, 2] * 0.5).astype(np.uint8) + + base, ext = os.path.splitext(output_png) + overlay_path = f"{base}_overlay{ext}" + + # Apply same radiological orientation to RGB overlay + if slice_plane == "axial": + oriented = np.fliplr(np.flipud(rgb.transpose(1, 0, 2))) + elif slice_plane == "coronal": + oriented = np.flipud(rgb.transpose(1, 0, 2)) + else: # sagittal + oriented = np.flipud(rgb.transpose(1, 0, 2)) + + img = Image.fromarray(oriented, mode="RGB") + img.save(overlay_path) + except Exception as e: + logger.warning("Failed to save overlay for %s: %s", output_png, e) + + +# ── Public helper: extract a slice at an arbitrary z-index ─────────────────── + + +def extract_slice_at_z( + ct_path: str, + z_index: int, + output_png: str, + profile: Optional["PreprocessProfile"] = None, + window_center: float = _DEFAULT_WINDOW_CENTER, + window_width: float = _DEFAULT_WINDOW_WIDTH, +) -> None: + """Extract and save a 2D slice at a specific z-index (no mask needed). + + Uses the same windowing, orientation, and output format as + :func:`extract_slice`, but requires no mask—caller supplies the z-index + directly. Intended for generating nodule-free negative slices. + + Parameters + ---------- + ct_path : str + Path to the 3D CT NIfTI file. + z_index : int + Axial slice index (after RAS+ reorientation). + output_png : str + Where to save the output image. + profile : PreprocessProfile, optional + Preprocessing profile (controls windowing, output format, etc.). + window_center, window_width : float + CT windowing. Overridden by *profile* if provided. + """ + if profile is not None: + window_center = profile.window_center + window_width = profile.window_width + slice_plane = profile.slice_plane + num_context = profile.num_context_slices + output_format = profile.output_format + else: + slice_plane = "axial" + num_context = _STACK_MARGIN + output_format = "png_gray" + + nii = nib.load(ct_path) + nii = nib.as_closest_canonical(nii) + ct_data = nii.get_fdata(dtype=np.float32) + + _axis_map = {"axial": 2, "coronal": 1, "sagittal": 0} + max_idx = ct_data.shape[_axis_map[slice_plane]] - 1 + z_index = int(np.clip(z_index, 0, max_idx)) + + _save_slice_stack( + ct_data, + z_index, + output_png, + window_center, + window_width, + slice_plane, + num_context, + output_format, + ) diff --git a/itrialspace/src/itrialspace/evaluation/vlm_eval/splits.py b/itrialspace/src/itrialspace/evaluation/vlm_eval/splits.py new file mode 100644 index 0000000000000000000000000000000000000000..55a1e470634063c2ee910a75241274512782e118 --- /dev/null +++ b/itrialspace/src/itrialspace/evaluation/vlm_eval/splits.py @@ -0,0 +1,107 @@ +""" +Frozen evaluation splits for the VLM benchmark. + +A *split* is an immutable, checksummed list of canonical case ids (``uid``\\ s) +that a result is reported on, so that reruns and re-reports score exactly the +same cases. See ``docs/vlm_eval.md`` (section "Reporting convention") and +``docs/dataset_card.md``. + +Canonical uid +------------- +The stable identity of a case is **not** the ``case_id`` column -- that is a +non-unique positional index in both ``eval_dataset.csv`` and the per-model +result CSVs (it restarts per shard, so unrelated cases collide). The stable key +is the slice image path with the condition-variant sub-dir and the file +extension stripped, e.g.:: + + .../slices/mode1_controlled_prevalence/NLST_cohort__C0000.png -> mode1_controlled_prevalence/NLST_cohort__C0000 + .../slices/mode1_controlled_prevalence/bbox/NLST_cohort__C0000.png -> mode1_controlled_prevalence/NLST_cohort__C0000 + +so the same case maps to one uid across all four image conditions, and results +join cleanly to ``eval_dataset.csv``. +""" + +from __future__ import annotations + +import hashlib +import os +from pathlib import Path +from typing import Iterable, Set, Union + +import pandas as pd + +# Overlay sub-directory names inserted between the mode dir and the file name. +CONDITION_DIRS = ("bbox", "contour", "bbox_contour") + +# Path columns that may carry a slice path, in preference order. +_PATH_COLS = ( + "image_path", + "png_path", + "png_bbox_path", + "png_contour_path", + "png_bbox_contour_path", +) + +PathLike = Union[str, os.PathLike] + + +def canonical_uid(image_path: str) -> str: + """Canonical case uid from a slice image path (condition + extension stripped).""" + tail = str(image_path).split("/slices/")[-1] + parts = [p for p in tail.split("/") if p not in CONDITION_DIRS] + parts[-1] = os.path.splitext(parts[-1])[0] + return "/".join(parts) + + +def uid_series(df: pd.DataFrame) -> pd.Series: + """Series of canonical uids for a results / eval DataFrame. + + Uses the first available path column (``image_path`` for result CSVs, + ``png_path`` for eval datasets). + """ + col = next((c for c in _PATH_COLS if c in df.columns), None) + if col is None: + raise KeyError( + f"DataFrame has none of the slice-path columns {_PATH_COLS}; " + "cannot derive canonical uids." + ) + return df[col].astype(str).map(canonical_uid) + + +def load_split(path: PathLike) -> Set[str]: + """Load a split file (one uid per line; blank lines and ``#`` comments ignored).""" + ids: Set[str] = set() + for line in Path(path).read_text().splitlines(): + s = line.strip() + if s and not s.startswith("#"): + ids.add(s) + return ids + + +def filter_to_split(df: pd.DataFrame, case_ids: Union[PathLike, Iterable[str]]) -> pd.DataFrame: + """Restrict a DataFrame to rows whose canonical uid is in ``case_ids``. + + ``case_ids`` may be a path to a split file or an iterable of uids. + """ + if isinstance(case_ids, (str, os.PathLike)): + case_ids = load_split(case_ids) + wanted = set(case_ids) + return df[uid_series(df).isin(wanted)].copy() + + +def sha256_of_ids(ids: Iterable[str]) -> str: + """Stable content hash of a uid set (sorted, newline-joined).""" + h = hashlib.sha256() + for u in sorted(set(ids)): + h.update(u.encode("utf-8")) + h.update(b"\n") + return h.hexdigest() + + +def write_split(ids: Iterable[str], out_path: PathLike) -> dict: + """Write a sorted split file; return ``{"n", "sha256"}`` metadata.""" + ids = sorted(set(ids)) + p = Path(out_path) + p.parent.mkdir(parents=True, exist_ok=True) + p.write_text("\n".join(ids) + "\n") + return {"n": len(ids), "sha256": sha256_of_ids(ids)} diff --git a/itrialspace/src/itrialspace/index/__init__.py b/itrialspace/src/itrialspace/index/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/itrialspace/src/itrialspace/index/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/index/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0a1ffb5fc8d2eacb05539a2ae4c2584e36561900 Binary files /dev/null and b/itrialspace/src/itrialspace/index/__pycache__/__init__.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/index/__pycache__/nodule_index.cpython-310.pyc b/itrialspace/src/itrialspace/index/__pycache__/nodule_index.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..810b46aff514ac387e8c6f45d00c03e97b8d0658 Binary files /dev/null and b/itrialspace/src/itrialspace/index/__pycache__/nodule_index.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/index/nodule_index.py b/itrialspace/src/itrialspace/index/nodule_index.py new file mode 100644 index 0000000000000000000000000000000000000000..29b85aaa48e15535ce5ea630e05243f93d34cbe7 --- /dev/null +++ b/itrialspace/src/itrialspace/index/nodule_index.py @@ -0,0 +1,197 @@ +""" +NoduleIndex — the central object. +Loads all datasets, merges into a single DataFrame, exposes query/stats API. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +import pandas as pd + +from itrialspace.core.schema import DATASET_FLAGS +from itrialspace.io.loader import DatasetLoader +from itrialspace.io.registry import DatasetRegistry + +if TYPE_CHECKING: + from itrialspace.query.query_api import NoduleQuery + + +class NoduleIndex: + """ + A merged, queryable index over all iTrialSpace nodule profile datasets. + + The backing store is a single pandas DataFrame containing the 53 core + pipeline columns plus `label`, `patient_id`, `annotation_id`, `dataset`, + and all dataset-specific extra columns (NaN where not applicable). + + Usage: + # From a registry (recommended) + registry = DatasetRegistry.from_directory("/data/profiles/") + idx = NoduleIndex.from_registry(registry) + + # From a single CSV + idx = NoduleIndex.from_csv("DLCS24", "/data/DLCS24_nodule_profiles.csv") + + # From a pre-built DataFrame + idx = NoduleIndex(df) + + # Query + results = idx.query().label(1).lobe("right_lung_upper_lobe").fetch() + + # Stats + print(idx.stats()) + """ + + def __init__(self, df: pd.DataFrame): + self._df = df.copy().reset_index(drop=True) + + @classmethod + def from_csv(cls, dataset: str, csv_path: str) -> "NoduleIndex": + """Load a single dataset CSV.""" + df = DatasetLoader.load_to_dataframe(dataset, csv_path) + return cls(df) + + @classmethod + def from_registry(cls, registry: DatasetRegistry, verbose: bool = True) -> "NoduleIndex": + """Load all registered datasets and merge into one index.""" + frames = [] + for dataset, path in registry.items(): + if verbose: + print(f" Loading {dataset:<10s} ← {path}") + try: + df = DatasetLoader.load_to_dataframe(dataset, path) + frames.append(df) + if verbose: + mal = df["label"].sum() if df["label"].notna().any() else "?" + print(f" {len(df):>5d} rows | label={mal}") + except Exception as e: + print(f" ⚠ {dataset}: failed ({e})") + + if not frames: + raise RuntimeError("No datasets loaded.") + + merged = pd.concat(frames, axis=0, ignore_index=True, sort=False) + if verbose: + print(f"\n Total: {len(merged):,} nodules across {len(frames)} datasets") + return cls(merged) + + @classmethod + def from_dict(cls, mapping: dict[str, str], verbose: bool = True) -> "NoduleIndex": + """Shortcut: load from dict {'DLCS24': '/path/...', ...}""" + registry = DatasetRegistry.from_dict(mapping) + return cls.from_registry(registry, verbose=verbose) + + # ── Core properties ──────────────────────────────────────────────────────── + + @property + def df(self) -> pd.DataFrame: + """Access the underlying DataFrame directly.""" + return self._df + + @property + def datasets(self) -> list[str]: + return sorted(self._df["dataset"].unique().tolist()) + + def __len__(self) -> int: + return len(self._df) + + def __repr__(self) -> str: + n = len(self._df) + ds = ", ".join(self.datasets) + labelled = self._df["label"].notna().sum() + return f"NoduleIndex({n:,} nodules | {ds} | {labelled:,} labelled)" + + # ── Query entry point ────────────────────────────────────────────────────── + + def query(self) -> "NoduleQuery": + from itrialspace.query.query_api import NoduleQuery + + return NoduleQuery(self._df) + + # ── Stats ────────────────────────────────────────────────────────────────── + + def stats(self) -> pd.DataFrame: + """ + Per-dataset summary table: n, malignancy rate, size stats, lobe coverage. + """ + rows = [] + for ds in sorted(self._df["dataset"].unique()): + sub = self._df[self._df["dataset"] == ds] + flags = DATASET_FLAGS.get(ds, {}) + + labelled = sub["label"].notna() + mal_rate = ( + f"{sub.loc[labelled, 'label'].mean() * 100:.1f}%" if labelled.any() else "N/A" + ) + mal_n = int(sub["label"].sum()) if labelled.any() else 0 + + diam = sub["nodule_mean_diam_mm"] + rows.append( + { + "dataset": ds, + "n": len(sub), + "patients": sub["patient_id"].nunique(), + "labelled": int(labelled.sum()), + "malignant": mal_n, + "mal_rate": mal_rate, + "diam_median": round(diam.median(), 1), + "diam_mean": round(diam.mean(), 1), + "diam_max": round(diam.max(), 1), + "all_malignant": flags.get("all_malignant", False), + "all_unlabelled": flags.get("all_unlabelled", False), + "label_is_soft": flags.get("label_is_soft", False), + "notes": flags.get("notes", ""), + } + ) + return pd.DataFrame(rows).set_index("dataset") + + def lobe_stats(self) -> pd.DataFrame: + """Lobe × dataset malignancy rates.""" + sub = self._df[self._df["label"].notna()] + return ( + sub.groupby(["dataset", "lobe_name"])["label"] + .agg(["sum", "count", "mean"]) + .rename(columns={"sum": "malignant", "count": "total", "mean": "rate"}) + .assign(rate=lambda d: (d["rate"] * 100).round(1)) + ) + + def size_stats(self) -> pd.DataFrame: + """Size bucket × dataset malignancy rates.""" + bins = [0, 5, 10, 15, 20, 30, 200] + lbls = ["<5mm", "5-10mm", "10-15mm", "15-20mm", "20-30mm", ">30mm"] + df = self._df.copy() + df["size_bucket"] = pd.cut(df["nodule_mean_diam_mm"], bins=bins, labels=lbls) + return ( + df.groupby(["dataset", "size_bucket"])["label"] + .agg(["sum", "count", "mean"]) + .rename(columns={"sum": "malignant", "count": "total", "mean": "rate"}) + .assign(rate=lambda d: (d["rate"] * 100).round(1)) + ) + + # ── Flags ────────────────────────────────────────────────────────────────── + + def dataset_flags(self, dataset: str) -> dict: + """Return known data quality flags for a dataset.""" + flags = DATASET_FLAGS.get(dataset, {}) + if not flags: + return {"warning": f"No flags registered for '{dataset}'"} + return flags + + # ── Convenience filters ─────────────────────────────────────────────────── + + def labelled(self) -> "NoduleIndex": + """Return a new NoduleIndex with only rows that have a label.""" + return NoduleIndex(self._df[self._df["label"].notna()]) + + def malignant(self) -> "NoduleIndex": + """Return only malignant rows.""" + return NoduleIndex(self._df[self._df["label"] == 1]) + + def benign(self) -> "NoduleIndex": + """Return only benign rows.""" + return NoduleIndex(self._df[self._df["label"] == 0]) + + def subset(self, datasets: list[str]) -> "NoduleIndex": + """Return only rows from specified datasets.""" + return NoduleIndex(self._df[self._df["dataset"].isin(datasets)]) diff --git a/itrialspace/src/itrialspace/io/__init__.py b/itrialspace/src/itrialspace/io/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/itrialspace/src/itrialspace/io/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/io/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1716442af41174b35d6828acae43619b66abc5c6 Binary files /dev/null and b/itrialspace/src/itrialspace/io/__pycache__/__init__.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/io/__pycache__/loader.cpython-310.pyc b/itrialspace/src/itrialspace/io/__pycache__/loader.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d9a44f29ad2cbe368b3ecbad8f1a997c8d91bffe Binary files /dev/null and b/itrialspace/src/itrialspace/io/__pycache__/loader.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/io/__pycache__/registry.cpython-310.pyc b/itrialspace/src/itrialspace/io/__pycache__/registry.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a5eec882ac96590c1139c8780b55ae523aa95798 Binary files /dev/null and b/itrialspace/src/itrialspace/io/__pycache__/registry.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/io/adapters/__init__.py b/itrialspace/src/itrialspace/io/adapters/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/itrialspace/src/itrialspace/io/adapters/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/io/adapters/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2388d3fa33c1181823401b60cdc622c47ec0e463 Binary files /dev/null and b/itrialspace/src/itrialspace/io/adapters/__pycache__/__init__.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/io/adapters/__pycache__/adapters.cpython-310.pyc b/itrialspace/src/itrialspace/io/adapters/__pycache__/adapters.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2005de7d88372e8bc75b1bb7d56f72c3d22ff6bc Binary files /dev/null and b/itrialspace/src/itrialspace/io/adapters/__pycache__/adapters.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/io/adapters/adapters.py b/itrialspace/src/itrialspace/io/adapters/adapters.py new file mode 100644 index 0000000000000000000000000000000000000000..31f65962289786565287f071946ecce84345e3b8 --- /dev/null +++ b/itrialspace/src/itrialspace/io/adapters/adapters.py @@ -0,0 +1,128 @@ +""" +Dataset adapters — one class per dataset. + +Each adapter knows: + - which column is the patient_id + - which column is the annotation_id + - which columns are dataset-specific metadata (go into meta{}) + - any special pre-processing needed before loading +""" + +from __future__ import annotations + +from typing import Optional + +import pandas as pd + + +class _BaseAdapter: + dataset: str = "" + patient_id_col: str = "PatientID" + annotation_id_col: Optional[str] = "AnnotationID" + + # Columns that are dataset-specific (go to meta dict, not core fields) + # Computed as: all columns NOT in CORE_COLS and NOT identity cols + _extra_col_cache: Optional[list[str]] = None + + def extra_cols(self, df_columns: list[str]) -> list[str]: + from itrialspace.core.schema import CORE_COLS + + core_set = set(CORE_COLS) | { + "coordX", + "coordY", + "coordZ", + self.patient_id_col, + self.annotation_id_col or "", + "ct_path", + } + return [c for c in df_columns if c not in core_set] + + def get_patient_id(self, row: pd.Series) -> str: + v = row.get(self.patient_id_col) + return str(v) if pd.notna(v) else "unknown" + + def get_annotation_id(self, row: pd.Series) -> str: + if self.annotation_id_col and self.annotation_id_col in row.index: + v = row.get(self.annotation_id_col) + if pd.notna(v): + return str(v) + # fallback: dataset + index + return f"{self.dataset}_unknown" + + def preprocess(self, df: pd.DataFrame) -> pd.DataFrame: + """Hook for dataset-specific pre-processing. Override as needed.""" + return df + + +class DLCS24Adapter(_BaseAdapter): + dataset = "DLCS24" + patient_id_col = "patient-id" + annotation_id_col = "AnnotationID" + + +class LUNA25Adapter(_BaseAdapter): + dataset = "LUNA25" + patient_id_col = "PatientID" + annotation_id_col = "AnnotationID" + + +class LUNA16Adapter(_BaseAdapter): + dataset = "LUNA16" + patient_id_col = "seriesuid" + annotation_id_col = "AnnotationID" + + +class LUNGxAdapter(_BaseAdapter): + dataset = "LUNGx" + patient_id_col = "PatientID" + annotation_id_col = "AnnotationID" + + +class LNDbv4Adapter(_BaseAdapter): + dataset = "LNDbv4" + patient_id_col = "PatientID" + annotation_id_col = "AnnotationID" + + def preprocess(self, df: pd.DataFrame) -> pd.DataFrame: + # Aggregate multi-radiologist rows: group by unique_NoduleID, + # take mean of numeric ratings, keep first for string fields + if "unique_NoduleID" not in df.columns: + return df + return df # loaded as-is; aggregation is optional and caller-driven + + +class NSCLCRAdapter(_BaseAdapter): + dataset = "NSCLCR" + patient_id_col = "PatientID" + annotation_id_col = "AnnotationID" + + +class IMDCTAdapter(_BaseAdapter): + dataset = "IMDCT" + patient_id_col = "PatientID" + annotation_id_col = None # IMDCT has no AnnotationID column + + def get_annotation_id(self, row: pd.Series) -> str: + # Synthesise from PatientID + row index (set by loader) + pid = self.get_patient_id(row) + idx = row.get("_row_index", "0") + return f"IMDCT_{pid}_{idx}" + + +# ── Registry ────────────────────────────────────────────────────────────────── + +ADAPTERS: dict[str, _BaseAdapter] = { + "DLCS24": DLCS24Adapter(), + "LUNA25": LUNA25Adapter(), + "LUNA16": LUNA16Adapter(), + "LUNGx": LUNGxAdapter(), + "LNDbv4": LNDbv4Adapter(), + "NSCLCR": NSCLCRAdapter(), + "IMDCT": IMDCTAdapter(), +} + + +def get_adapter(dataset: str) -> _BaseAdapter: + if dataset not in ADAPTERS: + raise ValueError(f"No adapter for dataset '{dataset}'. Known: {list(ADAPTERS)}") + return ADAPTERS[dataset] diff --git a/itrialspace/src/itrialspace/io/loader.py b/itrialspace/src/itrialspace/io/loader.py new file mode 100644 index 0000000000000000000000000000000000000000..525874cacb48658bece5923e8a62e6b1ca9d664a --- /dev/null +++ b/itrialspace/src/itrialspace/io/loader.py @@ -0,0 +1,196 @@ +""" +DatasetLoader — reads a nodule profile CSV and returns a list of +NoduleProfile objects with unified schema. +""" + +from __future__ import annotations + +from typing import Optional + +import numpy as np +import pandas as pd + +from itrialspace.core.label import LabelNormaliser +from itrialspace.core.profile import NoduleProfile +from itrialspace.io.adapters.adapters import get_adapter + +# Map CSV column names → NoduleProfile attribute names +_COL_MAP = { + "coordX": "coord_x", + "coordY": "coord_y", + "coordZ": "coord_z", +} + + +def _f(v, default=None) -> Optional[float]: + """Safe float conversion.""" + try: + f = float(v) + return None if np.isnan(f) else f + except (TypeError, ValueError): + return default + + +def _i(v, default=None) -> Optional[int]: + """Safe int conversion.""" + try: + f = float(v) + return None if np.isnan(f) else int(f) + except (TypeError, ValueError): + return default + + +def _b(v) -> Optional[bool]: + """Safe bool conversion.""" + if pd.isna(v): + return None + if isinstance(v, bool): + return v + if isinstance(v, (int, float)): + return bool(v) + s = str(v).strip().lower() + if s in ("true", "1", "yes"): + return True + if s in ("false", "0", "no"): + return False + return None + + +def _s(v, default: str = "") -> str: + """Safe string conversion.""" + if pd.isna(v): + return default + return str(v).strip() + + +class DatasetLoader: + """ + Loads a nodule profile CSV for a given dataset and returns + a list of NoduleProfile objects. + + Usage: + profiles = DatasetLoader.load("DLCS24", "/path/to/DLCS24_nodule_profiles.csv") + """ + + @staticmethod + def load(dataset: str, csv_path: str) -> list[NoduleProfile]: + adapter = get_adapter(dataset) + normaliser = LabelNormaliser(dataset) + + df = pd.read_csv(csv_path, low_memory=False) + df = adapter.preprocess(df) + + # Add row index for adapters that need it (IMDCT) + df["_row_index"] = df.index.astype(str) + + extra_cols = adapter.extra_cols(list(df.columns)) + profiles = [] + + for _, row in df.iterrows(): + pid = adapter.get_patient_id(row) + aid = adapter.get_annotation_id(row) + label = normaliser.normalise(row) + + meta = { + c: (None if pd.isna(row.get(c)) else row.get(c)) + for c in extra_cols + if c != "_row_index" + } + + p = NoduleProfile( + # identity + annotation_id=aid, + patient_id=pid, + dataset=dataset, + ct_path=_s(row.get("ct_path")), + label=label, + # bounding box + coord_x=_f(row.get("coordX"), 0.0), + coord_y=_f(row.get("coordY"), 0.0), + coord_z=_f(row.get("coordZ"), 0.0), + w=_f(row.get("w"), 0.0), + h=_f(row.get("h"), 0.0), + d=_f(row.get("d"), 0.0), + # morphology + nodule_mean_diam_mm=_f(row.get("nodule_mean_diam_mm"), 0.0), + nodule_vol_mm3=_f(row.get("nodule_vol_mm3")), + # anatomy + lobe_name=_s(row.get("lobe_name"), "unknown"), + lung_side=_s(row.get("lung_side"), "unknown"), + lung_zone=_s(row.get("lung_zone"), "unknown"), + organ_label_id=_i(row.get("organ_label_id"), 0), + organ_label_name=_s(row.get("organ_label_name")), + central_peripheral=_s(row.get("central_peripheral"), "unknown"), + nearby_organs_10mm=_s(row.get("nearby_organs_10mm")) or None, + # position – lung % + cranio_caudal_pct=_f(row.get("cranio_caudal_pct")), + mediolateral_pct=_f(row.get("mediolateral_pct")), + anteroposterior_pct=_f(row.get("anteroposterior_pct")), + # position – lobe % + lobe_cc_pct=_f(row.get("lobe_cc_pct")), + lobe_ml_pct=_f(row.get("lobe_ml_pct")), + lobe_ap_pct=_f(row.get("lobe_ap_pct")), + # distances + dist_to_trachea_mm=_f(row.get("dist_to_trachea_mm")), + dist_to_aorta_mm=_f(row.get("dist_to_aorta_mm")), + dist_to_heart_mm=_f(row.get("dist_to_heart_mm")), + dist_to_esophagus_mm=_f(row.get("dist_to_esophagus_mm")), + dist_to_pulmonary_vein_mm=_f(row.get("dist_to_pulmonary_vein_mm")), + dist_to_superior_vena_cava_mm=_f(row.get("dist_to_superior_vena_cava_mm")), + pleural_distance_mm=_f(row.get("pleural_distance_mm")), + airway_distance_mm=_f(row.get("airway_distance_mm")), + # inter-nodule + n_nodules_in_patient=_i(row.get("n_nodules_in_patient"), 1), + nearest_nodule_id=_s(row.get("nearest_nodule_id")) or None, + nearest_nodule_dist_mm=_f(row.get("nearest_nodule_dist_mm")), + nearest_dx_mm=_f(row.get("nearest_dx_mm")), + nearest_dy_mm=_f(row.get("nearest_dy_mm")), + nearest_dz_mm=_f(row.get("nearest_dz_mm")), + all_nodule_ids=_s(row.get("all_nodule_ids")) or None, + all_nodule_dists_mm=_s(row.get("all_nodule_dists_mm")) or None, + ipsilateral=_b(row.get("ipsilateral")), + nearest_same_lobe=_b(row.get("nearest_same_lobe")), + bilateral_distribution=_b(row.get("bilateral_distribution")) or False, + # reinsertion (100% complete) + reinsertion_lobe=_s(row.get("reinsertion_lobe"), "unknown"), + reinsertion_lung_side=_s(row.get("reinsertion_lung_side"), "unknown"), + reinsertion_lung_zone=_s(row.get("reinsertion_lung_zone"), "unknown"), + reinsertion_lobe_cc_pct=_f(row.get("reinsertion_lobe_cc_pct"), 0.0), + reinsertion_lobe_ml_pct=_f(row.get("reinsertion_lobe_ml_pct"), 0.0), + reinsertion_lobe_ap_pct=_f(row.get("reinsertion_lobe_ap_pct"), 0.0), + reinsertion_lung_cc_pct=_f(row.get("reinsertion_lung_cc_pct"), 0.0), + reinsertion_lung_ml_pct=_f(row.get("reinsertion_lung_ml_pct"), 0.0), + reinsertion_lung_ap_pct=_f(row.get("reinsertion_lung_ap_pct"), 0.0), + reinsertion_pleural_dist_mm=_f(row.get("reinsertion_pleural_dist_mm")), + reinsertion_airway_dist_mm=_f(row.get("reinsertion_airway_dist_mm")), + reinsertion_nodule_diam_mm=_f(row.get("reinsertion_nodule_diam_mm"), 0.0), + meta=meta, + ) + profiles.append(p) + + return profiles + + @staticmethod + def load_to_dataframe(dataset: str, csv_path: str) -> pd.DataFrame: + """ + Load CSV, add normalised `label`, `patient_id`, `dataset` columns, + and return the full DataFrame (core + extra columns). + Faster than load() for index-building. + """ + adapter = get_adapter(dataset) + normaliser = LabelNormaliser(dataset) + + df = pd.read_csv(csv_path, low_memory=False) + df = adapter.preprocess(df) + df["_row_index"] = df.index.astype(str) + + # Normalised identity columns + df["dataset"] = dataset + df["patient_id"] = df.apply(adapter.get_patient_id, axis=1) + df["annotation_id"] = df.apply(adapter.get_annotation_id, axis=1) + df["label"] = normaliser.normalise_series(df) + + # Drop internal helper + df = df.drop(columns=["_row_index"]) + + return df diff --git a/itrialspace/src/itrialspace/io/registry.py b/itrialspace/src/itrialspace/io/registry.py new file mode 100644 index 0000000000000000000000000000000000000000..87328ba5a1a02c510784b069f58a4f0e700c8dc2 --- /dev/null +++ b/itrialspace/src/itrialspace/io/registry.py @@ -0,0 +1,135 @@ +""" +DatasetRegistry — maps dataset names to CSV paths. +Reads from config/datasets.yaml or can be built programmatically. +""" + +from __future__ import annotations + +import os +from pathlib import Path +from typing import Optional + +# Datasets permanently removed from the ecosystem. +_REMOVED_DATASETS = {"NLST3D"} + + +class DatasetRegistry: + """ + Holds the mapping of dataset name → CSV path. + + Usage — from YAML config (recommended): + registry = DatasetRegistry.from_yaml("/path/to/datasets.yaml") + + Usage — programmatic: + registry = DatasetRegistry() + registry.register("DLCS24", "/data/DLCS24_nodule_profiles.csv") + registry.register("LUNA25", "/data/LUNA25_nodule_profiles.csv") + + Usage — auto-discover from a directory: + registry = DatasetRegistry.from_directory("/data/profiles/") + # Looks for files matching *_nodule_profiles.csv + """ + + # Known dataset names in canonical order + KNOWN_DATASETS = ["DLCS24", "LUNA25", "LUNA16", "LUNGx", "LNDbv4", "NSCLCR", "IMDCT"] + + def __init__(self): + self._entries: dict[str, str] = {} # dataset → csv_path + + def register(self, dataset: str, csv_path: str) -> "DatasetRegistry": + """Register a single dataset. Returns self for chaining.""" + if dataset in _REMOVED_DATASETS: + raise ValueError( + f"Dataset '{dataset}' was removed due to quality issues and cannot be registered." + ) + csv_path = str(Path(csv_path).expanduser()) + if not os.path.isfile(csv_path): + raise FileNotFoundError(f"CSV not found: {csv_path}") + self._entries[dataset] = csv_path + return self + + def register_if_exists(self, dataset: str, csv_path: str) -> "DatasetRegistry": + """Register only if the file exists. Silent skip otherwise.""" + try: + return self.register(dataset, csv_path) + except FileNotFoundError: + return self + + def get(self, dataset: str) -> Optional[str]: + return self._entries.get(dataset) + + def datasets(self) -> list[str]: + return list(self._entries.keys()) + + def items(self): + return self._entries.items() + + def __len__(self) -> int: + return len(self._entries) + + def __repr__(self) -> str: + lines = [f"DatasetRegistry ({len(self)} datasets):"] + for ds, path in self._entries.items(): + lines.append(f" {ds:<10s} {path}") + return "\n".join(lines) + + # ── Class methods ────────────────────────────────────────────────────────── + + @classmethod + def from_yaml(cls, yaml_path: Optional[str] = None) -> "DatasetRegistry": + """Load from a YAML config file. + + When ``yaml_path`` is omitted, the file is discovered via + ``itrialspace.config.settings`` (top-level ``configs/datasets.yaml`` → + shipped ``datasets.example.yaml`` → bundled package default), and + ``${ITRIALSPACE_DATA_DIR}`` style placeholders are expanded. + """ + from itrialspace.config import settings + + _pkg_default = Path(__file__).resolve().parents[1] / "config" / "datasets.yaml" + if yaml_path is None: + yaml_path = settings.find_config("datasets.yaml", package_default=_pkg_default) + + config = settings.load_yaml(yaml_path) + + registry = cls() + datasets = config.get("datasets", config) # support flat or nested + + for name, entry in datasets.items(): + if isinstance(entry, dict): + path = entry.get("csv_path") or entry.get("path") + else: + path = str(entry) + if path: + registry.register_if_exists(name, path) + + return registry + + @classmethod + def from_directory( + cls, directory: str, pattern: str = "*_nodule_profiles.csv" + ) -> "DatasetRegistry": + """ + Auto-discover CSVs in a directory. + Filename must start with the dataset name, e.g. DLCS24_nodule_profiles.csv + """ + import glob + + registry = cls() + paths = sorted(glob.glob(os.path.join(directory, pattern))) + for path in paths: + fname = os.path.basename(path) + # Extract dataset name as the part before '_nodule_profiles.csv' + if "_nodule_profiles" in fname: + dataset = fname.split("_nodule_profiles")[0] + if dataset in cls.KNOWN_DATASETS: + registry.register_if_exists(dataset, path) + return registry + + @classmethod + def from_dict(cls, mapping: dict[str, str]) -> "DatasetRegistry": + """Build from a plain dict: {'DLCS24': '/path/...', ...}""" + registry = cls() + for name, path in mapping.items(): + registry.register_if_exists(name, path) + return registry diff --git a/itrialspace/src/itrialspace/mask_inserter/__init__.py b/itrialspace/src/itrialspace/mask_inserter/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c366ffddc6c9a918c9a8682c2ed00f4747e7a99d --- /dev/null +++ b/itrialspace/src/itrialspace/mask_inserter/__init__.py @@ -0,0 +1,22 @@ +# -*- coding: utf-8 -*- +""" +iTrialSpace Mask Insertion Engine +================================= + +Downstream module that takes an iTrialSpace CohortManifest and produces +host-space nodule masks by inserting donor nodule masks into host CT +geometry according to the manifest's insertion plan. + +Submodules: + placement – percentile→voxel conversion, snapping, pleural margin, collision + resample – scipy-based resampling, scaling, binary cleanup + resolver_bridge – PathResolver integration for host/donor path resolution + inserter – main per-row and per-manifest orchestration + cli – command-line interface for HPC batch execution +""" + +__version__ = "0.1.0" + +from itrialspace.mask_inserter.inserter import insert_case, insert_manifest + +__all__ = ["insert_manifest", "insert_case", "__version__"] diff --git a/itrialspace/src/itrialspace/mask_inserter/__main__.py b/itrialspace/src/itrialspace/mask_inserter/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..b258935263bcaafd26211c2d562e771d0d863b12 --- /dev/null +++ b/itrialspace/src/itrialspace/mask_inserter/__main__.py @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +"""Allow running as ``python -m itrialspace.mask_inserter``.""" + +from itrialspace.mask_inserter.cli import main + +if __name__ == "__main__": + main() diff --git a/itrialspace/src/itrialspace/mask_inserter/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/mask_inserter/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b53908c1a6d0f886a0f404dae16ced71930a4845 Binary files /dev/null and b/itrialspace/src/itrialspace/mask_inserter/__pycache__/__init__.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/mask_inserter/__pycache__/__main__.cpython-310.pyc b/itrialspace/src/itrialspace/mask_inserter/__pycache__/__main__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9ef5f622b2a1e12baa98d3571166e4f3c6192084 Binary files /dev/null and b/itrialspace/src/itrialspace/mask_inserter/__pycache__/__main__.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/mask_inserter/__pycache__/cli.cpython-310.pyc b/itrialspace/src/itrialspace/mask_inserter/__pycache__/cli.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3576617989f0310a9e6cecb776afb4a2bf55a6a5 Binary files /dev/null and b/itrialspace/src/itrialspace/mask_inserter/__pycache__/cli.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/mask_inserter/__pycache__/inserter.cpython-310.pyc b/itrialspace/src/itrialspace/mask_inserter/__pycache__/inserter.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3973c60e978c2fcb19fd0eaea09be388f81df29a Binary files /dev/null and b/itrialspace/src/itrialspace/mask_inserter/__pycache__/inserter.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/mask_inserter/__pycache__/placement.cpython-310.pyc b/itrialspace/src/itrialspace/mask_inserter/__pycache__/placement.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..79ed8e6557d47ef00cb2e789fa60fc0b342c6a98 Binary files /dev/null and b/itrialspace/src/itrialspace/mask_inserter/__pycache__/placement.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/mask_inserter/__pycache__/resample.cpython-310.pyc b/itrialspace/src/itrialspace/mask_inserter/__pycache__/resample.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..68165a0dae160187d01b26c2cec16c8dd4a05040 Binary files /dev/null and b/itrialspace/src/itrialspace/mask_inserter/__pycache__/resample.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/mask_inserter/__pycache__/resolver_bridge.cpython-310.pyc b/itrialspace/src/itrialspace/mask_inserter/__pycache__/resolver_bridge.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fef6bde87b0fb4344ca989830d0f82db1319e04e Binary files /dev/null and b/itrialspace/src/itrialspace/mask_inserter/__pycache__/resolver_bridge.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/mask_inserter/cli.py b/itrialspace/src/itrialspace/mask_inserter/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..051db905c955d7d3d36dde64df409c253dbe1f05 --- /dev/null +++ b/itrialspace/src/itrialspace/mask_inserter/cli.py @@ -0,0 +1,258 @@ +# -*- coding: utf-8 -*- +""" +cli.py — Command-line interface for the iTrialSpace Mask Insertion Engine. + +Usage:: + + # Full batch run + python -m itrialspace.mask_inserter run \\ + --manifest cohort_manifest.csv \\ + --output-dir $ITRIALSPACE_OUTPUT_DIR/trial_01 \\ + --config my_overrides.yaml \\ + --trial-name trial_01 \\ + --seed 42 + + # Dry-run (placement only, no files written) + python -m itrialspace.mask_inserter run \\ + --manifest cohort_manifest.csv \\ + --output-dir $ITRIALSPACE_OUTPUT_DIR/trial_01 \\ + --dry-run + + # Verify existing outputs + python -m itrialspace.mask_inserter verify \\ + --output-dir $ITRIALSPACE_OUTPUT_DIR/trial_01 +""" + +from __future__ import annotations + +import argparse +import json +import logging +import os +import sys + + +def main(argv: list[str] | None = None) -> int: + """Entry point for ``python -m itrialspace.mask_inserter``.""" + parser = argparse.ArgumentParser( + prog="itrialspace.mask_inserter", + description="iTrialSpace Mask Insertion Engine — insert donor nodule " + "masks into host CT space according to a CohortManifest.", + ) + parser.add_argument( + "--version", + action="version", + version=f"%(prog)s {_get_version()}", + ) + sub = parser.add_subparsers(dest="command") + + # ── run ──────────────────────────────────────────────────────────────── + p_run = sub.add_parser("run", help="Run the insertion pipeline.") + p_run.add_argument( + "--manifest", + "-m", + required=True, + help="Path to CohortManifest CSV or JSON.", + ) + p_run.add_argument( + "--output-dir", + "-o", + required=True, + help="Root output directory.", + ) + p_run.add_argument( + "--config", + "-c", + default=None, + help="YAML config overrides (merged with defaults).", + ) + p_run.add_argument( + "--base-dir", + default=None, + help="Base directory for resolving relative paths in the manifest.", + ) + p_run.add_argument( + "--trial-name", + default="unnamed", + help="Trial name (used for deterministic seeding).", + ) + p_run.add_argument( + "--seed", + type=int, + default=42, + help="Global random seed.", + ) + p_run.add_argument( + "--dry-run", + action="store_true", + help="Compute placement without writing masks.", + ) + p_run.add_argument( + "--n-jobs", + type=int, + default=1, + help="Number of parallel workers (across cases).", + ) + p_run.add_argument( + "--verbose", + "-v", + action="count", + default=0, + help="Increase logging verbosity.", + ) + + # ── verify ──────────────────────────────────────────────────────────── + p_verify = sub.add_parser( + "verify", + help="Verify outputs from a previous run.", + ) + p_verify.add_argument( + "--output-dir", + "-o", + required=True, + help="Output directory to verify.", + ) + p_verify.add_argument( + "--manifest", + "-m", + default=None, + help="Original manifest for cross-referencing (optional).", + ) + + args = parser.parse_args(argv) + + if args.command is None: + parser.print_help() + return 0 + + # Set up logging + level = logging.WARNING + if hasattr(args, "verbose"): + if args.verbose == 1: + level = logging.INFO + elif args.verbose >= 2: + level = logging.DEBUG + + logging.basicConfig( + level=level, + format="%(asctime)s [%(name)s] %(levelname)s: %(message)s", + datefmt="%H:%M:%S", + ) + + if args.command == "run": + return _cmd_run(args) + elif args.command == "verify": + return _cmd_verify(args) + else: + parser.print_help() + return 1 + + +def _cmd_run(args: argparse.Namespace) -> int: + """Execute the insertion pipeline.""" + from itrialspace.mask_inserter.inserter import insert_manifest + + records = insert_manifest( + manifest_path=args.manifest, + output_dir=args.output_dir, + config_path=args.config, + base_dir=args.base_dir, + trial_name=args.trial_name, + seed=args.seed, + dry_run=args.dry_run, + n_jobs=args.n_jobs, + ) + + n_ok = sum(1 for r in records if r.status == "success") + n_fail = sum(1 for r in records if r.status == "failed") + n_dry = sum(1 for r in records if r.status == "dry_run") + + print(f"\niTrialSpace Mask Inserter — {'DRY RUN' if args.dry_run else 'COMPLETE'}") + print(f" Total rows: {len(records)}") + print(f" Success: {n_ok}") + print(f" Failed: {n_fail}") + if n_dry: + print(f" Dry-run: {n_dry}") + print(f" Output dir: {args.output_dir}") + + if n_fail > 0: + print("\nFailed cases:") + for r in records: + if r.status == "failed": + print(f" {r.case_id}/nodule_{r.nodule_idx}: {r.reason}") + + return 1 if n_fail > 0 and n_ok == 0 else 0 + + +def _cmd_verify(args: argparse.Namespace) -> int: + """Verify outputs from a previous run.""" + output_dir = args.output_dir + audit_path = os.path.join(output_dir, "audit.json") + + if not os.path.isfile(audit_path): + print(f"ERROR: No audit.json found in {output_dir}") + return 1 + + with open(audit_path) as f: + audit = json.load(f) + + records = audit.get("records", []) + print(f"Verifying {len(records)} insertion records from {audit_path}") + + missing_nodule_masks = 0 + missing_combined = 0 + total_success = 0 + seen_combined = set() + + for rec in records: + if rec.get("status") != "success": + continue + total_success += 1 + + # Per-nodule mask (optional — may not be saved) + mask_path = rec.get("output_mask_path", "") + if mask_path and not os.path.isfile(mask_path): + missing_nodule_masks += 1 + + # Combined mask (one per case) + combined_path = rec.get("output_combined_path", "") + if combined_path and combined_path not in seen_combined: + seen_combined.add(combined_path) + if not os.path.isfile(combined_path): + missing_combined += 1 + print(f" MISSING combined: {combined_path}") + + print("\nVerification:") + print(f" Successful insertions: {total_success}") + print( + f" Combined masks: {len(seen_combined)} expected, " + f"{len(seen_combined) - missing_combined} found" + ) + if missing_combined: + print(f" Missing combined: {missing_combined}") + + if args.manifest: + import pandas as pd + + df = pd.read_csv(args.manifest) + n_cases = df["case_id"].nunique() if "case_id" in df.columns else len(df) + print(f" Manifest rows: {len(df)} ({n_cases} unique cases)") + print( + f" Coverage: {total_success}/{len(df)} " + f"({100*total_success/max(len(df),1):.1f}%)" + ) + + return 1 if missing_combined > 0 else 0 + + +def _get_version() -> str: + try: + from itrialspace.mask_inserter import __version__ + + return __version__ + except ImportError: + return "unknown" + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/itrialspace/src/itrialspace/mask_inserter/config/defaults.yaml b/itrialspace/src/itrialspace/mask_inserter/config/defaults.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2035657fa4cdbd99f3db7c794fd23b2868fcbdaa --- /dev/null +++ b/itrialspace/src/itrialspace/mask_inserter/config/defaults.yaml @@ -0,0 +1,113 @@ +# iTrialSpace Mask Insertion Engine — defaults +# Override per-site via --config flag or INSERTER_CONFIG env var. + +# ── Lobe label mapping (VISTA3D integer labels) ───────────────────────────── +lobe_labels: + left_lung_upper_lobe: 28 + left_lung_lower_lobe: 29 + right_lung_upper_lobe: 30 + right_lung_middle_lobe: 31 + right_lung_lower_lobe: 32 + +# String ↔ integer aliases accepted in manifest ``insertion_lobe`` column. +# Keys are normalised lowercased names; values map to the canonical key above. +lobe_aliases: + lul: left_lung_upper_lobe + lll: left_lung_lower_lobe + rul: right_lung_upper_lobe + rml: right_lung_middle_lobe + rll: right_lung_lower_lobe + left_upper: left_lung_upper_lobe + left_lower: left_lung_lower_lobe + right_upper: right_lung_upper_lobe + right_middle: right_lung_middle_lobe + right_lower: right_lung_lower_lobe + +# Labels treated as "whole lung" for fallback placement. +lung_labels: [28, 29, 30, 31, 32] + +# ── Nodule output label ───────────────────────────────────────────────────── +# Integer value written into the host output mask for inserted nodule voxels. +# The intermediate binary mask (0/1) is converted to this label before writing. +# Default 23; change without code edits by overriding this value. +nodule_label_value: 23 + +# Future extension: per-nodule-type label mapping (unused for now). +# When populated, keys are nodule type strings and values are integer labels. +# Example: {"malignant": 23, "benign": 24} +nodule_type_to_label: {} + +# ── Placement parameters ──────────────────────────────────────────────────── +placement: + # Maximum search radius (voxels) when snapping an out-of-mask candidate to + # the nearest valid voxel inside the target mask. + max_snap_radius_vox: 25 + + # Minimum distance (mm) from the lung boundary that an insertion centre must + # satisfy. Set to 0 to disable. + min_pleural_dist_mm: 2.0 + + # If True, check for overlap with existing nodules in the combined mask and + # attempt to shift the placement to avoid it. + check_overlap: true + + # Maximum fraction of donor mask voxels allowed to overlap with an existing + # nodule mask before the placement is declared infeasible. + max_overlap_fraction: 0.05 + + # Maximum additional shift (voxels) attempted to resolve overlap collisions. + max_collision_shift_vox: 15 + +# ── Resampling parameters ─────────────────────────────────────────────────── +resample: + # Interpolation for binary masks: "nearest" (default) or "linear" then + # threshold. + interpolation: nearest + + # After resampling, voxels with value >= this threshold are set to 1. + binary_threshold: 0.5 + + # Remove connected components smaller than this (voxels) after resampling. + min_component_size_vox: 3 + + # Fill holes in the binary mask after resampling. + fill_holes: true + +# ── Output naming ─────────────────────────────────────────────────────────── +output: + # Flat directory — all combined masks in one folder, no subdirectories. + use_case_subdirs: false + + # Combined mask template. + # Delimiter convention: '--' separates fields, '-' separates key from value. + # Parsing: dict(f.split('-', 1) for f in stem.split('--')[1:] if '-' in f) + # Available placeholders: {trial_name}, {case_id}, {host_id}, {host_dataset}, {donor_id}. + # case_id is zero-padded to 4 digits. host_id is SHA-256[:8] when >20 chars. + combined_mask_template: "iTS--{trial_name}--C{case_id}--host-{host_id}--src-{host_dataset}--nod-{donor_id}_mask.nii.gz" + + # Whether to save individual per-nodule binary masks (in addition to the combined mask). + save_per_nodule_mask: false + + # Per-nodule mask template (only used when save_per_nodule_mask is true). + nodule_mask_template: "case_{case_id}_nodule_{nodule_idx}_mask.nii.gz" + + # Audit log filename. + audit_name: audit.json + + # Compress NIfTI outputs. + compress: true + +# ── Optional CT intensity insertion (experimental, off by default) ────────── +ct_insertion: + enabled: false + blending_mode: poisson # poisson | direct | alpha + boundary_width_mm: 2.0 + +# ── Parallelism ───────────────────────────────────────────────────────────── +parallel: + backend: loky # loky | threading | sequential + n_jobs: 1 + verbose: 10 + +# ── Reproducibility ───────────────────────────────────────────────────────── +seed: 42 diff --git a/itrialspace/src/itrialspace/mask_inserter/inserter.py b/itrialspace/src/itrialspace/mask_inserter/inserter.py new file mode 100644 index 0000000000000000000000000000000000000000..46d33980e17a99193d69e19cb73ca127b430d1a0 --- /dev/null +++ b/itrialspace/src/itrialspace/mask_inserter/inserter.py @@ -0,0 +1,694 @@ +# -*- coding: utf-8 -*- +""" +inserter.py — Main orchestration for the mask insertion pipeline. + +Public API: + insert_case(row, ...) – process a single manifest row + insert_manifest(path, ...) – process an entire manifest CSV/JSON + +Workflow per row: + 1. Resolve paths (resolver_bridge) + 2. Load host organ segmentation → canonical RAS+ + 3. Compute placement (placement.py) + 4. Load donor nodule mask → canonical RAS+ + 5. Resample donor into host geometry (resample.py) + 6. Paste into combined mask; check collision + 7. Save per-nodule mask and update combined mask + 8. Return audit record +""" + +from __future__ import annotations + +import hashlib +import json +import logging +import os +import time +from dataclasses import asdict, dataclass, field +from pathlib import Path +from typing import Any, Tuple + +import numpy as np +import pandas as pd + +try: + import yaml +except ImportError: + yaml = None # type: ignore[assignment] + +from itrialspace.mask_inserter.placement import ( + PlacementConfig, + check_overlap, + compute_placement, + make_seed, + resolve_collision, +) +from itrialspace.mask_inserter.resample import ( + ResampleConfig, + load_nifti_canonical, + resample_donor_to_host, + save_nifti, +) +from itrialspace.mask_inserter.resolver_bridge import ResolverBridge + +logger = logging.getLogger("itrialspace.mask_inserter") + + +def _compact_id(raw_id: str, max_len: int = 20) -> str: + """Shorten IDs longer than *max_len* to a deterministic 8-char hex hash.""" + s = str(raw_id) + if len(s) <= max_len: + return s + return hashlib.sha256(s.encode()).hexdigest()[:8] + + +# ── Configuration loading ───────────────────────────────────────────────── + +_DEFAULTS_YAML = Path(__file__).parent / "config" / "defaults.yaml" + + +def load_config(config_path: str | None = None) -> dict: + """Load YAML config, merging with defaults.""" + if yaml is None: + raise ImportError("pyyaml required: pip install pyyaml") + + with open(_DEFAULTS_YAML) as f: + defaults = yaml.safe_load(f) or {} + + if config_path: + with open(config_path) as f: + overrides = yaml.safe_load(f) or {} + defaults = _deep_merge(defaults, overrides) + + return defaults + + +def _deep_merge(base: dict, override: dict) -> dict: + """Recursively merge *override* into *base*.""" + result = base.copy() + for k, v in override.items(): + if isinstance(v, dict) and isinstance(result.get(k), dict): + result[k] = _deep_merge(result[k], v) + else: + result[k] = v + return result + + +def _placement_config_from_dict(d: dict) -> PlacementConfig: + p = d.get("placement", {}) + return PlacementConfig( + max_snap_radius_vox=p.get("max_snap_radius_vox", 25), + min_pleural_dist_mm=p.get("min_pleural_dist_mm", 2.0), + check_overlap=p.get("check_overlap", True), + max_overlap_fraction=p.get("max_overlap_fraction", 0.05), + max_collision_shift_vox=p.get("max_collision_shift_vox", 15), + ) + + +def _resample_config_from_dict(d: dict) -> ResampleConfig: + r = d.get("resample", {}) + return ResampleConfig( + interpolation=r.get("interpolation", "nearest"), + binary_threshold=r.get("binary_threshold", 0.5), + min_component_size_vox=r.get("min_component_size_vox", 3), + fill_holes=r.get("fill_holes", True), + ) + + +# ── Audit record ────────────────────────────────────────────────────────── + + +@dataclass +class InsertionAuditRecord: + """Audit trail for a single nodule insertion.""" + + case_id: str = "" + nodule_idx: int = 0 + is_primary: bool = True + companion_group_id: str = "" + status: str = "success" # success | skipped | failed + reason: str = "" + # Paths used + host_ct_path: str = "" + host_organ_seg_path: str = "" + donor_nodule_mask_path: str = "" + # Placement + insertion_lobe: str = "" + cc_pct: float = 0.0 + ml_pct: float = 0.0 + ap_pct: float = 0.0 + target_ijk: Tuple[int, int, int] | None = None + target_world_mm: Tuple[float, float, float] | None = None + snapped: bool = False + snap_distance_vox: float = 0.0 + pleural_dist_mm: float = 0.0 + overlap_fraction: float = 0.0 + placement_warnings: list = field(default_factory=list) + # Resample + scale_factor: float = 1.0 + donor_mask_voxels: int = 0 + resampled_mask_voxels: int = 0 + # Output + output_mask_path: str = "" + output_combined_path: str = "" + host_id_compact: str = "" + nodule_label_value: int = 23 + elapsed_sec: float = 0.0 + + +# ── Per-row insertion ───────────────────────────────────────────────────── + + +def insert_case( + row: pd.Series | dict, + *, + output_dir: str, + config: dict | None = None, + resolver: ResolverBridge | None = None, + existing_combined: np.ndarray | None = None, + existing_affine: np.ndarray | None = None, + trial_name: str = "unnamed", + seed: int = 42, + dry_run: bool = False, +) -> Tuple[InsertionAuditRecord, np.ndarray | None, np.ndarray | None]: + """Insert a single donor nodule into host space. + + Parameters + ---------- + row : Series or dict + One row from the CohortManifest. + output_dir : str + Root output directory. + config : dict + Merged configuration (see ``load_config``). + resolver : ResolverBridge + For path resolution. + existing_combined : ndarray, optional + Current combined mask for this host (updated in-place for multi-nodule). + existing_affine : ndarray, optional + Affine of the existing combined mask. + trial_name : str + seed : int + dry_run : bool + If True, compute placement but don't write files. + + Returns + ------- + (audit_record, updated_combined_mask, combined_affine) + """ + t0 = time.time() + if isinstance(row, dict): + row = pd.Series(row) + + cfg = config or load_config() + resolver = resolver or ResolverBridge() + placement_cfg = _placement_config_from_dict(cfg) + resample_cfg = _resample_config_from_dict(cfg) + + case_id = str(row.get("case_id", "unknown")) + nodule_idx = int(row.get("nodule_idx", 0)) + + audit = InsertionAuditRecord( + case_id=case_id, + nodule_idx=nodule_idx, + is_primary=bool(row.get("is_primary_nodule", True)), + companion_group_id=str(row.get("companion_group_id", "")), + insertion_lobe=str(row.get("insertion_lobe", "")), + cc_pct=float(row.get("insertion_lobe_cc_pct", 0)), + ml_pct=float(row.get("insertion_lobe_ml_pct", 0)), + ap_pct=float(row.get("insertion_lobe_ap_pct", 0)), + scale_factor=float(row.get("scale_factor", 1.0)), + ) + + # ── 1. Resolve paths ───────────────────────────────────────────────── + paths = resolver.resolve(row) + missing = paths.validate() + if missing: + audit.status = "failed" + audit.reason = f"Missing files: {missing}" + audit.elapsed_sec = time.time() - t0 + logger.warning("Row %s/%d: %s", case_id, nodule_idx, audit.reason) + return audit, existing_combined, existing_affine + + audit.host_ct_path = paths.host_ct + audit.host_organ_seg_path = paths.host_organ_seg + audit.donor_nodule_mask_path = paths.donor_nodule_mask + + # ── 2. Load host organ segmentation ────────────────────────────────── + try: + seg_data, seg_aff, seg_spacing = load_nifti_canonical(paths.host_organ_seg) + except Exception as e: + audit.status = "failed" + audit.reason = f"Failed to load organ seg: {e}" + audit.elapsed_sec = time.time() - t0 + return audit, existing_combined, existing_affine + + host_shape = seg_data.shape + host_spacing = seg_spacing + + # ── 2a. Shape guard: reset combined mask if host geometry changed ───── + # Multi-nodule cases (e.g. LUNA25) may span different CT series with + # different array shapes. When that happens we must re-initialise the + # combined mask from the current organ seg so that later overlap + # checks and voxel stamping don't crash on shape mismatches. + if existing_combined is not None and existing_combined.shape != host_shape: + logger.warning( + "Row %s/%d: host geometry changed from %s to %s — " + "re-initialising combined mask for this CT series.", + case_id, + nodule_idx, + existing_combined.shape, + host_shape, + ) + existing_combined = None + existing_affine = None + + # ── 2b. Sanity check: host seg should not already contain nodule label ─ + nodule_label_value = int(cfg.get("nodule_label_value", 23)) + if existing_combined is None and (seg_data == nodule_label_value).any(): + n_pre = int((seg_data == nodule_label_value).sum()) + logger.warning( + "Row %s/%d: host organ seg already contains %d voxels with " + "nodule label %d — these will be overwritten during insertion.", + case_id, + nodule_idx, + n_pre, + nodule_label_value, + ) + + # ── 3. Compute placement ───────────────────────────────────────────── + case_seed = make_seed(trial_name, case_id, nodule_idx, seed) + rng = np.random.default_rng(case_seed) + + lobe_labels = cfg.get("lobe_labels", None) + lobe_aliases = cfg.get("lobe_aliases", None) + lung_labels = cfg.get("lung_labels", None) + + placement = compute_placement( + seg_data=seg_data, + affine=seg_aff, + voxel_spacing_mm=host_spacing, + insertion_lobe=audit.insertion_lobe, + cc_pct=audit.cc_pct, + ml_pct=audit.ml_pct, + ap_pct=audit.ap_pct, + config=placement_cfg, + existing_combined_mask=existing_combined, + lobe_labels=lobe_labels, + lobe_aliases=lobe_aliases, + lung_labels=lung_labels, + rng=rng, + ) + + audit.target_ijk = placement.center_ijk + audit.target_world_mm = placement.center_world_mm + audit.snapped = placement.snapped + audit.snap_distance_vox = placement.snap_distance_vox + audit.pleural_dist_mm = placement.pleural_dist_mm + audit.placement_warnings = placement.warnings + + if not placement.is_feasible: + audit.status = "failed" + audit.reason = f"Placement infeasible: {placement.reason}" + audit.elapsed_sec = time.time() - t0 + logger.warning("Row %s/%d: %s", case_id, nodule_idx, audit.reason) + return audit, existing_combined, existing_affine + + if dry_run: + audit.status = "dry_run" + audit.elapsed_sec = time.time() - t0 + return audit, existing_combined, existing_affine + + # ── 4. Load donor nodule mask ──────────────────────────────────────── + try: + donor_data, donor_aff, donor_spacing = load_nifti_canonical(paths.donor_nodule_mask) + except Exception as e: + audit.status = "failed" + audit.reason = f"Failed to load donor mask: {e}" + audit.elapsed_sec = time.time() - t0 + return audit, existing_combined, existing_affine + + audit.donor_mask_voxels = int((donor_data > 0).sum()) + + # ── 5. Resample donor into host geometry ───────────────────────────── + scale_factor = audit.scale_factor + target_ijk = placement.center_ijk + + try: + host_nodule_mask = resample_donor_to_host( + donor_mask=donor_data, + donor_affine=donor_aff, + donor_spacing=donor_spacing, + host_shape=host_shape, + host_affine=seg_aff, + host_spacing=host_spacing, + target_center_ijk=target_ijk, + scale_factor=scale_factor, + config=resample_cfg, + ) + except Exception as e: + audit.status = "failed" + audit.reason = f"Resampling failed: {e}" + audit.elapsed_sec = time.time() - t0 + return audit, existing_combined, existing_affine + + audit.resampled_mask_voxels = int((host_nodule_mask > 0).sum()) + + # ── 6. Overlap check & collision resolution ────────────────────────── + if placement_cfg.check_overlap and existing_combined is not None: + frac, ok = check_overlap( + existing_combined, + host_nodule_mask, + placement_cfg.max_overlap_fraction, + ) + audit.overlap_fraction = frac + if not ok: + new_center = resolve_collision( + (seg_data > 0).astype(np.uint8), + existing_combined, + target_ijk, + max_shift=placement_cfg.max_collision_shift_vox, + rng=rng, + ) + if new_center is not None: + audit.placement_warnings.append( + f"Shifted from {target_ijk} to {new_center} to resolve collision." + ) + # Re-resample at new centre + host_nodule_mask = resample_donor_to_host( + donor_mask=donor_data, + donor_affine=donor_aff, + donor_spacing=donor_spacing, + host_shape=host_shape, + host_affine=seg_aff, + host_spacing=host_spacing, + target_center_ijk=new_center, + scale_factor=scale_factor, + config=resample_cfg, + ) + audit.target_ijk = new_center + audit.resampled_mask_voxels = int((host_nodule_mask > 0).sum()) + else: + audit.placement_warnings.append("Could not resolve collision; mask may overlap.") + + # ── 7. Optionally save per-nodule mask ───────────────────────────── + out_cfg = cfg.get("output", {}) + audit.nodule_label_value = nodule_label_value + + if out_cfg.get("save_per_nodule_mask", False): + if out_cfg.get("use_case_subdirs", False): + case_dir = os.path.join(output_dir, case_id) + else: + case_dir = output_dir + + mask_template = out_cfg.get( + "nodule_mask_template", + "case_{case_id}_nodule_{nodule_idx}_mask.nii.gz", + ) + donor_id = str(row.get("donor_annotation_id", f"donor_{nodule_idx}")) + mask_name = mask_template.format( + case_id=str(case_id).zfill(4), + nodule_idx=nodule_idx, + donor_id=donor_id, + host_patient_id=str(row.get("host_patient_id", "")), + host_dataset=str(row.get("host_dataset", "")), + ) + mask_path = os.path.join(case_dir, mask_name) + + labelled_nodule_mask = np.where( + host_nodule_mask > 0, + np.int16(nodule_label_value), + np.int16(0), + ).astype(np.int16) + save_nifti(labelled_nodule_mask, seg_aff, mask_path, dtype=np.int16) + audit.output_mask_path = mask_path + + # ── 8. Update combined mask ────────────────────────────────────────── + if existing_combined is None: + # Initialise from the host organ segmentation so the combined mask + # carries full body context (lobe labels etc.) in addition to the + # inserted nodule voxels. + existing_combined = seg_data.astype(np.int16) + existing_affine = seg_aff + + # Stamp nodule voxels with the label value. + # Overlap check prevents overwriting an already-inserted nodule voxel; + # it does NOT block placement over organ-seg labels (lobe labels are + # overwritten by the nodule, which is the intended behaviour). + insert_where = host_nodule_mask > 0 + if placement_cfg.check_overlap: + # Only refuse to overwrite voxels that already carry the nodule label + # (i.e. a previous nodule in this companion group). + insert_where = insert_where & (existing_combined != nodule_label_value) + existing_combined[insert_where] = nodule_label_value + + audit.status = "success" + audit.elapsed_sec = time.time() - t0 + logger.info( + "Inserted %s/nodule_%d: %d voxels at %s (%.1fs)", + case_id, + nodule_idx, + audit.resampled_mask_voxels, + audit.target_ijk, + audit.elapsed_sec, + ) + return audit, existing_combined, existing_affine + + +# ── Manifest-level orchestration ────────────────────────────────────────── + + +def insert_manifest( + manifest_path: str, + output_dir: str, + *, + config_path: str | None = None, + resolver: ResolverBridge | None = None, + path_resolver: object = None, + base_dir: str | None = None, + trial_name: str | None = None, + seed: int | None = None, + dry_run: bool = False, + n_jobs: int = 1, +) -> list[InsertionAuditRecord]: + """Process an entire CohortManifest. + + Groups rows by case_id to handle multi-nodule companion groups, + processing nodules within a case sequentially (so the combined mask + accumulates correctly). + + Parameters + ---------- + manifest_path : str + Path to manifest CSV or JSON. + output_dir : str + Root output directory. + config_path : str, optional + YAML config overrides. + resolver : ResolverBridge, optional + path_resolver : object, optional + iTrialSpace PathResolver to wrap. + base_dir : str, optional + Fallback base directory for relative paths. + trial_name : str, optional + seed : int, optional + dry_run : bool + n_jobs : int + Parallelism (across cases, not within). + + Returns + ------- + list[InsertionAuditRecord] + """ + cfg = load_config(config_path) + seed = seed or cfg.get("seed", 42) + trial_name = trial_name or "unnamed" + + if resolver is None: + resolver = ResolverBridge(path_resolver=path_resolver, base_dir=base_dir) + + # Load manifest + df = _load_manifest_df(manifest_path) + logger.info( + "Loaded manifest with %d rows from %s", + len(df), + manifest_path, + ) + + # Group by case_id + if "case_id" not in df.columns: + raise ValueError("Manifest must have a 'case_id' column.") + + groups = list(df.groupby("case_id", sort=False)) + logger.info("Processing %d cases.", len(groups)) + + all_records: list[InsertionAuditRecord] = [] + out_cfg = cfg.get("output", {}) + + # Sequential per-case processing (multi-nodule must be sequential) + for case_id, case_df in groups: + if "nodule_idx" in case_df.columns: + case_df = case_df.sort_values("nodule_idx") + combined_mask = None + combined_aff = None + + # Track per-geometry combined masks for cases that span multiple + # CT series (e.g. LUNA25 patients with different-shaped CTs). + # Each entry: (mask_array, affine, [audit_record_indices]) + geo_masks: list[tuple[np.ndarray, np.ndarray | None, list[int]]] = [] + current_geo_audits: list[int] = [] + + for _, row in case_df.iterrows(): + prev_mask = combined_mask + prev_aff = combined_aff + + audit, combined_mask, combined_aff = insert_case( + row, + output_dir=output_dir, + config=cfg, + resolver=resolver, + existing_combined=combined_mask, + existing_affine=combined_aff, + trial_name=trial_name, + seed=seed, + dry_run=dry_run, + ) + + audit_idx = len(all_records) + all_records.append(audit) + + # Detect geometry reset: insert_case created a new combined + # mask array because the host shape changed. + if prev_mask is not None and combined_mask is not prev_mask: + geo_masks.append((prev_mask, prev_aff, current_geo_audits)) + current_geo_audits = [] + + current_geo_audits.append(audit_idx) + + # Finalise last geometry + if combined_mask is not None: + geo_masks.append((combined_mask, combined_aff, current_geo_audits)) + + # Save combined mask(s) per case + if not dry_run and geo_masks: + if out_cfg.get("use_case_subdirs", False): + case_dir = os.path.join(output_dir, str(case_id)) + else: + case_dir = output_dir + + first_row = case_df.iloc[0] + combined_template = out_cfg.get( + "combined_mask_template", + "iTS--{trial_name}--C{case_id}--host-{host_id}--src-{host_dataset}--nod-{donor_id}_mask.nii.gz", + ) + raw_host_id = str(first_row.get("host_patient_id", "")) + compact_host_id = _compact_id(raw_host_id) + + if len(case_df) > 1: + donor_id_str = f"Nnod{len(case_df)}" + else: + donor_id_str = str(first_row.get("donor_annotation_id", "")) + + base_combined_name = combined_template.format( + trial_name=str(first_row.get("trial_name", trial_name)), + case_id=str(case_id).zfill(4), + host_id=compact_host_id, + host_dataset=str(first_row.get("host_dataset", "")), + donor_id=donor_id_str, + ) + + multi_geo = len(geo_masks) > 1 + if multi_geo: + logger.info( + "Case %s spans %d CT geometries; saving separate " + "combined masks per geometry.", + case_id, + len(geo_masks), + ) + + for geo_idx, (mask, aff, audit_indices) in enumerate(geo_masks): + if not mask.any(): + continue + if aff is None: + aff = np.eye(4) + + # Append _ct{N} suffix for multi-geometry cases so each + # CT series gets its own combined mask file. + if multi_geo: + combined_name = base_combined_name.replace( + "_mask.nii.gz", + f"_ct{geo_idx}_mask.nii.gz", + ) + else: + combined_name = base_combined_name + + combined_path = os.path.join(case_dir, combined_name) + save_nifti(mask, aff, combined_path, dtype=np.int16) + + for ai in audit_indices: + all_records[ai].output_combined_path = combined_path + all_records[ai].host_id_compact = compact_host_id + + # Write audit JSON + if not dry_run: + audit_name = out_cfg.get("audit_name", "audit.json") + audit_path = os.path.join(output_dir, audit_name) + _write_audit(all_records, audit_path, trial_name, manifest_path) + + n_ok = sum(1 for r in all_records if r.status == "success") + n_fail = sum(1 for r in all_records if r.status == "failed") + logger.info( + "Done: %d success, %d failed, %d total.", + n_ok, + n_fail, + len(all_records), + ) + + return all_records + + +# ── Helpers ─────────────────────────────────────────────────────────────── + + +def _load_manifest_df(path: str) -> pd.DataFrame: + """Load manifest from CSV or JSON.""" + if path.endswith(".json"): + with open(path) as f: + data = json.load(f) + if isinstance(data, list): + return pd.DataFrame(data) + if "cases" in data: + return pd.DataFrame(data["cases"]) + raise ValueError("JSON manifest must be a list or have a 'cases' key.") + return pd.read_csv(path) + + +def _write_audit( + records: list[InsertionAuditRecord], + path: str, + trial_name: str, + manifest_path: str, +) -> None: + """Write audit trail as JSON.""" + os.makedirs(os.path.dirname(path) or ".", exist_ok=True) + data = { + "trial_name": trial_name, + "manifest_path": manifest_path, + "n_total": len(records), + "n_success": sum(1 for r in records if r.status == "success"), + "n_failed": sum(1 for r in records if r.status == "failed"), + "records": [_audit_to_dict(r) for r in records], + } + with open(path, "w") as f: + json.dump(data, f, indent=2, default=str) + logger.info("Audit written to %s", path) + + +def _audit_to_dict(r: InsertionAuditRecord) -> dict[str, Any]: + """Convert audit record to a JSON-safe dict.""" + d = asdict(r) + # Convert tuples to lists for JSON + for key in ("target_ijk", "target_world_mm"): + if d[key] is not None: + d[key] = list(d[key]) + return d diff --git a/itrialspace/src/itrialspace/mask_inserter/placement.py b/itrialspace/src/itrialspace/mask_inserter/placement.py new file mode 100644 index 0000000000000000000000000000000000000000..6ed23d768a82c79a988de4ff7ff9e675727f9088 --- /dev/null +++ b/itrialspace/src/itrialspace/mask_inserter/placement.py @@ -0,0 +1,628 @@ +# -*- coding: utf-8 -*- +""" +placement.py — Percentile-to-voxel conversion, snapping, pleural-margin +enforcement, and overlap/collision avoidance for nodule insertion. + +Coordinate convention: all index operations are performed **after** +canonicalising both the host CT and organ-segmentation to RAS+ orientation +using ``nibabel.as_closest_canonical``. In RAS+: + + axis 0 → Right→Left (X / mediolateral) + axis 1 → Anterior→Posterior (Y / anteroposterior) + axis 2 → Inferior→Superior (Z / craniocaudal) + +Percentile mapping: + + voxel_i = i_min + (ml_pct / 100) × (i_max − i_min) + voxel_j = j_min + (ap_pct / 100) × (j_max − j_min) + voxel_k = k_min + (cc_pct / 100) × (k_max − k_min) + +where (i_min…i_max, j_min…j_max, k_min…k_max) is the bounding box of +the target structure mask in canonical index space. +""" + +from __future__ import annotations + +import hashlib +from dataclasses import dataclass, field +from typing import Optional, Tuple + +import numpy as np +from scipy import ndimage + +# ── Data classes ────────────────────────────────────────────────────────── + + +@dataclass +class PlacementResult: + """Output of the placement algorithm.""" + + center_ijk: Optional[Tuple[int, int, int]] = None + center_world_mm: Optional[Tuple[float, float, float]] = None + is_feasible: bool = True + snapped: bool = False + snap_distance_vox: float = 0.0 + pleural_dist_mm: float = float("inf") + overlap_fraction: float = 0.0 + warnings: list = field(default_factory=list) + reason: str = "" + + +@dataclass +class PlacementConfig: + """Parameters governing placement decisions.""" + + max_snap_radius_vox: int = 25 + min_pleural_dist_mm: float = 2.0 + check_overlap: bool = True + max_overlap_fraction: float = 0.05 + max_collision_shift_vox: int = 15 + + +# ── Lobe label resolution ──────────────────────────────────────────────── + +# Canonical VISTA3D lobe labels. +DEFAULT_LOBE_LABELS = { + "left_lung_upper_lobe": 28, + "left_lung_lower_lobe": 29, + "right_lung_upper_lobe": 30, + "right_lung_middle_lobe": 31, + "right_lung_lower_lobe": 32, +} + +DEFAULT_LOBE_ALIASES = { + "lul": "left_lung_upper_lobe", + "lll": "left_lung_lower_lobe", + "rul": "right_lung_upper_lobe", + "rml": "right_lung_middle_lobe", + "rll": "right_lung_lower_lobe", + "left_upper": "left_lung_upper_lobe", + "left_lower": "left_lung_lower_lobe", + "right_upper": "right_lung_upper_lobe", + "right_middle": "right_lung_middle_lobe", + "right_lower": "right_lung_lower_lobe", +} + + +def resolve_lobe_label( + lobe_name: str, + lobe_labels: dict | None = None, + lobe_aliases: dict | None = None, +) -> int: + """Resolve a human-readable lobe name to its integer segmentation label. + + Parameters + ---------- + lobe_name : str + Raw value from the manifest ``insertion_lobe`` column. + lobe_labels : dict, optional + Canonical name → int mapping. Defaults to VISTA3D labels. + lobe_aliases : dict, optional + Alias → canonical name mapping. + + Returns + ------- + int Label ID in the organ segmentation. + + Raises + ------ + KeyError If the lobe name cannot be resolved. + """ + lobe_labels = lobe_labels or DEFAULT_LOBE_LABELS + lobe_aliases = lobe_aliases or DEFAULT_LOBE_ALIASES + + key = lobe_name.strip().lower().replace(" ", "_") + + # Direct hit + if key in lobe_labels: + return lobe_labels[key] + + # Alias + canonical = lobe_aliases.get(key) + if canonical and canonical in lobe_labels: + return lobe_labels[canonical] + + raise KeyError( + f"Cannot resolve lobe '{lobe_name}' (normalised='{key}'). " + f"Known lobes: {list(lobe_labels.keys())}; aliases: {list(lobe_aliases.keys())}" + ) + + +# ── Target mask extraction ──────────────────────────────────────────────── + + +def extract_target_mask( + seg_data: np.ndarray, + insertion_lobe: str, + lobe_labels: dict | None = None, + lobe_aliases: dict | None = None, + lung_labels: list[int] | None = None, +) -> Tuple[np.ndarray, str]: + """Extract a binary mask for the target structure. + + Strategy: + 1. If the target lobe label exists in ``seg_data``, use it. + 2. Else if the target *side* (left/right) is identifiable, use the union + of that side's lobes as fallback. + 3. Else use the whole-lung mask (union of all lobe labels). + 4. If nothing found, return an empty mask. + + Parameters + ---------- + seg_data : ndarray + 3-D integer organ segmentation (canonical RAS+ space). + insertion_lobe : str + Target lobe from the manifest. + lobe_labels, lobe_aliases : dict, optional + lung_labels : list[int], optional + Label IDs that are considered "lung parenchyma". + + Returns + ------- + (mask, fallback_level) where *fallback_level* is one of + ``"lobe"``, ``"side"``, ``"lung"``, or ``"empty"``. + """ + lobe_labels = lobe_labels or DEFAULT_LOBE_LABELS + lobe_aliases = lobe_aliases or DEFAULT_LOBE_ALIASES + lung_labels = lung_labels or list(lobe_labels.values()) + + # Attempt exact lobe + try: + label_id = resolve_lobe_label(insertion_lobe, lobe_labels, lobe_aliases) + except KeyError: + label_id = None + + if label_id is not None and np.any(seg_data == label_id): + return (seg_data == label_id).astype(np.uint8), "lobe" + + # Fallback: side + key = insertion_lobe.strip().lower().replace(" ", "_") + canonical = lobe_aliases.get(key, key) + if "left" in canonical: + side_ids = [v for k, v in lobe_labels.items() if "left" in k] + elif "right" in canonical: + side_ids = [v for k, v in lobe_labels.items() if "right" in k] + else: + side_ids = [] + + if side_ids: + side_mask = np.isin(seg_data, side_ids).astype(np.uint8) + if side_mask.any(): + return side_mask, "side" + + # Fallback: whole lung + lung_mask = np.isin(seg_data, lung_labels).astype(np.uint8) + if lung_mask.any(): + return lung_mask, "lung" + + return np.zeros_like(seg_data, dtype=np.uint8), "empty" + + +# ── Bounding-box helpers ────────────────────────────────────────────────── + + +def mask_bounding_box(mask: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: + """Axis-aligned bounding box of nonzero voxels. + + Returns (mins, maxs) each of shape (ndim,). Raises ValueError on empty. + """ + nz = np.argwhere(mask > 0) + if nz.size == 0: + raise ValueError("Empty mask — no bounding box.") + return nz.min(axis=0), nz.max(axis=0) + + +# ── Core percentile → voxel ────────────────────────────────────────────── + + +def percentile_to_voxel( + target_mask: np.ndarray, + cc_pct: float, + ml_pct: float, + ap_pct: float, +) -> Tuple[int, int, int]: + """Convert lobe-relative percentile coordinates to an initial voxel index. + + In RAS+ canonical space: + axis 0 = mediolateral (R→L) ← ml_pct + axis 1 = anteroposterior (A→P) ← ap_pct + axis 2 = craniocaudal (I→S) ← cc_pct + + **Coordinate reliability notes (iTrialSpace schema)**: + - cc_pct: clean 0-100 percentile; used directly for the K axis. + - ml_pct / ap_pct: known pipeline-normalisation bug — 93 %+ of values + fall outside [0, 100] in real datasets. When either is outside the + valid range the function falls back to the lobe centroid at the target + CC slab for the I/J axes, ensuring the initial candidate always lands + inside (or very close to) the lobe. + + Returns (i, j, k) in canonical index space. The initial candidate is + guaranteed to land inside (or within a few voxels of) the target mask. + """ + mins, maxs = mask_bounding_box(target_mask) + + # ── K axis: map cc_pct through *occupied* slices only ──────────────── + # The bounding-box range [k_min, k_max] can span large internal gaps + # (e.g. post-surgical anatomy in NSCLCR where lobes are fragmented). + # Interpolating within the bounding box would map cc_pct into a void. + # Instead, collect the k-slices that actually contain lobe voxels and + # use cc_pct to index into that sorted array. This guarantees k0 + # always lands on a slice with lobe tissue. + cc_pct_clamped = max(0.0, min(100.0, cc_pct)) + k_occupied = np.unique(np.nonzero(target_mask)[2]) + if len(k_occupied) == 1: + k0 = int(k_occupied[0]) + else: + idx = cc_pct_clamped / 100.0 * (len(k_occupied) - 1) + k0 = int(k_occupied[int(round(idx))]) + + # ── I/J axes: use percentile only when both values are in [0, 100] ─── + # Outside that range the values are mm-scale artefacts from the upstream + # normalisation bug; in that case use the centroid of lobe voxels in the + # CC slab around k0 (robust fallback). + # + # Even when ml/ap are in-range, the bounding-box interpolation can land + # outside a non-convex lobe cross-section. We start from the + # interpolated position but snap (i0, j0) to the nearest actual lobe + # voxel in the CC slab so the candidate is always inside the mask. + k_lo = max(0, k0 - 5) + k_hi = min(target_mask.shape[2], k0 + 6) + slab = target_mask[:, :, k_lo:k_hi] + nz = np.argwhere(slab) + if len(nz) == 0: + # Should not happen now that k0 is on an occupied slice, but + # keep the whole-lobe fallback for safety. + nz = np.argwhere(target_mask) + + if 0.0 <= ml_pct <= 100.0 and 0.0 <= ap_pct <= 100.0: + # Bounding-box interpolation → snap to nearest slab voxel + i_raw = mins[0] + (ml_pct / 100.0) * (maxs[0] - mins[0]) + j_raw = mins[1] + (ap_pct / 100.0) * (maxs[1] - mins[1]) + dists2d = ((nz[:, 0] - i_raw) ** 2 + (nz[:, 1] - j_raw) ** 2) ** 0.5 + nearest = nz[int(dists2d.argmin())] + i0, j0 = int(nearest[0]), int(nearest[1]) + else: + # Pick the lobe voxel nearest to the centroid within the CC slab. + ci = float(nz[:, 0].mean()) + cj = float(nz[:, 1].mean()) + dists2d = ((nz[:, 0] - ci) ** 2 + (nz[:, 1] - cj) ** 2) ** 0.5 + nearest = nz[int(dists2d.argmin())] + i0, j0 = int(nearest[0]), int(nearest[1]) + + return (i0, j0, k0) + + +# ── Snap to nearest valid voxel ────────────────────────────────────────── + + +def snap_to_mask( + target_mask: np.ndarray, + ijk: Tuple[int, int, int], + max_radius: int = 25, +) -> Tuple[Tuple[int, int, int], float]: + """Snap *ijk* to the nearest voxel inside *target_mask*. + + Uses a distance-transform approach for efficiency: compute the Euclidean + distance from the candidate point to all True voxels and pick the closest. + + Parameters + ---------- + target_mask : ndarray (bool / uint8) + ijk : (i, j, k) + max_radius : int Search radius in voxels. + + Returns + ------- + ((i, j, k), dist) – snapped index and distance in voxels. + Returns (ijk, 0.0) if already inside. + Returns (None, inf) if no valid voxel within radius. + """ + i, j, k = ijk + # Clamp to array bounds + shape = target_mask.shape + ic = max(0, min(i, shape[0] - 1)) + jc = max(0, min(j, shape[1] - 1)) + kc = max(0, min(k, shape[2] - 1)) + + if target_mask[ic, jc, kc]: + return (ic, jc, kc), 0.0 + + # Extract a local cube around the candidate + lo = np.array([ic, jc, kc]) - max_radius + hi = np.array([ic, jc, kc]) + max_radius + 1 + lo_clamped = np.maximum(lo, 0) + hi_clamped = np.minimum(hi, shape) + + local_mask = target_mask[ + lo_clamped[0] : hi_clamped[0], + lo_clamped[1] : hi_clamped[1], + lo_clamped[2] : hi_clamped[2], + ] + + nz = np.argwhere(local_mask > 0) + if nz.size == 0: + return None, float("inf") # type: ignore[return-value] + + # Shift to global coords, compute distance + nz_global = nz + lo_clamped[None, :] + dists = np.linalg.norm(nz_global - np.array([ic, jc, kc])[None, :], axis=1) + best = int(np.argmin(dists)) + best_dist = float(dists[best]) + + if best_dist > max_radius: + return None, float("inf") # type: ignore[return-value] + + best_ijk = tuple(int(x) for x in nz_global[best]) + return best_ijk, best_dist # type: ignore[return-value] + + +# ── Pleural distance enforcement ───────────────────────────────────────── + + +def compute_pleural_distance_map( + lung_mask: np.ndarray, + voxel_spacing_mm: Tuple[float, float, float], +) -> np.ndarray: + """Euclidean distance transform from the lung boundary into the interior. + + Returns an array of same shape as *lung_mask* where each voxel stores + its distance (mm) to the nearest lung-boundary voxel. + Voxels outside the lung have distance 0. + """ + # Interior voxels = lung_mask > 0 + dist = ndimage.distance_transform_edt( + lung_mask.astype(bool), + sampling=voxel_spacing_mm, + ) + return dist.astype(np.float32) + + +def enforce_pleural_margin( + target_mask: np.ndarray, + pleural_map: np.ndarray, + ijk: Tuple[int, int, int], + min_dist_mm: float, + max_shift: int = 15, +) -> Tuple[Tuple[int, int, int], float]: + """Move *ijk* inward if it violates the pleural safety margin. + + Searches among target-mask voxels within *max_shift* for the closest + one that satisfies the margin. + + Returns (new_ijk, pleural_dist_mm). + """ + i, j, k = ijk + shape = target_mask.shape + ic = max(0, min(i, shape[0] - 1)) + jc = max(0, min(j, shape[1] - 1)) + kc = max(0, min(k, shape[2] - 1)) + + current_dist = float(pleural_map[ic, jc, kc]) + if current_dist >= min_dist_mm: + return (ic, jc, kc), current_dist + + # Search nearby for a valid voxel + lo = np.maximum(np.array([ic, jc, kc]) - max_shift, 0) + hi = np.minimum(np.array([ic, jc, kc]) + max_shift + 1, shape) + + local_mask = target_mask[lo[0] : hi[0], lo[1] : hi[1], lo[2] : hi[2]] + local_pleu = pleural_map[lo[0] : hi[0], lo[1] : hi[1], lo[2] : hi[2]] + + # Candidate voxels: inside target mask AND satisfying margin + candidates = np.argwhere((local_mask > 0) & (local_pleu >= min_dist_mm)) + if candidates.size == 0: + # Relax: just pick deepest voxel inside target mask within region + in_mask = np.argwhere(local_mask > 0) + if in_mask.size == 0: + return (ic, jc, kc), current_dist + pleu_vals = local_pleu[in_mask[:, 0], in_mask[:, 1], in_mask[:, 2]] + best = int(np.argmax(pleu_vals)) + g = tuple(int(x) for x in (in_mask[best] + lo)) + return g, float(pleu_vals[best]) # type: ignore[return-value] + + # Pick closest candidate to original point + cand_global = candidates + lo[None, :] + dists = np.linalg.norm( + cand_global - np.array([ic, jc, kc])[None, :], + axis=1, + ) + best = int(np.argmin(dists)) + g = tuple(int(x) for x in cand_global[best]) + pdist = float(pleural_map[g[0], g[1], g[2]]) + return g, pdist # type: ignore[return-value] + + +# ── Overlap / collision check ───────────────────────────────────────────── + + +def check_overlap( + existing_mask: np.ndarray | None, + donor_mask_host: np.ndarray, + max_fraction: float = 0.05, +) -> Tuple[float, bool]: + """Compute overlap fraction between a new donor mask and existing nodules. + + Returns (fraction, is_acceptable). + """ + if existing_mask is None: + return 0.0, True + donor_vox = donor_mask_host > 0 + n_donor = int(donor_vox.sum()) + if n_donor == 0: + return 0.0, True + # Defensive: skip overlap check if shapes don't match (different CT series) + if existing_mask.shape != donor_mask_host.shape: + return 0.0, True + overlap = int((donor_vox & (existing_mask > 0)).sum()) + frac = overlap / n_donor + return frac, frac <= max_fraction + + +def resolve_collision( + target_mask: np.ndarray, + existing_mask: np.ndarray, + ijk: Tuple[int, int, int], + max_shift: int = 15, + rng: np.random.Generator | None = None, +) -> Tuple[int, int, int] | None: + """Attempt to shift *ijk* to avoid collision with existing nodules. + + Returns a new center or None if no collision-free spot found. + """ + rng = rng or np.random.default_rng(42) + shape = target_mask.shape + i, j, k = ijk + + lo = np.maximum(np.array([i, j, k]) - max_shift, 0) + hi = np.minimum(np.array([i, j, k]) + max_shift + 1, shape) + + local_target = target_mask[lo[0] : hi[0], lo[1] : hi[1], lo[2] : hi[2]] + local_exist = existing_mask[lo[0] : hi[0], lo[1] : hi[1], lo[2] : hi[2]] + + candidates = np.argwhere((local_target > 0) & (local_exist == 0)) + if candidates.size == 0: + return None + + cand_global = candidates + lo[None, :] + dists = np.linalg.norm( + cand_global - np.array([i, j, k])[None, :], + axis=1, + ) + # Sort by distance, pick from top-5 with slight randomness for diversity + order = np.argsort(dists)[:5] + pick = rng.choice(order) + return tuple(int(x) for x in cand_global[pick]) # type: ignore[return-value] + + +# ── Deterministic RNG seed ──────────────────────────────────────────────── + + +def make_seed( + trial_name: str, + case_id: str, + nodule_idx: int = 0, + global_seed: int = 42, +) -> int: + """Derive a deterministic seed from case identifiers. + + Uses SHA-256 truncated to 32 bits, mixed with the global seed. + """ + h = hashlib.sha256(f"{trial_name}|{case_id}|{nodule_idx}|{global_seed}".encode()).hexdigest() + return int(h[:8], 16) & 0x7FFFFFFF + + +# ── Top-level placement orchestrator ────────────────────────────────────── + + +def compute_placement( + seg_data: np.ndarray, + affine: np.ndarray, + voxel_spacing_mm: Tuple[float, float, float], + insertion_lobe: str, + cc_pct: float, + ml_pct: float, + ap_pct: float, + config: PlacementConfig | None = None, + existing_combined_mask: np.ndarray | None = None, + lobe_labels: dict | None = None, + lobe_aliases: dict | None = None, + lung_labels: list[int] | None = None, + rng: np.random.Generator | None = None, +) -> PlacementResult: + """Full placement pipeline: percentile → voxel → snap → pleural → collision. + + Parameters + ---------- + seg_data : ndarray + Host organ segmentation in canonical RAS+ space. + affine : ndarray (4×4) + Canonical RAS+ affine (voxel → world mm). + voxel_spacing_mm : (sx, sy, sz) + Voxel dimensions in mm along each RAS+ axis. + insertion_lobe, cc_pct, ml_pct, ap_pct : float + Target from the manifest. + config : PlacementConfig + existing_combined_mask : ndarray, optional + Existing nodule mask in host space (for overlap checking). + lobe_labels, lobe_aliases, lung_labels : dict / list, optional + rng : numpy Generator, optional + + Returns + ------- + PlacementResult + """ + cfg = config or PlacementConfig() + result = PlacementResult() + + # 1. Extract target mask + target_mask, fallback = extract_target_mask( + seg_data, + insertion_lobe, + lobe_labels, + lobe_aliases, + lung_labels, + ) + if fallback == "empty": + result.is_feasible = False + result.reason = "No lung voxels found in organ segmentation." + return result + if fallback != "lobe": + result.warnings.append(f"Lobe not found; using {fallback} fallback.") + + # 2. Percentile → initial voxel + try: + ijk0 = percentile_to_voxel(target_mask, cc_pct, ml_pct, ap_pct) + except ValueError as e: + result.is_feasible = False + result.reason = f"Percentile mapping failed: {e}" + return result + + # 3. Snap to target mask + ijk, snap_dist = snap_to_mask(target_mask, ijk0, cfg.max_snap_radius_vox) + if ijk is None: + result.is_feasible = False + result.reason = ( + f"Cannot snap to target mask within {cfg.max_snap_radius_vox} vox " + f"(initial candidate {ijk0})." + ) + return result + if snap_dist > 0: + result.snapped = True + result.snap_distance_vox = snap_dist + result.warnings.append( + f"Snapped {snap_dist:.1f} vox from initial candidate {ijk0} to {ijk}." + ) + + # 4. Pleural margin + if cfg.min_pleural_dist_mm > 0: + # Build lung mask for pleural distance + all_lung_labels = lung_labels or list((lobe_labels or DEFAULT_LOBE_LABELS).values()) + lung_mask = np.isin(seg_data, all_lung_labels).astype(np.uint8) + if lung_mask.any(): + pleural_map = compute_pleural_distance_map(lung_mask, voxel_spacing_mm) + ijk, pdist = enforce_pleural_margin( + target_mask, + pleural_map, + ijk, + cfg.min_pleural_dist_mm, + max_shift=cfg.max_collision_shift_vox, + ) + result.pleural_dist_mm = pdist + if pdist < cfg.min_pleural_dist_mm: + result.warnings.append( + f"Pleural margin {pdist:.1f} mm < {cfg.min_pleural_dist_mm} mm; " + "could not fully satisfy margin." + ) + + # 5. Collision check (deferred until donor mask is placed) + # We record the center; collision is re-checked in the inserter after + # the donor mask is pasted. + + result.center_ijk = ijk + + # Convert to world coords + ijk_h = np.array([ijk[0], ijk[1], ijk[2], 1.0]) + world = affine @ ijk_h + result.center_world_mm = tuple(float(x) for x in world[:3]) # type: ignore[assignment] + + return result diff --git a/itrialspace/src/itrialspace/mask_inserter/resample.py b/itrialspace/src/itrialspace/mask_inserter/resample.py new file mode 100644 index 0000000000000000000000000000000000000000..47ccd17374d2990884ba1858f4e7e46b60ecc631 --- /dev/null +++ b/itrialspace/src/itrialspace/mask_inserter/resample.py @@ -0,0 +1,322 @@ +# -*- coding: utf-8 -*- +""" +resample.py — Donor mask extraction, scaling/resampling into host +geometry, and binary cleanup. + +The resampling pipeline: + +1. Load donor nodule mask and canonicalise to RAS+. +2. Extract the largest connected component (in case of multi-label artifacts). +3. Build a SimpleITK similarity or affine transform that: + a. Scales the donor by the manifest scale_factor (isotropic or per-axis). + b. Translates the donor centre to the target insertion point in host space. +4. Resample the donor mask onto the host CT grid using nearest-neighbour. +5. Apply binary cleanup: threshold, remove small components, fill holes. +6. Return the mask as a numpy array matching host shape. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Tuple + +import nibabel as nib +import numpy as np +from scipy import ndimage + + +@dataclass +class ResampleConfig: + """Parameters governing resampling behaviour.""" + + interpolation: str = "nearest" # nearest | linear + binary_threshold: float = 0.5 + min_component_size_vox: int = 3 + fill_holes: bool = True + + +# ── NIfTI helpers ───────────────────────────────────────────────────────── + + +def load_nifti_canonical(path: str) -> Tuple[np.ndarray, np.ndarray, Tuple[float, ...]]: + """Load a NIfTI file, canonicalise to RAS+. + + Returns (data, affine_4x4, voxel_spacing). + """ + img = nib.load(path) + img_can = nib.as_closest_canonical(img) + data = np.asarray(img_can.dataobj) + aff = img_can.affine.copy() + spacing = tuple(float(s) for s in img_can.header.get_zooms()[:3]) + return data, aff, spacing + + +def save_nifti( + data: np.ndarray, + affine: np.ndarray, + path: str, + *, + dtype: np.dtype | type = np.uint8, +) -> None: + """Save a numpy array as a NIfTI file (optionally compressed).""" + import os + + os.makedirs(os.path.dirname(path) or ".", exist_ok=True) + img = nib.Nifti1Image(data.astype(dtype), affine) + nib.save(img, path) + + +# ── Connected-component extraction ─────────────────────────────────────── + + +def largest_connected_component(mask: np.ndarray) -> np.ndarray: + """Extract the largest connected component from a binary mask. + + Returns a uint8 mask with only the largest component set to 1. + """ + binary = (mask > 0).astype(np.uint8) + labelled, n_labels = ndimage.label(binary) + if n_labels <= 1: + return binary + + sizes = ndimage.sum(binary, labelled, range(1, n_labels + 1)) + biggest = int(np.argmax(sizes)) + 1 + return (labelled == biggest).astype(np.uint8) + + +# ── Centre of mass ──────────────────────────────────────────────────────── + + +def mask_centre_of_mass(mask: np.ndarray) -> Tuple[float, float, float]: + """Centre of mass of nonzero voxels in voxel coordinates.""" + com = ndimage.center_of_mass(mask.astype(float)) + return (float(com[0]), float(com[1]), float(com[2])) + + +# ── Donor bounding-box crop ────────────────────────────────────────────── + + +def crop_to_bbox( + mask: np.ndarray, + padding: int = 2, +) -> Tuple[np.ndarray, Tuple[int, int, int]]: + """Crop a 3-D mask to its tight bounding box plus padding. + + Returns (cropped_mask, origin_offset_ijk). + """ + nz = np.argwhere(mask > 0) + if nz.size == 0: + return mask, (0, 0, 0) + lo = np.maximum(nz.min(axis=0) - padding, 0) + hi = np.minimum(nz.max(axis=0) + padding + 1, mask.shape) + cropped = mask[lo[0] : hi[0], lo[1] : hi[1], lo[2] : hi[2]] + return cropped, tuple(int(x) for x in lo) # type: ignore[return-value] + + +# ── Scipy-based resampling ─────────────────────────────────────────────── + + +def resample_donor_to_host( + donor_mask: np.ndarray, + donor_affine: np.ndarray, + donor_spacing: Tuple[float, float, float], + host_shape: Tuple[int, int, int], + host_affine: np.ndarray, + host_spacing: Tuple[float, float, float], + target_center_ijk: Tuple[int, int, int], + scale_factor: float = 1.0, + config: ResampleConfig | None = None, +) -> np.ndarray: + """Resample a donor mask into host space. + + Algorithm: + 1. Extract largest connected component from donor mask. + 2. Crop to tight bounding box. + 3. Scale the cropped mask using scipy.ndimage.zoom (if scale_factor != 1). + 4. Adjust voxel sizes: zoom each axis by donor_spacing/host_spacing so + the physical size is preserved when pasted into host voxel grid. + 5. Paste the (scaled) donor into host space centred at target_center_ijk. + 6. Binary cleanup. + + Returns a uint8 array of shape ``host_shape``. + """ + cfg = config or ResampleConfig() + + # ── Extract largest component and crop ──────────────────────────────── + donor_lcc = largest_connected_component(donor_mask) + cropped, _ = crop_to_bbox(donor_lcc, padding=1) + + # ── Compute effective zoom factors ──────────────────────────────────── + # Two reasons to zoom: + # a) scale_factor from the manifest (e.g. grow/shrink the nodule) + # b) spacing mismatch between donor and host voxel grids + zoom_factors = tuple(scale_factor * (ds / hs) for ds, hs in zip(donor_spacing, host_spacing)) + + needs_zoom = any(abs(z - 1.0) > 0.01 for z in zoom_factors) + + if needs_zoom: + zoomed = ndimage.zoom( + cropped.astype(np.float32), + zoom_factors, + order=1, + ) + zoomed = (zoomed >= 0.5).astype(np.uint8) + else: + zoomed = cropped + + # ── Paste into host space ───────────────────────────────────────────── + result = _paste_cropped(zoomed, host_shape, target_center_ijk) + + # ── Binary cleanup ──────────────────────────────────────────────────── + result = binary_cleanup(result, cfg) + + return result + + +def _paste_cropped( + cropped: np.ndarray, + host_shape: Tuple[int, int, int], + center_ijk: Tuple[int, int, int], +) -> np.ndarray: + """Paste a cropped donor mask into host space centred at center_ijk.""" + result = np.zeros(host_shape, dtype=np.uint8) + d_shape = np.array(cropped.shape) + center = np.array(center_ijk) + + # Compute destination region (donor centre-of-mass → target centre) + donor_com = np.array(ndimage.center_of_mass((cropped > 0).astype(float))) + offset = np.round(center - donor_com).astype(int) + + dst_lo = offset + dst_hi = offset + d_shape + + # Clip to host bounds + src_lo = np.maximum(-dst_lo, 0) + src_hi = d_shape - np.maximum(dst_hi - np.array(host_shape), 0) + dst_lo_c = np.maximum(dst_lo, 0) + dst_hi_c = np.minimum(dst_hi, np.array(host_shape)) + + if np.all(src_lo < src_hi) and np.all(dst_lo_c < dst_hi_c): + result[ + dst_lo_c[0] : dst_hi_c[0], + dst_lo_c[1] : dst_hi_c[1], + dst_lo_c[2] : dst_hi_c[2], + ] = cropped[ + src_lo[0] : src_hi[0], + src_lo[1] : src_hi[1], + src_lo[2] : src_hi[2], + ] + + return result + + +# ── Binary mask cleanup ────────────────────────────────────────────────── + + +def binary_cleanup(mask: np.ndarray, config: ResampleConfig | None = None) -> np.ndarray: + """Threshold, remove small components, optionally fill holes.""" + cfg = config or ResampleConfig() + + # Threshold + binary = (mask >= cfg.binary_threshold).astype(np.uint8) + + # Remove small connected components + if cfg.min_component_size_vox > 0: + labelled, n = ndimage.label(binary) + if n > 0: + sizes = ndimage.sum(binary, labelled, range(1, n + 1)) + for idx, size in enumerate(sizes, start=1): + if size < cfg.min_component_size_vox: + binary[labelled == idx] = 0 + + # Fill holes + if cfg.fill_holes: + binary = ndimage.binary_fill_holes(binary).astype(np.uint8) + + return binary + + +# ── Direct paste (fallback / no-scale path) ────────────────────────────── + + +def paste_donor_direct( + donor_mask: np.ndarray, + host_shape: Tuple[int, int, int], + target_center_ijk: Tuple[int, int, int], +) -> np.ndarray: + """Paste a donor mask directly into host space at the given centre. + + Used when scale_factor == 1.0 and donor/host have identical spacing, + so no resampling is needed — just a simple array copy with bounds + clipping. + + Returns a uint8 array of shape ``host_shape``. + """ + donor_lcc = largest_connected_component(donor_mask) + donor_com = mask_centre_of_mass(donor_lcc) + + # Compute the offset to align donor COM with target centre + offset = np.array(target_center_ijk) - np.array(donor_com) + offset = np.round(offset).astype(int) + + result = np.zeros(host_shape, dtype=np.uint8) + + # Compute source and destination slicing + nz = np.argwhere(donor_lcc > 0) + if nz.size == 0: + return result + + for idx in range(len(nz)): + i, j, k = nz[idx] + offset + if 0 <= i < host_shape[0] and 0 <= j < host_shape[1] and 0 <= k < host_shape[2]: + result[i, j, k] = 1 + + return result + + +# ── Efficient paste using array slicing ────────────────────────────────── + + +def paste_donor_array( + donor_mask: np.ndarray, + host_shape: Tuple[int, int, int], + target_center_ijk: Tuple[int, int, int], +) -> np.ndarray: + """Faster paste using array slicing rather than per-voxel iteration. + + Centres the donor mask at target_center_ijk in host space. + Returns a uint8 array of shape ``host_shape``. + """ + donor_lcc = largest_connected_component(donor_mask) + donor_com = np.array(mask_centre_of_mass(donor_lcc)) + target = np.array(target_center_ijk, dtype=float) + + # Shift = how much to move donor indices to align COM with target + shift = np.round(target - donor_com).astype(int) + + # Compute valid overlap region + d_shape = np.array(donor_lcc.shape) + h_shape = np.array(host_shape) + + # Donor index ranges in host space + dst_lo = shift + dst_hi = shift + d_shape + + # Clip to host bounds + src_lo = np.maximum(-dst_lo, 0) + src_hi = d_shape - np.maximum(dst_hi - h_shape, 0) + dst_lo_clipped = np.maximum(dst_lo, 0) + dst_hi_clipped = np.minimum(dst_hi, h_shape) + + result = np.zeros(host_shape, dtype=np.uint8) + + # Check for valid overlap + if np.all(src_lo < src_hi) and np.all(dst_lo_clipped < dst_hi_clipped): + donor_crop = donor_lcc[src_lo[0] : src_hi[0], src_lo[1] : src_hi[1], src_lo[2] : src_hi[2]] + result[ + dst_lo_clipped[0] : dst_hi_clipped[0], + dst_lo_clipped[1] : dst_hi_clipped[1], + dst_lo_clipped[2] : dst_hi_clipped[2], + ] = donor_crop + + return result diff --git a/itrialspace/src/itrialspace/mask_inserter/resolver_bridge.py b/itrialspace/src/itrialspace/mask_inserter/resolver_bridge.py new file mode 100644 index 0000000000000000000000000000000000000000..e1e03434d76ba32427c46ab5ce846e0a05ed3c87 --- /dev/null +++ b/itrialspace/src/itrialspace/mask_inserter/resolver_bridge.py @@ -0,0 +1,185 @@ +# -*- coding: utf-8 -*- +""" +resolver_bridge.py — Thin adapter between iTrialSpace's PathResolver +and the mask insertion engine. + +The CohortManifest carries *relative* or *pre-resolved* paths in columns: + + host_ct_path, host_organ_seg_path, + donor_ct_path, donor_nodule_mask_path, donor_refined_seg_path + +If paths are already absolute and exist on disk, we use them directly. +Otherwise, we fall back to PathResolver for resolution. +""" + +from __future__ import annotations + +import os +from dataclasses import dataclass +from pathlib import Path +from typing import Optional + +import pandas as pd + + +@dataclass +class ResolvedPaths: + """All paths needed for a single insertion row.""" + + host_ct: str + host_organ_seg: str + donor_ct: str + donor_nodule_mask: str + donor_refined_seg: str = "" + + def validate(self) -> list[str]: + """Return list of missing files (empty if all OK).""" + missing = [] + for label, p in [ + ("host_ct", self.host_ct), + ("host_organ_seg", self.host_organ_seg), + ("donor_nodule_mask", self.donor_nodule_mask), + ]: + if not p or not os.path.isfile(p): + missing.append(f"{label}: {p}") + # donor_ct is optional (only needed for CT-level insertion) + if self.donor_ct and not os.path.isfile(self.donor_ct): + missing.append(f"donor_ct: {self.donor_ct}") + return missing + + +class ResolverBridge: + """Resolve manifest row paths, using PathResolver when needed. + + Usage:: + + bridge = ResolverBridge(path_resolver=my_resolver) + # or without PathResolver (paths must all be absolute already): + bridge = ResolverBridge() + + resolved = bridge.resolve(manifest_row) + """ + + def __init__( + self, + path_resolver: Optional[object] = None, + base_dir: Optional[str] = None, + ): + """ + Args: + path_resolver: An iTrialSpace ``PathResolver`` instance (optional). + base_dir: Fallback base directory for relative-path resolution. + """ + self._resolver = path_resolver + self._base_dir = base_dir or "" + + def resolve(self, row: pd.Series) -> ResolvedPaths: + """Resolve all paths for a manifest row. + + Logic per column: + 1. If the column value is an absolute path and exists → use as-is. + 2. If a PathResolver is available → delegate resolution. + 3. Else prepend base_dir and hope for the best. + """ + return ResolvedPaths( + host_ct=self._resolve_one( + row.get("host_ct_path", ""), + "ct", + row.get("host_dataset", ""), + row, + ), + host_organ_seg=self._resolve_one( + row.get("host_organ_seg_path", ""), + "organ_seg", + row.get("host_dataset", ""), + row, + ), + donor_ct=self._resolve_one( + row.get("donor_ct_path", ""), + "ct", + row.get("donor_dataset", ""), + row, + ), + donor_nodule_mask=self._resolve_one( + row.get("donor_nodule_mask_path", ""), + "nodule_mask", + row.get("donor_dataset", ""), + row, + ), + donor_refined_seg=self._resolve_one( + row.get("donor_refined_seg_path", ""), + "refined_seg", + row.get("donor_dataset", ""), + row, + ), + ) + + def _resolve_one( + self, + raw_value: str, + kind: str, + dataset: str, + row: pd.Series, + ) -> str: + """Resolve a single path column value.""" + raw_value = str(raw_value).strip() if pd.notna(raw_value) else "" + if not raw_value: + return "" + + # 1. Already absolute and exists + if os.path.isabs(raw_value) and os.path.exists(raw_value): + return raw_value + + # 2. PathResolver delegation + if self._resolver is not None and dataset: + try: + resolved = self._try_path_resolver(raw_value, kind, dataset, row) + if resolved and os.path.exists(resolved): + return resolved + except (KeyError, AttributeError, TypeError): + pass # fall through + + # 3. base_dir join + if self._base_dir: + joined = os.path.join(self._base_dir, raw_value) + if os.path.exists(joined): + return joined + + # 4. Return raw (caller will validate) + return raw_value + + def _try_path_resolver( + self, + raw_value: str, + kind: str, + dataset: str, + row: pd.Series, + ) -> str: + """Attempt to resolve via PathResolver API.""" + r = self._resolver + if kind == "ct": + return r.resolve_ct_path(dataset, raw_value) # type: ignore[union-attr] + elif kind == "organ_seg": + ct_path = str( + row.get("host_ct_path", "") if "host" in kind else row.get("donor_ct_path", "") + ) + ct_id = _extract_ct_id(ct_path) + return r.resolve_organ_seg_path(dataset, ct_id) # type: ignore[union-attr] + elif kind == "nodule_mask": + ann_id = str(row.get("donor_annotation_id", "")) + ct_path = str(row.get("donor_ct_path", "")) + ct_id = _extract_ct_id(ct_path) + return r.resolve_nodule_mask_path(dataset, ann_id, ct_id) # type: ignore[union-attr] + elif kind == "refined_seg": + ct_path = str(row.get("donor_ct_path", "")) + ct_id = _extract_ct_id(ct_path) + return r.resolve_refined_seg_path(dataset, ct_id) # type: ignore[union-attr] + return raw_value + + +def _extract_ct_id(ct_path: str) -> str: + """Extract ct_id from a path — basename without .nii.gz.""" + basename = os.path.basename(ct_path) + if basename.endswith(".nii.gz"): + return basename[:-7] + return Path(basename).stem diff --git a/itrialspace/src/itrialspace/mask_inserter/tools/__init__.py b/itrialspace/src/itrialspace/mask_inserter/tools/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/itrialspace/src/itrialspace/mask_inserter/tools/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/mask_inserter/tools/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..effa5214f31518cd6b6a7403d4b14f954652b022 Binary files /dev/null and b/itrialspace/src/itrialspace/mask_inserter/tools/__pycache__/__init__.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/mask_inserter/tools/__pycache__/list_manifests.cpython-310.pyc b/itrialspace/src/itrialspace/mask_inserter/tools/__pycache__/list_manifests.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b979b98fa7172b5eb051f81bb62f507cc2fe7b60 Binary files /dev/null and b/itrialspace/src/itrialspace/mask_inserter/tools/__pycache__/list_manifests.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/mask_inserter/tools/__pycache__/make_test_manifest.cpython-310.pyc b/itrialspace/src/itrialspace/mask_inserter/tools/__pycache__/make_test_manifest.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0e4b57020230335869a1c2fa90310faa31a0a410 Binary files /dev/null and b/itrialspace/src/itrialspace/mask_inserter/tools/__pycache__/make_test_manifest.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/mask_inserter/tools/list_manifests.py b/itrialspace/src/itrialspace/mask_inserter/tools/list_manifests.py new file mode 100644 index 0000000000000000000000000000000000000000..01f76504e9c70255ea8c8b66f482a8981a82be4b --- /dev/null +++ b/itrialspace/src/itrialspace/mask_inserter/tools/list_manifests.py @@ -0,0 +1,175 @@ +#!/usr/bin/env python3 +""" +list_manifests.py — Recursively find manifest CSV/JSON files in a directory +and write a manifest list file (one path per line) for use with SLURM array jobs. + +Usage: + python list_manifests.py --dir $ITRIALSPACE_DATA_DIR/.../manifests/mode2_size_detection_curve \ + --output manifests_mode2.txt + + python list_manifests.py --dir $ITRIALSPACE_DATA_DIR/.../manifests/mode7_bootstrap_confidence \ + --output manifests_mode7.txt \ + --pattern "*.csv" +""" + +from __future__ import annotations + +import argparse +import os +import sys +from pathlib import Path + + +def find_manifests( + directory: str | Path, + pattern: str = "*.csv", + also_json: bool = True, + exclude_patterns: list[str] | None = None, +) -> list[Path]: + """ + Recursively find manifest files in *directory*. + + Parameters + ---------- + directory : str or Path + Root directory to search. + pattern : str + Glob pattern for manifest files (default: ``*.csv``). + also_json : bool + Also search for ``*.json`` in addition to *pattern*. + exclude_patterns : list of str, optional + Skip files whose name contains any of these substrings + (e.g., ``["audit", "log", "metadata"]``). + + Returns + ------- + list of Path + Sorted list of absolute paths to discovered manifest files. + """ + directory = Path(directory).resolve() + if not directory.is_dir(): + print(f"ERROR: Not a directory: {directory}", file=sys.stderr) + sys.exit(1) + + exclude = exclude_patterns or [ + "audit", + "metadata", + "log", + "README", + "_run_config", + ] + + results: list[Path] = [] + + # Collect matching files + for pat in [pattern] + (["*.json"] if also_json else []): + for p in directory.rglob(pat): + if not p.is_file(): + continue + # Skip known non-manifest files + if any(ex.lower() in p.name.lower() for ex in exclude): + continue + results.append(p) + + # Deduplicate (in case pattern already includes json) and sort + results = sorted(set(results)) + + # When both CSV and JSON exist for the same stem, keep only the CSV to + # prevent duplicate array tasks that race on the same output directory. + if also_json: + stems_with_csv = {p.stem for p in results if p.suffix == ".csv"} + results = [p for p in results if not (p.suffix == ".json" and p.stem in stems_with_csv)] + + return results + + +def write_manifest_list(manifests: list[Path], output_path: str | Path) -> None: + """Write one manifest path per line to *output_path*.""" + output_path = Path(output_path) + output_path.parent.mkdir(parents=True, exist_ok=True) + + with open(output_path, "w") as f: + for m in manifests: + f.write(str(m) + "\n") + + +def main(): + parser = argparse.ArgumentParser( + description="Find cohort manifest CSV/JSON files and write a list file " + "for use with SLURM array jobs.", + ) + parser.add_argument( + "--dir", + "-d", + required=True, + help="Directory to search recursively for manifest files.", + ) + parser.add_argument( + "--output", + "-o", + required=True, + help="Output file path (one manifest path per line).", + ) + parser.add_argument( + "--pattern", + default="*.csv", + help="Glob pattern for manifest files (default: *.csv).", + ) + parser.add_argument( + "--no-json", + action="store_true", + help="Do not also search for *.json files.", + ) + parser.add_argument( + "--exclude", + nargs="*", + default=None, + help="Substrings to exclude from filenames (default: audit, metadata, log, README).", + ) + parser.add_argument( + "--dry-run", + action="store_true", + help="Print found manifests but do not write the output file.", + ) + parser.add_argument( + "--quiet", + "-q", + action="store_true", + help="Suppress informational output (still prints errors/warnings).", + ) + + args = parser.parse_args() + + manifests = find_manifests( + directory=args.dir, + pattern=args.pattern, + also_json=not args.no_json, + exclude_patterns=args.exclude, + ) + + print(f"Directory: {os.path.abspath(args.dir)}") + print(f"Pattern: {args.pattern}" + (" + *.json" if not args.no_json else "")) + print(f"Found: {len(manifests)} manifest(s)") + print() + + if len(manifests) == 0: + print("WARNING: No manifests found. Check the directory path.", file=sys.stderr) + sys.exit(0) + + if not args.quiet: + for i, m in enumerate(manifests): + print(f" [{i:3d}] {m}") + + if args.dry_run: + if not args.quiet: + print(f"\n(dry-run) Would write to: {args.output}") + else: + write_manifest_list(manifests, args.output) + if not args.quiet: + print(f"\nWritten to: {args.output}") + print("\nTo submit as a SLURM array job:") + print(f" sbatch --array=0-{len(manifests) - 1} modeX_insert_masks_array.sub") + + +if __name__ == "__main__": + main() diff --git a/itrialspace/src/itrialspace/mask_inserter/tools/make_test_manifest.py b/itrialspace/src/itrialspace/mask_inserter/tools/make_test_manifest.py new file mode 100644 index 0000000000000000000000000000000000000000..bf001781df48030fb50ac816f0e5a23658f1ed3f --- /dev/null +++ b/itrialspace/src/itrialspace/mask_inserter/tools/make_test_manifest.py @@ -0,0 +1,291 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +make_test_manifest.py — Generate a minimal test manifest (1–3 rows) +pointing to real host CTs and donor nodule masks on the server. + +Usage: + python itrialspace_mask_inserter/tools/make_test_manifest.py \ + --output $ITRIALSPACE_DATA_DIR/test_manifest.csv \ + [--base-dir $ITRIALSPACE_DATA_DIR] \ + [--n-rows 2] \ + [--dataset LUNA25] + +The script uses iTrialSpace's PathResolver to discover real data paths, +picks 1 host CT + 1 donor nodule from the specified (or first available) +dataset, and writes a CSV with absolute paths. +""" + +from __future__ import annotations + +import argparse +import os +import sys +from pathlib import Path + +import numpy as np +import pandas as pd + + +def _find_project_root() -> str: + """Walk up from this script to find the itrialspace package root.""" + here = Path(__file__).resolve().parent + for candidate in [here.parent.parent, here.parent.parent.parent]: + if (candidate / "itrialspace" / "site" / "path_resolver.py").exists(): + return str(candidate) + return str(here.parent.parent) + + +def main(): + parser = argparse.ArgumentParser( + description="Generate a minimal test manifest for full-volume integration tests.", + ) + parser.add_argument( + "--output", + "-o", + required=True, + help="Output CSV path.", + ) + parser.add_argument( + "--base-dir", + default=None, + help="iTrialSpace data base directory. " "Default: $ITRIALSPACE_DATA_DIR", + ) + parser.add_argument( + "--dataset", + default=None, + help="Dataset to pick host/donor from (e.g. LUNA25, DLCS24). " + "Default: first dataset with available profile CSV.", + ) + parser.add_argument( + "--n-rows", + type=int, + default=2, + help="Number of manifest rows to generate (default: 2).", + ) + parser.add_argument( + "--seed", + type=int, + default=42, + help="Random seed for reproducible selection.", + ) + args = parser.parse_args() + + base_dir = args.base_dir or ( + os.environ.get("ITRIALSPACE_DATA_DIR") or os.path.expanduser("~/.itrialspace/data") + ) + + # Try to import PathResolver + project_root = _find_project_root() + sys.path.insert(0, project_root) + + try: + from itrialspace.site.path_resolver import PathResolver + + resolver = PathResolver(base_dir=base_dir) + print(f"PathResolver loaded. Base dir: {resolver.base_dir}") + print(f"Available datasets: {resolver.available_datasets}") + except Exception as e: + print(f"WARNING: Could not load PathResolver: {e}") + print("Falling back to manual path construction.") + resolver = None + + # Pick dataset + dataset = args.dataset + if dataset is None and resolver is not None: + dataset = _pick_dataset(resolver) + if dataset is None: + dataset = "LUNA25" + print(f"Using dataset: {dataset}") + + # Load profile CSV to find real nodules + rng = np.random.default_rng(args.seed) + rows = _build_rows(resolver, base_dir, dataset, args.n_rows, rng) + + if not rows: + print("ERROR: Could not build any manifest rows. Check data paths.") + sys.exit(1) + + df = pd.DataFrame(rows) + os.makedirs(os.path.dirname(args.output) or ".", exist_ok=True) + df.to_csv(args.output, index=False) + print(f"\nWrote {len(df)} rows to {args.output}") + print(df[["case_id", "host_ct_path", "donor_nodule_mask_path", "insertion_lobe"]].to_string()) + + +def _pick_dataset(resolver) -> str | None: + """Pick the first dataset that has a readable profile CSV.""" + for ds in resolver.available_datasets: + csv_path = resolver.resolve_profile_csv_path(ds) + if os.path.isfile(csv_path): + return ds + return None + + +def _build_rows( + resolver, + base_dir: str, + dataset: str, + n_rows: int, + rng: np.random.Generator, +) -> list[dict]: + """Build manifest rows from real data.""" + # Load profile to find nodule info + if resolver is not None: + profile_path = resolver.resolve_profile_csv_path(dataset) + else: + profile_path = os.path.join(base_dir, "profiles", f"{dataset}_nodule_profiles.csv") + + if not os.path.isfile(profile_path): + print(f"WARNING: Profile CSV not found at {profile_path}") + return _build_rows_manual(base_dir, dataset, n_rows, rng) + + print(f"Loading profile: {profile_path}") + prof = pd.read_csv(profile_path) + print(f" {len(prof)} nodules in {dataset}") + + # Filter to nodules with valid lobe data + valid = prof.dropna(subset=["ct_path"]) + if "reinsertion_lobe" in valid.columns: + valid = valid[valid["reinsertion_lobe"].notna()] + if len(valid) == 0: + print("WARNING: No valid nodules after filtering.") + return [] + + # Sample + n = min(n_rows, len(valid)) + sample = valid.sample(n=n, random_state=int(rng.integers(0, 2**31))) + + rows = [] + for idx, (_, nod) in enumerate(sample.iterrows()): + ct_path_rel = str(nod["ct_path"]) + ct_id = os.path.basename(ct_path_rel).replace(".nii.gz", "") + + # Resolve paths + if resolver is not None: + host_ct = resolver.resolve_ct_path(dataset, ct_path_rel) + host_seg = resolver.resolve_organ_seg_path(dataset, ct_id) + ann_id = str(nod.get("annotation_id", ct_id)) if "annotation_id" in nod.index else ct_id + donor_mask = resolver.resolve_nodule_mask_path(dataset, ann_id, ct_id) + else: + host_ct = os.path.join(base_dir, "raw_ct", ct_path_rel) + host_seg = os.path.join( + base_dir, "masks", dataset, "refined_seg", f"{ct_id}_seg.nii.gz" + ) + donor_mask = os.path.join(base_dir, "masks", dataset, "nodule_seg", f"{ct_id}.nii.gz") + + lobe = str(nod.get("reinsertion_lobe", nod.get("lobe_name", "right_lung_upper_lobe"))) + cc_pct = float(nod.get("reinsertion_lobe_cc_pct", nod.get("lobe_cc_pct", 50.0))) + ml_pct = float(nod.get("reinsertion_lobe_ml_pct", nod.get("lobe_ml_pct", 50.0))) + ap_pct = float(nod.get("reinsertion_lobe_ap_pct", nod.get("lobe_ap_pct", 50.0))) + + # Clamp percentiles to [0, 100] + cc_pct = max(0.0, min(100.0, cc_pct)) + ml_pct = max(0.0, min(100.0, ml_pct)) + ap_pct = max(0.0, min(100.0, ap_pct)) + + rows.append( + { + "case_id": f"test_case_{idx:03d}", + "nodule_idx": 0, + "is_primary_nodule": True, + "companion_group_id": "", + "trial_name": "integration_test", + "host_dataset": dataset, + "host_patient_id": ct_id, + "host_ct_path": host_ct, + "host_organ_seg_path": host_seg, + "donor_dataset": dataset, + "donor_annotation_id": ( + str(nod.get("annotation_id", ct_id)) if "annotation_id" in nod.index else ct_id + ), + "donor_patient_id": ct_id, + "donor_ct_path": host_ct, + "donor_nodule_mask_path": donor_mask, + "donor_refined_seg_path": "", + "insertion_lobe": lobe, + "insertion_lobe_cc_pct": cc_pct, + "insertion_lobe_ml_pct": ml_pct, + "insertion_lobe_ap_pct": ap_pct, + "insertion_mode": "profile_faithful", + "scale_factor": 1.0, + "warp_applied": "none", + "effective_diam_mm": float( + nod.get("reinsertion_nodule_diam_mm", nod.get("nodule_mean_diam_mm", 8.0)) + ), + "nodule_diam_mm": float(nod.get("nodule_mean_diam_mm", 8.0)), + "label": ( + int(nod["label"]) if "label" in nod.index and pd.notna(nod.get("label")) else 0 + ), + } + ) + + return rows + + +def _build_rows_manual( + base_dir: str, + dataset: str, + n_rows: int, + rng: np.random.Generator, +) -> list[dict]: + """Fallback: scan directories directly.""" + ct_dir = os.path.join(base_dir, "raw_ct", dataset) + if not os.path.isdir(ct_dir): + print(f"WARNING: CT directory not found: {ct_dir}") + return [] + + cts = [f for f in os.listdir(ct_dir) if f.endswith(".nii.gz")] + if not cts: + return [] + + rng.shuffle(cts) # type: ignore[arg-type] + rows = [] + for idx, ct_file in enumerate(cts[:n_rows]): + ct_id = ct_file.replace(".nii.gz", "") + rows.append( + { + "case_id": f"test_case_{idx:03d}", + "nodule_idx": 0, + "is_primary_nodule": True, + "companion_group_id": "", + "trial_name": "integration_test", + "host_dataset": dataset, + "host_patient_id": ct_id, + "host_ct_path": os.path.join(ct_dir, ct_file), + "host_organ_seg_path": os.path.join( + base_dir, + "masks", + dataset, + "refined_seg", + f"{ct_id}_seg.nii.gz", + ), + "donor_dataset": dataset, + "donor_annotation_id": ct_id, + "donor_patient_id": ct_id, + "donor_ct_path": os.path.join(ct_dir, ct_file), + "donor_nodule_mask_path": os.path.join( + base_dir, + "masks", + dataset, + "nodule_seg", + f"{ct_id}.nii.gz", + ), + "donor_refined_seg_path": "", + "insertion_lobe": "right_lung_upper_lobe", + "insertion_lobe_cc_pct": 50.0, + "insertion_lobe_ml_pct": 50.0, + "insertion_lobe_ap_pct": 50.0, + "insertion_mode": "profile_faithful", + "scale_factor": 1.0, + "warp_applied": "none", + "effective_diam_mm": 8.0, + "nodule_diam_mm": 8.0, + "label": 0, + } + ) + return rows + + +if __name__ == "__main__": + main() diff --git a/itrialspace/src/itrialspace/query/__init__.py b/itrialspace/src/itrialspace/query/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/itrialspace/src/itrialspace/query/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/query/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..16f99d21b7d96bd31c8217c2a992e10cf315f5f8 Binary files /dev/null and b/itrialspace/src/itrialspace/query/__pycache__/__init__.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/query/__pycache__/matcher.cpython-310.pyc b/itrialspace/src/itrialspace/query/__pycache__/matcher.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a32d349a84133051d4f50eba4713f55a17d8540 Binary files /dev/null and b/itrialspace/src/itrialspace/query/__pycache__/matcher.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/query/__pycache__/query_api.cpython-310.pyc b/itrialspace/src/itrialspace/query/__pycache__/query_api.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..01f52f597c70edb2f5e7e2c5f7e9523c44e73456 Binary files /dev/null and b/itrialspace/src/itrialspace/query/__pycache__/query_api.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/query/matcher.py b/itrialspace/src/itrialspace/query/matcher.py new file mode 100644 index 0000000000000000000000000000000000000000..340cdea8f4de5240910d13640e8a207db397f5b3 --- /dev/null +++ b/itrialspace/src/itrialspace/query/matcher.py @@ -0,0 +1,180 @@ +""" +ReinsertionMatcher — given a target anatomy, find the best matching donor nodule. + +Uses the `reinsertion_*` columns (100% complete across all 8 datasets) +as the match space so no anatomical re-computation is needed at insert time. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Optional + +import pandas as pd + + +@dataclass +class ReinsertionTarget: + """ + Describes where you want to place a nodule in a target CT. + + Fields map directly to the reinsertion_* columns in the index. + Only `lobe` is required — all others are optional soft constraints. + """ + + lobe: str # required — e.g. 'right_lung_upper_lobe' + lobe_cc_pct: Optional[float] = None # craniocaudal % within lobe (0=apex, 100=base) + pleural_dist_mm: Optional[float] = None # desired pleural distance + diameter_mm: Optional[float] = None # desired nodule diameter + label: Optional[int] = None # 0=benign, 1=malignant, None=any + lung_zone: Optional[str] = None # 'upper_zone' | 'middle_zone' | 'lower_zone' + lung_side: Optional[str] = None # 'left' | 'right' + exclude_datasets: list[str] = field(default_factory=list) + include_datasets: list[str] = field(default_factory=list) # empty = all + + +@dataclass +class MatchResult: + """A single match result with its score.""" + + annotation_id: str + dataset: str + ct_path: str + score: float # lower = better match + lobe: str + diameter_mm: float + pleural_mm: Optional[float] + lobe_cc_pct: float + label: Optional[int] + row: pd.Series = field(repr=False) # full row for downstream use + + def __repr__(self) -> str: + lbl = {0: "benign", 1: "malignant", None: "unlabelled"}[self.label] + return ( + f"MatchResult(score={self.score:.3f} | {self.dataset} | " + f"{self.annotation_id} | {self.diameter_mm:.1f}mm | " + f"{self.lobe} | {lbl})" + ) + + +class ReinsertionMatcher: + """ + Anatomy-based nearest-neighbour matcher over the reinsertion index. + + Match score (lower = better): + + score = w_lobe * (0 if lobe matches else lobe_penalty) + + w_cc * |lobe_cc_pct - target.lobe_cc_pct| / 100 + + w_pleural * |pleural_dist_mm - target.pleural_dist_mm| / max_pleural + + w_diam * |diameter_mm - target.diameter_mm| / max_diam + + All weights and penalty values are configurable. + """ + + DEFAULT_WEIGHTS = { + "w_cc": 1.0, + "w_pleural": 0.8, + "w_diam": 0.6, + "lobe_penalty": 5.0, # added to score when lobe doesn't match + } + + def __init__(self, index, weights: Optional[dict] = None): + """ + Args: + index: NoduleIndex instance + weights: override default scoring weights + """ + from itrialspace.index.nodule_index import NoduleIndex + + if not isinstance(index, NoduleIndex): + raise TypeError("index must be a NoduleIndex") + self._df = index.df + self._w = {**self.DEFAULT_WEIGHTS, **(weights or {})} + + def find_best(self, target: ReinsertionTarget) -> Optional[MatchResult]: + """Return the single best matching nodule.""" + results = self.find_top_k(target, k=1) + return results[0] if results else None + + def find_top_k(self, target: ReinsertionTarget, k: int = 10) -> list[MatchResult]: + """Return the top-k matching nodules, sorted by score ascending.""" + candidates = self._filter_candidates(target) + if candidates.empty: + return [] + + scores = self._score(candidates, target) + candidates = candidates.copy() + candidates["_score"] = scores + candidates = candidates.nsmallest(k, "_score") + + results = [] + for _, row in candidates.iterrows(): + results.append( + MatchResult( + annotation_id=str(row.get("annotation_id", "")), + dataset=str(row.get("dataset", "")), + ct_path=str(row.get("ct_path", "")), + score=float(row["_score"]), + lobe=str(row.get("reinsertion_lobe", "")), + diameter_mm=float(row.get("reinsertion_nodule_diam_mm", 0)), + pleural_mm=row.get("reinsertion_pleural_dist_mm"), + lobe_cc_pct=float(row.get("reinsertion_lobe_cc_pct", 0)), + label=(int(row["label"]) if pd.notna(row.get("label")) else None), + row=row, + ) + ) + return results + + def _filter_candidates(self, target: ReinsertionTarget) -> pd.DataFrame: + """Apply hard filters before scoring.""" + mask = pd.Series(True, index=self._df.index) + + # Dataset filters + if target.exclude_datasets: + mask &= ~self._df["dataset"].isin(target.exclude_datasets) + if target.include_datasets: + mask &= self._df["dataset"].isin(target.include_datasets) + + # Label filter (hard) + if target.label is not None: + mask &= self._df["label"] == target.label + + # Zone filter (hard if specified) + if target.lung_zone: + mask &= self._df["reinsertion_lung_zone"] == target.lung_zone + + # Side filter (hard if specified) + if target.lung_side: + mask &= self._df["reinsertion_lung_side"] == target.lung_side + + return self._df[mask].copy() + + def _score(self, df: pd.DataFrame, target: ReinsertionTarget) -> pd.Series: + """Compute match score for each candidate row.""" + w = self._w + score = pd.Series(0.0, index=df.index) + + # Lobe match (soft penalty if no hard filter was applied) + lobe_match = df["reinsertion_lobe"] == target.lobe + score += (~lobe_match).astype(float) * w["lobe_penalty"] + + # Craniocaudal position within lobe + if target.lobe_cc_pct is not None: + cc_diff = (df["reinsertion_lobe_cc_pct"] - target.lobe_cc_pct).abs() / 100.0 + score += w["w_cc"] * cc_diff + + # Pleural distance + if target.pleural_dist_mm is not None: + max_p = max(df["reinsertion_pleural_dist_mm"].max(), 1.0) + pl_diff = ( + df["reinsertion_pleural_dist_mm"].fillna(max_p) - target.pleural_dist_mm + ).abs() / max_p + score += w["w_pleural"] * pl_diff + + # Diameter + if target.diameter_mm is not None: + max_d = max(df["reinsertion_nodule_diam_mm"].max(), 1.0) + d_diff = (df["reinsertion_nodule_diam_mm"] - target.diameter_mm).abs() / max_d + score += w["w_diam"] * d_diff + + return score diff --git a/itrialspace/src/itrialspace/query/query_api.py b/itrialspace/src/itrialspace/query/query_api.py new file mode 100644 index 0000000000000000000000000000000000000000..b58a8584f5bbe2a3fb528ad48337357875c64da9 --- /dev/null +++ b/itrialspace/src/itrialspace/query/query_api.py @@ -0,0 +1,316 @@ +""" +NoduleQuery — fluent builder API for querying the NoduleIndex. + +Usage: + results = ( + idx.query() + .datasets(['DLCS24', 'LUNA25']) + .label(1) + .lobe('right_lung_upper_lobe') + .diameter(min=8.0, max=20.0) + .pleural_distance(max=10.0) + .sample(n=100, seed=42) + .fetch() + ) +""" + +from __future__ import annotations + +from typing import Optional, Union + +import pandas as pd + +from itrialspace.core.profile import NoduleProfile +from itrialspace.site.spec import validate_dataset_names + + +class NoduleQuery: + """ + Fluent query builder. All filter methods return `self` for chaining. + Call `.fetch()` or `.count()` to execute. + """ + + def __init__(self, df: pd.DataFrame): + self._df = df + self._mask = pd.Series(True, index=df.index) + self._sample_n: Optional[int] = None + self._sample_seed: Optional[int] = None + + # ── Dataset filters ──────────────────────────────────────────────────────── + + def datasets(self, names: Union[str, list[str]]) -> "NoduleQuery": + """Include only these datasets.""" + if isinstance(names, str): + names = [names] + validate_dataset_names(names) + self._mask &= self._df["dataset"].isin(names) + return self + + def exclude_datasets(self, names: Union[str, list[str]]) -> "NoduleQuery": + """Exclude these datasets.""" + if isinstance(names, str): + names = [names] + self._mask &= ~self._df["dataset"].isin(names) + return self + + # ── Label filters ────────────────────────────────────────────────────────── + + def label(self, val: Optional[int]) -> "NoduleQuery": + """Filter by label: 0=benign, 1=malignant, None=unlabelled.""" + if val is None: + self._mask &= self._df["label"].isna() + else: + self._mask &= self._df["label"] == val + return self + + def labelled(self) -> "NoduleQuery": + """Only rows with a non-null label.""" + self._mask &= self._df["label"].notna() + return self + + # ── Anatomy filters ──────────────────────────────────────────────────────── + + def lobe(self, names: Union[str, list[str]]) -> "NoduleQuery": + """Filter by lobe_name.""" + if isinstance(names, str): + names = [names] + self._mask &= self._df["lobe_name"].isin(names) + return self + + def lung_side(self, side: str) -> "NoduleQuery": + """'left' or 'right'.""" + self._mask &= self._df["lung_side"] == side + return self + + def lung_zone(self, zone: Union[str, list[str]]) -> "NoduleQuery": + """'upper_zone', 'middle_zone', or 'lower_zone'.""" + if isinstance(zone, str): + zone = [zone] + self._mask &= self._df["lung_zone"].isin(zone) + return self + + def central_peripheral(self, val: str) -> "NoduleQuery": + """'central' or 'peripheral'.""" + self._mask &= self._df["central_peripheral"] == val + return self + + # ── Size filters ─────────────────────────────────────────────────────────── + + def diameter(self, min: Optional[float] = None, max: Optional[float] = None) -> "NoduleQuery": + """Filter by nodule_mean_diam_mm.""" + if min is not None: + self._mask &= self._df["nodule_mean_diam_mm"] >= min + if max is not None: + self._mask &= self._df["nodule_mean_diam_mm"] <= max + return self + + def volume(self, min: Optional[float] = None, max: Optional[float] = None) -> "NoduleQuery": + """Filter by nodule_vol_mm3.""" + if min is not None: + self._mask &= self._df["nodule_vol_mm3"].fillna(0) >= min + if max is not None: + self._mask &= self._df["nodule_vol_mm3"].fillna(0) <= max + return self + + # ── Distance filters ─────────────────────────────────────────────────────── + + def pleural_distance( + self, min: Optional[float] = None, max: Optional[float] = None + ) -> "NoduleQuery": + """Filter by pleural_distance_mm.""" + col = self._df["pleural_distance_mm"] + if min is not None: + self._mask &= col.fillna(999) >= min + if max is not None: + self._mask &= col.fillna(999) <= max + return self + + def airway_distance( + self, min: Optional[float] = None, max: Optional[float] = None + ) -> "NoduleQuery": + """Filter by airway_distance_mm.""" + col = self._df["airway_distance_mm"] + if min is not None: + self._mask &= col.fillna(999) >= min + if max is not None: + self._mask &= col.fillna(999) <= max + return self + + # ── Reinsertion filters (primary index — 100% complete) ──────────────────── + + def reinsertion_lobe(self, name: Union[str, list[str]]) -> "NoduleQuery": + """Filter by reinsertion_lobe.""" + if isinstance(name, str): + name = [name] + self._mask &= self._df["reinsertion_lobe"].isin(name) + return self + + def reinsertion_zone(self, zone: Union[str, list[str]]) -> "NoduleQuery": + """Filter by reinsertion_lung_zone.""" + if isinstance(zone, str): + zone = [zone] + self._mask &= self._df["reinsertion_lung_zone"].isin(zone) + return self + + def reinsertion_side(self, side: str) -> "NoduleQuery": + """Filter by reinsertion_lung_side.""" + self._mask &= self._df["reinsertion_lung_side"] == side + return self + + def reinsertion_diameter( + self, min: Optional[float] = None, max: Optional[float] = None + ) -> "NoduleQuery": + """Filter by reinsertion_nodule_diam_mm.""" + col = self._df["reinsertion_nodule_diam_mm"] + if min is not None: + self._mask &= col >= min + if max is not None: + self._mask &= col <= max + return self + + def reinsertion_pleural( + self, min: Optional[float] = None, max: Optional[float] = None + ) -> "NoduleQuery": + """Filter by reinsertion_pleural_dist_mm.""" + col = self._df["reinsertion_pleural_dist_mm"] + if min is not None: + self._mask &= col.fillna(999) >= min + if max is not None: + self._mask &= col.fillna(999) <= max + return self + + def reinsertion_cc_pct( + self, min: Optional[float] = None, max: Optional[float] = None + ) -> "NoduleQuery": + """Filter by reinsertion_lobe_cc_pct (craniocaudal position within lobe).""" + col = self._df["reinsertion_lobe_cc_pct"] + if min is not None: + self._mask &= col >= min + if max is not None: + self._mask &= col <= max + return self + + # ── Multi-nodule filters ───────────────────────────────────────────────── + + def n_nodules_in_patient( + self, min: Optional[int] = None, max: Optional[int] = None + ) -> "NoduleQuery": + """Filter by number of nodules in the source patient.""" + col = self._df["n_nodules_in_patient"] + if min is not None: + self._mask &= col >= min + if max is not None: + self._mask &= col <= max + return self + + # ── Sampling ─────────────────────────────────────────────────────────────── + + def sample(self, n: int, seed: Optional[int] = None) -> "NoduleQuery": + """Random sample of n results (applied at fetch time).""" + self._sample_n = n + self._sample_seed = seed + return self + + # ── Execute ──────────────────────────────────────────────────────────────── + + def fetch(self) -> pd.DataFrame: + """Execute query and return matching rows as a DataFrame.""" + result = self._df[self._mask].copy() + if self._sample_n is not None: + n = min(self._sample_n, len(result)) + result = result.sample(n=n, random_state=self._sample_seed) + return result.reset_index(drop=True) + + def count(self) -> int: + """Return count without fetching data.""" + return int(self._mask.sum()) + + def exists(self) -> bool: + """Return True if any rows match.""" + return self.count() > 0 + + def fetch_profiles(self) -> list[NoduleProfile]: + """ + Execute query and return matching rows as NoduleProfile objects. + Note: slower than fetch() — use for small result sets. + """ + from itrialspace.io.loader import _b, _f, _i, _s + + profiles = [] + for _, row in self.fetch().iterrows(): + ds = row.get("dataset", "unknown") + from itrialspace.core.schema import CORE_COLS + + core_set = set(CORE_COLS) | { + "ct_path", + "dataset", + "patient_id", + "annotation_id", + "label", + } + meta = {k: v for k, v in row.items() if k not in core_set and not k.startswith("_")} + p = NoduleProfile( + annotation_id=str(row.get("annotation_id", "")), + patient_id=str(row.get("patient_id", "")), + dataset=ds, + ct_path=_s(row.get("ct_path")), + label=_i(row.get("label")), + coord_x=_f(row.get("coordX"), 0.0), + coord_y=_f(row.get("coordY"), 0.0), + coord_z=_f(row.get("coordZ"), 0.0), + w=_f(row.get("w"), 0.0), + h=_f(row.get("h"), 0.0), + d=_f(row.get("d"), 0.0), + nodule_mean_diam_mm=_f(row.get("nodule_mean_diam_mm"), 0.0), + nodule_vol_mm3=_f(row.get("nodule_vol_mm3")), + lobe_name=_s(row.get("lobe_name"), "unknown"), + lung_side=_s(row.get("lung_side"), "unknown"), + lung_zone=_s(row.get("lung_zone"), "unknown"), + organ_label_id=_i(row.get("organ_label_id"), 0), + organ_label_name=_s(row.get("organ_label_name")), + central_peripheral=_s(row.get("central_peripheral"), "unknown"), + nearby_organs_10mm=_s(row.get("nearby_organs_10mm")) or None, + cranio_caudal_pct=_f(row.get("cranio_caudal_pct")), + mediolateral_pct=_f(row.get("mediolateral_pct")), + anteroposterior_pct=_f(row.get("anteroposterior_pct")), + lobe_cc_pct=_f(row.get("lobe_cc_pct")), + lobe_ml_pct=_f(row.get("lobe_ml_pct")), + lobe_ap_pct=_f(row.get("lobe_ap_pct")), + dist_to_trachea_mm=_f(row.get("dist_to_trachea_mm")), + dist_to_aorta_mm=_f(row.get("dist_to_aorta_mm")), + dist_to_heart_mm=_f(row.get("dist_to_heart_mm")), + dist_to_esophagus_mm=_f(row.get("dist_to_esophagus_mm")), + dist_to_pulmonary_vein_mm=_f(row.get("dist_to_pulmonary_vein_mm")), + dist_to_superior_vena_cava_mm=_f(row.get("dist_to_superior_vena_cava_mm")), + pleural_distance_mm=_f(row.get("pleural_distance_mm")), + airway_distance_mm=_f(row.get("airway_distance_mm")), + n_nodules_in_patient=_i(row.get("n_nodules_in_patient"), 1), + nearest_nodule_id=_s(row.get("nearest_nodule_id")) or None, + nearest_nodule_dist_mm=_f(row.get("nearest_nodule_dist_mm")), + nearest_dx_mm=_f(row.get("nearest_dx_mm")), + nearest_dy_mm=_f(row.get("nearest_dy_mm")), + nearest_dz_mm=_f(row.get("nearest_dz_mm")), + all_nodule_ids=_s(row.get("all_nodule_ids")) or None, + all_nodule_dists_mm=_s(row.get("all_nodule_dists_mm")) or None, + ipsilateral=_b(row.get("ipsilateral")), + nearest_same_lobe=_b(row.get("nearest_same_lobe")), + bilateral_distribution=_b(row.get("bilateral_distribution")) or False, + reinsertion_lobe=_s(row.get("reinsertion_lobe"), "unknown"), + reinsertion_lung_side=_s(row.get("reinsertion_lung_side"), "unknown"), + reinsertion_lung_zone=_s(row.get("reinsertion_lung_zone"), "unknown"), + reinsertion_lobe_cc_pct=_f(row.get("reinsertion_lobe_cc_pct"), 0.0), + reinsertion_lobe_ml_pct=_f(row.get("reinsertion_lobe_ml_pct"), 0.0), + reinsertion_lobe_ap_pct=_f(row.get("reinsertion_lobe_ap_pct"), 0.0), + reinsertion_lung_cc_pct=_f(row.get("reinsertion_lung_cc_pct"), 0.0), + reinsertion_lung_ml_pct=_f(row.get("reinsertion_lung_ml_pct"), 0.0), + reinsertion_lung_ap_pct=_f(row.get("reinsertion_lung_ap_pct"), 0.0), + reinsertion_pleural_dist_mm=_f(row.get("reinsertion_pleural_dist_mm")), + reinsertion_airway_dist_mm=_f(row.get("reinsertion_airway_dist_mm")), + reinsertion_nodule_diam_mm=_f(row.get("reinsertion_nodule_diam_mm"), 0.0), + meta=meta, + ) + profiles.append(p) + return profiles + + def __repr__(self) -> str: + return f"NoduleQuery(matching={self.count():,} rows)" diff --git a/itrialspace/src/itrialspace/site/__init__.py b/itrialspace/src/itrialspace/site/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..abfec7541a036754273f64ca304922c538a7bd85 --- /dev/null +++ b/itrialspace/src/itrialspace/site/__init__.py @@ -0,0 +1,40 @@ +""" +iTrialSpace — Synthetic Imaging Trial Engine. + +Manufactures cohort manifests for synthetic CT trials on top of +the itrialspace nodule profile index. Supports 10 scientific trial modes +with multi-nodule companion inclusion. +""" + +from itrialspace.site import trial_modes +from itrialspace.site.cohort_builder import CohortBuilder +from itrialspace.site.insertion_planner import InsertionPlan, InsertionPlanner +from itrialspace.site.knowledge_base import TrialKnowledgeBase +from itrialspace.site.manifest import CohortManifest +from itrialspace.site.path_resolver import PathResolver +from itrialspace.site.sampling import DistributionSampler +from itrialspace.site.spec import ( + DemographicSpec, + InsertionSpec, + NoduleSpec, + SizeDistribution, + TrialSpec, +) +from itrialspace.site.validation import SpecValidator + +__all__ = [ + "TrialSpec", + "NoduleSpec", + "DemographicSpec", + "SizeDistribution", + "InsertionSpec", + "PathResolver", + "DistributionSampler", + "TrialKnowledgeBase", + "InsertionPlanner", + "InsertionPlan", + "CohortManifest", + "SpecValidator", + "CohortBuilder", + "trial_modes", +] diff --git a/itrialspace/src/itrialspace/site/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/site/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a8fdaa58479365da92b9e154975a83f237e3dafc Binary files /dev/null and b/itrialspace/src/itrialspace/site/__pycache__/__init__.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/site/__pycache__/cohort_builder.cpython-310.pyc b/itrialspace/src/itrialspace/site/__pycache__/cohort_builder.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6fcd9c165a27fa922095e6674d07d3584fd02d21 Binary files /dev/null and b/itrialspace/src/itrialspace/site/__pycache__/cohort_builder.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/site/__pycache__/insertion_planner.cpython-310.pyc b/itrialspace/src/itrialspace/site/__pycache__/insertion_planner.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3e3be66026fcff4432aecaa7351522b110222c4a Binary files /dev/null and b/itrialspace/src/itrialspace/site/__pycache__/insertion_planner.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/site/__pycache__/knowledge_base.cpython-310.pyc b/itrialspace/src/itrialspace/site/__pycache__/knowledge_base.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..96876ecc129d6c06ced14316247acf1f6d335730 Binary files /dev/null and b/itrialspace/src/itrialspace/site/__pycache__/knowledge_base.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/site/__pycache__/manifest.cpython-310.pyc b/itrialspace/src/itrialspace/site/__pycache__/manifest.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c82b4038f49e7b95c7acb7a996eb391e0056e8c5 Binary files /dev/null and b/itrialspace/src/itrialspace/site/__pycache__/manifest.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/site/__pycache__/path_resolver.cpython-310.pyc b/itrialspace/src/itrialspace/site/__pycache__/path_resolver.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3fd0774b345309fea8e0e4f2fa214e21fefa4973 Binary files /dev/null and b/itrialspace/src/itrialspace/site/__pycache__/path_resolver.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/site/__pycache__/sampling.cpython-310.pyc b/itrialspace/src/itrialspace/site/__pycache__/sampling.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..55a4a2445074a7450909938b10a932821b0b569f Binary files /dev/null and b/itrialspace/src/itrialspace/site/__pycache__/sampling.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/site/__pycache__/spec.cpython-310.pyc b/itrialspace/src/itrialspace/site/__pycache__/spec.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b3769138852bd4f217dbcb36a2750497856a3470 Binary files /dev/null and b/itrialspace/src/itrialspace/site/__pycache__/spec.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/site/__pycache__/trial_modes.cpython-310.pyc b/itrialspace/src/itrialspace/site/__pycache__/trial_modes.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..57712614a49e92c42baa707d8d10fadffc4aa6a6 Binary files /dev/null and b/itrialspace/src/itrialspace/site/__pycache__/trial_modes.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/site/__pycache__/validation.cpython-310.pyc b/itrialspace/src/itrialspace/site/__pycache__/validation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..70f2677543ecc2772ee98e7f8b0552699ab7b677 Binary files /dev/null and b/itrialspace/src/itrialspace/site/__pycache__/validation.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/site/cohort_builder.py b/itrialspace/src/itrialspace/site/cohort_builder.py new file mode 100644 index 0000000000000000000000000000000000000000..9d0c78877848d0c30c41456faebae6bf2d18aabe --- /dev/null +++ b/itrialspace/src/itrialspace/site/cohort_builder.py @@ -0,0 +1,1536 @@ +""" +CohortBuilder — the main orchestrator. + +Resolves a TrialSpec into a CohortManifest by: +1. Validating the spec +2. Selecting nodule and host pools via NoduleQuery +3. Assigning labels and sizes +4. Pairing hosts with donors (native/matched/synthetic) +5. Planning insertions +6. Resolving file paths +7. Assembling the manifest +""" + +from __future__ import annotations + +import os +import warnings +from typing import Optional + +import numpy as np +import pandas as pd + +from itrialspace.index.nodule_index import NoduleIndex +from itrialspace.query.matcher import ReinsertionMatcher, ReinsertionTarget +from itrialspace.site.insertion_planner import InsertionPlanner +from itrialspace.site.manifest import CohortManifest +from itrialspace.site.path_resolver import PathResolver +from itrialspace.site.sampling import DistributionSampler, _diameter_to_bucket +from itrialspace.site.spec import ( + HISTOPATH_DATASETS, + LABEL_SOURCE_MAP, + POPULATION_TYPE_MAP, + SCREENING_DATASETS, + DigitalTwinCompleteSpec, + DigitalTwinCrossSpec, + DigitalTwinIsolationSpec, + TrialSpec, +) +from itrialspace.site.validation import SpecValidator + +# Demographics column mapping per dataset (meta column names → manifest columns) +_DEMO_COL_MAP: dict[str, dict[str, str]] = { + "DLCS24": { + "Age": "patient_age", + "Sex": "patient_sex", + "Smoking Status (Current/Former/Never/Unknown)": "smoking_status", + }, + "LUNA25": {"age": "patient_age", "gender": "patient_sex"}, + "IMDCT": {}, + "NSCLCR": {}, + "LUNGx": {}, + "LNDbv4": {}, + "LUNA16": {}, +} + + +class CohortBuilder: + """Resolves a TrialSpec into a CohortManifest.""" + + def __init__(self, index: NoduleIndex, path_resolver: PathResolver): + self._index = index + self._resolver = path_resolver + self._matcher = ReinsertionMatcher(index) + self._planner = InsertionPlanner(index.df) + + def build(self, spec: TrialSpec, verbose: bool = True) -> CohortManifest: + """Main entry point: TrialSpec → CohortManifest. + + If spec.n_bootstrap > 1, returns the first bootstrap replicate. + Use build_all() for multiple replicates. + """ + # Validate + validator = SpecValidator(self._index.df) + errors = validator.validate(spec) + if errors: + raise ValueError("Invalid TrialSpec:\n" + "\n".join(f" - {e}" for e in errors)) + + if verbose: + report = validator.feasibility_report(spec) + if report["warnings"]: + for w in report["warnings"]: + warnings.warn(f"iTrialSpace feasibility: {w}") + print( + f"Pool: {report['pool_size']} nodules | " + f"Malignant: {report['malignant_pool']} | " + f"Benign: {report['benign_pool']}" + ) + + rng = np.random.default_rng(spec.seed) + + # Build based on mode + if spec.cohort_mode == "native": + rows = self._build_native(spec, rng, verbose) + elif spec.cohort_mode == "matched": + rows = self._build_matched(spec, rng, verbose) + elif spec.cohort_mode == "synthetic": + rows = self._build_synthetic(spec, rng, verbose) + else: + raise ValueError(f"Unknown cohort_mode: {spec.cohort_mode}") + + df = pd.DataFrame(rows) + return CohortManifest(df, spec) + + def build_all(self, spec: TrialSpec, verbose: bool = False) -> list[CohortManifest]: + """Build multiple bootstrap replicates.""" + manifests = [] + for i in range(spec.n_bootstrap): + boot_spec = TrialSpec( + **{ + **spec.__dict__, + "seed": spec.seed + i, + } + ) + manifest = self.build(boot_spec, verbose=verbose) + # Tag bootstrap_id + manifest.df["bootstrap_id"] = i + manifests.append(manifest) + return manifests + + # ── Mode: Native ────────────────────────────────────────────────────────── + + def _build_native(self, spec: TrialSpec, rng: np.random.Generator, verbose: bool) -> list[dict]: + """Patient + their own nodule. No cross-patient mixing.""" + pool = self._select_nodule_pool(spec) + + if spec.malignancy_prevalence is not None: + pool = self._sample_by_prevalence(pool, spec, rng) + else: + pool = self._sample_pool(pool, spec.n_cases, rng) + + rows = [] + for case_id, (_, nod) in enumerate(pool.iterrows()): + case_rows = self._build_case_rows( + case_id=case_id, + spec=spec, + donor_row=nod, + host_row=nod, # same patient + target_diam_mm=None, + rng=rng, + ) + rows.extend(case_rows) + + return rows + + # ── Mode: Matched ───────────────────────────────────────────────────────── + + def _build_matched( + self, spec: TrialSpec, rng: np.random.Generator, verbose: bool + ) -> list[dict]: + """Host CT + anatomically-matched donor nodule via ReinsertionMatcher.""" + host_pool = self._select_host_pool(spec) + donor_pool = self._select_nodule_pool(spec) + + # Sample target sizes + target_sizes = self._sample_target_sizes(spec, rng) + + # Sample labels + labels = self._sample_label_assignments(spec, rng) + + # Sample hosts + n = spec.n_cases + if len(host_pool) < n: + host_indices = rng.choice(len(host_pool), size=n, replace=True) + else: + host_indices = rng.choice(len(host_pool), size=n, replace=False) + + rows = [] + for case_id in range(n): + host_row = host_pool.iloc[host_indices[case_id]] + target_diam = target_sizes[case_id] if target_sizes is not None else None + label = labels[case_id] if labels is not None else None + + # Build reinsertion target for matching + target = ReinsertionTarget( + lobe=str(host_row.get("reinsertion_lobe", "right_lung_upper_lobe")), + lobe_cc_pct=float(host_row.get("reinsertion_lobe_cc_pct", 50)), + diameter_mm=target_diam, + label=label, + include_datasets=spec.donor_datasets or [], + exclude_datasets=spec.exclude_datasets or [], + ) + + match = self._matcher.find_best(target) + if match is None: + # Fallback: relax label constraint + target.label = None + match = self._matcher.find_best(target) + + if match is None: + if verbose: + warnings.warn(f"Case {case_id}: no donor found, skipping") + continue + + case_rows = self._build_case_rows( + case_id=case_id, + spec=spec, + donor_row=match.row, + host_row=host_row, + target_diam_mm=target_diam, + rng=rng, + label_override=label, + ) + rows.extend(case_rows) + + return rows + + # ── Mode: Synthetic ─────────────────────────────────────────────────────── + + def _build_synthetic( + self, spec: TrialSpec, rng: np.random.Generator, verbose: bool + ) -> list[dict]: + """Any nodule + any host CT, paired independently.""" + donor_pool = self._select_nodule_pool(spec) + host_pool = self._select_host_pool(spec) + + target_sizes = self._sample_target_sizes(spec, rng) + labels = self._sample_label_assignments(spec, rng) + + n = spec.n_cases + + rows = [] + for case_id in range(n): + label = labels[case_id] if labels is not None else None + target_diam = target_sizes[case_id] if target_sizes is not None else None + + # Select donor matching label and size + donor_row = self._find_donor(donor_pool, label, target_diam, rng) + if donor_row is None: + if verbose: + warnings.warn(f"Case {case_id}: no suitable donor, skipping") + continue + + # Select host randomly + host_idx = rng.integers(0, len(host_pool)) + host_row = host_pool.iloc[host_idx] + + case_rows = self._build_case_rows( + case_id=case_id, + spec=spec, + donor_row=donor_row, + host_row=host_row, + target_diam_mm=target_diam, + rng=rng, + label_override=label, + ) + rows.extend(case_rows) + + return rows + + # ── Pool selection ──────────────────────────────────────────────────────── + + def _filter_missing_masks( + self, + pool: pd.DataFrame, + dataset: str, + verbose: bool = True, + ) -> pd.DataFrame: + """Drop rows whose nodule mask file does not exist on disk. + + This prevents downstream insertion failures caused by annotations + in the NoduleIndex that lack a corresponding segmentation mask + (upstream data gap). Skipped when the mask directory doesn't exist + (e.g. in unit-test environments with synthetic data). + """ + mask_dir = os.path.join(self._resolver._base_dir, "masks", dataset, "nodule_seg") + if not os.path.isdir(mask_dir): + return pool + + mask_exists = pool.apply( + lambda row: os.path.isfile( + self._resolver.resolve_nodule_mask_path( + dataset, + str(row["annotation_id"]), + ct_id=PathResolver.extract_ct_id(str(row.get("ct_path", ""))), + ) + ), + axis=1, + ) + n_missing = (~mask_exists).sum() + if n_missing > 0 and verbose: + dropped = pool.loc[~mask_exists, "annotation_id"].tolist() + print(f" ⚠ Dropped {n_missing} annotation(s) with missing nodule masks: " f"{dropped}") + return pool[mask_exists].reset_index(drop=True) + + def _select_nodule_pool(self, spec: TrialSpec) -> pd.DataFrame: + """Use NoduleQuery to build the donor nodule pool.""" + q = self._index.query() + + # Dataset constraints + ds = spec.donor_datasets or spec.source_datasets + if ds: + q = q.datasets(ds) + if spec.exclude_datasets: + q = q.exclude_datasets(spec.exclude_datasets) + + # Training exclusion — remove datasets the model was trained on + if spec.exclude_training_datasets: + q = q.exclude_datasets(spec.exclude_training_datasets) + + # Nodule spec constraints + ns = spec.nodule_spec + if ns: + if ns.diameter_range: + q = q.reinsertion_diameter(min=ns.diameter_range[0], max=ns.diameter_range[1]) + if ns.lobe: + q = q.reinsertion_lobe(ns.lobe) + if ns.zone: + q = q.reinsertion_zone(ns.zone) + if ns.side: + q = q.reinsertion_side(ns.side) + if ns.pleural_distance_range: + q = q.reinsertion_pleural( + min=ns.pleural_distance_range[0], + max=ns.pleural_distance_range[1], + ) + if ns.exclude_all_malignant_datasets: + q = q.exclude_datasets(["NSCLCR"]) + + # Label source filter: histopathology, radiology, or all + if ns.label_source and ns.label_source != "all": + allowed = LABEL_SOURCE_MAP.get(ns.label_source) + if allowed: + q = q.datasets(allowed) + elif ns.require_histopath_label: # deprecated fallback + q = q.datasets(HISTOPATH_DATASETS) + + # Population type filter: screening, diagnostic, or all + if ns.population_type and ns.population_type != "all": + allowed = POPULATION_TYPE_MAP.get(ns.population_type) + if allowed: + q = q.datasets(allowed) + + # Multi-nodule filter + if ns.n_nodules_filter == "single_only": + q = q.n_nodules_in_patient(min=1, max=1) + elif ns.n_nodules_filter == "multi_only": + q = q.n_nodules_in_patient(min=2) + + pool = q.fetch() + + # Filter out annotations whose mask files are missing on disk. + # This prevents deterministic Stage-2 failures for all build paths + # (modes 1-10 synthetic/matched/native AND digital-twin modes). + if hasattr(self, "_resolver") and hasattr(self._resolver, "_base_dir"): + datasets = pool["dataset"].unique() if "dataset" in pool.columns else [] + parts = [] + for ds in datasets: + ds_mask = pool["dataset"] == ds + ds_pool = pool[ds_mask] + filtered = self._filter_missing_masks(ds_pool, ds, verbose=True) + parts.append(filtered) + if parts: + pool = pd.concat(parts, ignore_index=True) + + return pool + + def _select_host_pool(self, spec: TrialSpec) -> pd.DataFrame: + """Select unique patient CTs for the host pool.""" + q = self._index.query() + + ds = spec.host_datasets or spec.source_datasets + if ds: + q = q.datasets(ds) + if spec.exclude_datasets: + q = q.exclude_datasets(spec.exclude_datasets) + + # Training exclusion — remove datasets the model was trained on + if spec.exclude_training_datasets: + q = q.exclude_datasets(spec.exclude_training_datasets) + + # Population type filter applies to hosts too + ns = spec.nodule_spec + if ns and ns.population_type and ns.population_type != "all": + allowed = POPULATION_TYPE_MAP.get(ns.population_type) + if allowed: + q = q.datasets(allowed) + + pool = q.fetch() + # Deduplicate to one row per patient (first nodule row) + pool = pool.drop_duplicates(subset=["patient_id", "ct_path"], keep="first") + + # Filter out hosts whose organ segmentation file is missing on disk. + # This prevents deterministic Stage-2 "Failed to load organ seg" errors. + if hasattr(self, "_resolver") and hasattr(self._resolver, "_base_dir"): + + def _has_organ_seg(row): + seg_path = self._resolver.resolve_organ_seg_path( + str(row.get("dataset", "")), + PathResolver.extract_ct_id(str(row.get("ct_path", ""))), + ) + return os.path.isfile(seg_path) + + seg_exists = pool.apply(_has_organ_seg, axis=1) + n_missing = (~seg_exists).sum() + if n_missing > 0: + dropped_ids = pool.loc[~seg_exists, "patient_id"].tolist() + print( + f" \u26a0 Dropped {n_missing} host(s) with missing organ " + f"segmentations: {dropped_ids}" + ) + pool = pool[seg_exists].reset_index(drop=True) + + return pool.reset_index(drop=True) + + # ── Sampling helpers ────────────────────────────────────────────────────── + + def _sample_by_prevalence( + self, pool: pd.DataFrame, spec: TrialSpec, rng: np.random.Generator + ) -> pd.DataFrame: + """Sample from pool respecting malignancy prevalence.""" + prev = spec.malignancy_prevalence + if prev is None: + return self._sample_pool(pool, spec.n_cases, rng) + + n = spec.n_cases + n_mal = int(round(n * prev)) + n_ben = n - n_mal + + mal_pool = pool[pool["label"] == 1] + ben_pool = pool[pool["label"] == 0] + + mal_n = min(n_mal, len(mal_pool)) + ben_n = min(n_ben, len(ben_pool)) + + mal_sample = ( + mal_pool.sample(n=mal_n, random_state=rng.integers(2**31)) + if mal_n > 0 + else mal_pool.iloc[:0] + ) + ben_sample = ( + ben_pool.sample(n=ben_n, random_state=rng.integers(2**31)) + if ben_n > 0 + else ben_pool.iloc[:0] + ) + + result = pd.concat([mal_sample, ben_sample], ignore_index=True) + return result.sample(frac=1, random_state=rng.integers(2**31)).reset_index(drop=True) + + def _sample_pool(self, pool: pd.DataFrame, n: int, rng: np.random.Generator) -> pd.DataFrame: + """Simple random sample from pool.""" + replace = len(pool) < n + return pool.sample(n=n, replace=replace, random_state=rng.integers(2**31)).reset_index( + drop=True + ) + + def _sample_target_sizes( + self, spec: TrialSpec, rng: np.random.Generator + ) -> Optional[np.ndarray]: + """Sample target diameters from spec if size distribution is defined.""" + ns = spec.nodule_spec + if ns and ns.size_distribution: + sd = ns.size_distribution + if sd.bucket_weights: + return DistributionSampler.sample_size_from_buckets( + sd.bucket_weights, spec.n_cases, rng + ) + elif sd.mean_log_mm is not None and sd.std_log_mm is not None: + return DistributionSampler.sample_size_lognormal( + spec.n_cases, sd.mean_log_mm, sd.std_log_mm, sd.min_mm, sd.max_mm, rng + ) + return None + + def _sample_label_assignments( + self, spec: TrialSpec, rng: np.random.Generator + ) -> Optional[np.ndarray]: + """Sample label assignments from prevalence.""" + if spec.malignancy_prevalence is not None: + return DistributionSampler.sample_labels(spec.n_cases, spec.malignancy_prevalence, rng) + return None + + def _find_donor( + self, + pool: pd.DataFrame, + label: Optional[int], + target_diam: Optional[float], + rng: np.random.Generator, + ) -> Optional[pd.Series]: + """Find a suitable donor nodule from the pool.""" + candidates = pool + + # Filter by label + if label is not None: + label_match = candidates[candidates["label"] == label] + if len(label_match) > 0: + candidates = label_match + + # Filter by size (within 50% tolerance for initial search) + if target_diam is not None and len(candidates) > 5: + lo = target_diam * 0.5 + hi = target_diam * 2.0 + size_match = candidates[ + (candidates["reinsertion_nodule_diam_mm"] >= lo) + & (candidates["reinsertion_nodule_diam_mm"] <= hi) + ] + if len(size_match) > 0: + candidates = size_match + + if len(candidates) == 0: + return None + + idx = rng.integers(0, len(candidates)) + return candidates.iloc[idx] + + # ── Companion resolution ───────────────────────────────────────────────── + + def _resolve_companions( + self, + primary_row: pd.Series, + spec: TrialSpec, + ) -> list[pd.Series]: + """Find companion nodules from the same donor patient. + + Uses the all_nodule_ids field (comma-delimited annotation IDs) + to look up sibling nodules in the index DataFrame. + + Returns list of pd.Series rows (excluding the primary itself). + Skipped in native mode (nodules already exist in the CT). + """ + if spec.companion_strategy == "none": + return [] + if spec.cohort_mode == "native": + return [] + + all_ids_str = primary_row.get("all_nodule_ids") + if pd.isna(all_ids_str) or not all_ids_str: + return [] + + all_ids = [aid.strip() for aid in str(all_ids_str).split(",")] + primary_id = str(primary_row.get("annotation_id", "")) + companion_ids = [aid for aid in all_ids if aid and aid != primary_id] + + if not companion_ids: + return [] + + # Look up companions in the full index + idx_df = self._index.df + companions = idx_df[idx_df["annotation_id"].isin(companion_ids)] + + # Apply strategy filter + if spec.companion_strategy == "ipsilateral": + primary_side = primary_row.get("reinsertion_lung_side", "") + companions = companions[companions["reinsertion_lung_side"] == primary_side] + elif spec.companion_strategy == "same_lobe": + primary_lobe = primary_row.get("reinsertion_lobe", "") + companions = companions[companions["reinsertion_lobe"] == primary_lobe] + # "all_companions" → no further filter + + return [row for _, row in companions.iterrows()] + + # ── Case row assembly ───────────────────────────────────────────────────── + + def _build_case_rows( + self, + case_id: int, + spec: TrialSpec, + donor_row: pd.Series, + host_row: pd.Series, + target_diam_mm: Optional[float], + rng: np.random.Generator, + label_override: Optional[int] = None, + ) -> list[dict]: + """Assemble manifest rows for a case, including any companions.""" + primary = self._build_single_row( + case_id=case_id, + spec=spec, + donor_row=donor_row, + host_row=host_row, + target_diam_mm=target_diam_mm, + rng=rng, + label_override=label_override, + nodule_idx=0, + is_primary=True, + ) + rows = [primary] + + # Resolve companions + companions = self._resolve_companions(donor_row, spec) + for i, comp_row in enumerate(companions): + comp = self._build_single_row( + case_id=case_id, + spec=spec, + donor_row=comp_row, + host_row=host_row, + target_diam_mm=None, # companions keep original size + rng=rng, + label_override=None, # companions keep their own label + nodule_idx=i + 1, + is_primary=False, + ) + rows.append(comp) + + # Set n_nodules_in_case on all rows + n = len(rows) + for r in rows: + r["n_nodules_in_case"] = n + r["companion_group_id"] = case_id + + return rows + + def _build_single_row( + self, + case_id: int, + spec: TrialSpec, + donor_row: pd.Series, + host_row: pd.Series, + target_diam_mm: Optional[float], + rng: np.random.Generator, + label_override: Optional[int] = None, + nodule_idx: int = 0, + is_primary: bool = True, + ) -> dict: + """Assemble a single manifest row.""" + # Insertion planning + plan = self._planner.plan( + nodule_row=donor_row, + mode=spec.insertion_mode, + target_diam_mm=target_diam_mm, + insertion_spec=spec.insertion_spec, + rng=rng, + ) + + # Path resolution + host_ds = str(host_row.get("dataset", "")) + donor_ds = str(donor_row.get("dataset", "")) + host_ct_rel = str(host_row.get("ct_path", "")) + donor_ct_rel = str(donor_row.get("ct_path", "")) + donor_ann_id = str(donor_row.get("annotation_id", "")) + host_ct_id = PathResolver.extract_ct_id(host_ct_rel) + donor_ct_id = PathResolver.extract_ct_id(donor_ct_rel) + + # Label + if label_override is not None: + label = label_override + else: + raw_label = donor_row.get("label") + label = int(raw_label) if pd.notna(raw_label) else None + + # Diameter + donor_diam = float(donor_row.get("reinsertion_nodule_diam_mm", 0)) + effective_diam = plan.effective_diam_mm if plan.effective_diam_mm > 0 else donor_diam + + # Size bucket + size_bucket = _diameter_to_bucket(effective_diam) if effective_diam > 0 else "" + + # Population type and label source + population_type = "screening" if donor_ds in SCREENING_DATASETS else "diagnostic" + label_source = "histopathology" if donor_ds in HISTOPATH_DATASETS else "radiology" + + # Demographics extraction + patient_age, patient_sex, smoking_status, pack_years = self._extract_demographics( + host_row, host_ds + ) + + return { + # Case identity + "case_id": case_id, + "nodule_idx": nodule_idx, + "is_primary_nodule": is_primary, + "n_nodules_in_case": 1, # updated by _build_case_rows + "companion_group_id": case_id, # updated by _build_case_rows + "trial_name": spec.trial_name, + "trial_template": spec.trial_template or "", + "bootstrap_id": 0, + # Host CT + "host_patient_id": str(host_row.get("patient_id", "")), + "host_dataset": host_ds, + "host_ct_path": self._resolver.resolve_ct_path(host_ds, host_ct_rel), + "host_organ_seg_path": self._resolver.resolve_organ_seg_path(host_ds, host_ct_id), + # Donor nodule + "donor_patient_id": str(donor_row.get("patient_id", "")), + "donor_annotation_id": donor_ann_id, + "donor_dataset": donor_ds, + "donor_nodule_mask_path": self._resolver.resolve_nodule_mask_path( + donor_ds, donor_ann_id, ct_id=donor_ct_id + ), + "donor_ct_path": self._resolver.resolve_ct_path(donor_ds, donor_ct_rel), + "donor_refined_seg_path": self._resolver.resolve_refined_seg_path( + donor_ds, donor_ct_id + ), + # Insertion + "insertion_coord_x": plan.insertion_coord_x, + "insertion_coord_y": plan.insertion_coord_y, + "insertion_coord_z": plan.insertion_coord_z, + "insertion_lobe": plan.insertion_lobe, + "insertion_lobe_cc_pct": plan.insertion_lobe_cc_pct, + "insertion_lobe_ml_pct": plan.insertion_lobe_ml_pct, + "insertion_lobe_ap_pct": plan.insertion_lobe_ap_pct, + "insertion_mode": plan.insertion_mode, + # Nodule characteristics + "nodule_diam_mm": donor_diam, + "effective_diam_mm": effective_diam, + "scale_factor": plan.scale_factor, + "warp_applied": plan.warp_applied, + "label": label, + # Anatomy + "nodule_lobe_name": str(donor_row.get("reinsertion_lobe", "")), + "nodule_lung_side": str(donor_row.get("reinsertion_lung_side", "")), + "nodule_lung_zone": str(donor_row.get("reinsertion_lung_zone", "")), + "nodule_central_peripheral": str(donor_row.get("central_peripheral", "")), + "pleural_distance_mm": donor_row.get("reinsertion_pleural_dist_mm"), + # Demographics + "patient_age": patient_age, + "patient_sex": patient_sex, + "smoking_status": smoking_status, + "pack_years": pack_years, + # Cohort metadata + "cohort_mode": spec.cohort_mode, + "size_bucket": size_bucket, + "population_type": population_type, + "label_source": label_source, + } + + @staticmethod + def _extract_demographics( + row: pd.Series, dataset: str + ) -> tuple[Optional[float], Optional[str], Optional[str], Optional[float]]: + """Extract demographics from meta columns (best-effort).""" + col_map = _DEMO_COL_MAP.get(dataset, {}) + + age = None + sex = None + smoking = None + pack_years = None + + for src_col, tgt in col_map.items(): + val = row.get(src_col) + if pd.isna(val) if isinstance(val, float) else (val is None): + continue + if tgt == "patient_age": + try: + age = float(val) + except (ValueError, TypeError): + pass + elif tgt == "patient_sex": + sex = str(val) + elif tgt == "smoking_status": + smoking = str(val) + elif tgt == "pack_years": + try: + pack_years = float(val) + except (ValueError, TypeError): + pass + + return age, sex, smoking, pack_years + + # ── Digital twin isolation ──────────────────────────────────────────────── + + def build_digital_twin_isolation( + self, + spec: DigitalTwinIsolationSpec, + verbose: bool = True, + ) -> CohortManifest: + """Build a digital twin isolation manifest. + + For each CT scan in the dataset, generates one isolation case + per native nodule. Each case pairs the host's clean anatomy mask + with exactly one native nodule mask. + + Matching is at the CT-scan level: a nodule is only paired with + the CT it was originally annotated from. Patients with multiple + CT scans produce separate cases per CT (not grouped by patient). + + Returns a CohortManifest whose DataFrame uses the extended + ISOLATION_MANIFEST_COLS schema. + """ + from itrialspace.site.sampling import _diameter_to_bucket + + rng = np.random.default_rng(spec.seed) + dataset = spec.dataset + + # 1. Select nodule pool from the target dataset + q = self._index.query().datasets([dataset]) + + # Apply nodule-level filters + ns = spec.nodule_spec + if ns: + if ns.label is not None: + q = q.label(ns.label) + if ns.diameter_range: + lo, hi = ns.diameter_range + if lo is not None: + q = q.reinsertion_diameter(min=lo) + if hi is not None: + q = q.reinsertion_diameter(max=hi) + + pool = q.fetch() + + # Filter out annotations whose mask files are missing on disk + pool = self._filter_missing_masks(pool, dataset, verbose=verbose) + + if len(pool) == 0: + raise ValueError( + f"No eligible nodules found in dataset '{dataset}' with the given filters." + ) + + # 2. Group by patient (for user-facing selection), then by CT scan + grouped_by_patient = pool.groupby("patient_id") + all_patient_ids = sorted(grouped_by_patient.groups.keys()) + + total_eligible_patients = len(all_patient_ids) + total_eligible_nodules = len(pool) + + # 3. Select patients + if spec.all_patients: + selected_ids = all_patient_ids + else: + n = min(spec.max_patients, total_eligible_patients) + indices = rng.choice(total_eligible_patients, size=n, replace=False) + indices.sort() + selected_ids = [all_patient_ids[i] for i in indices] + + total_selected_patients = len(selected_ids) + + # Gather nodules for selected patients, then group by ct_path + selected_pool = pool[pool["patient_id"].isin(selected_ids)] + grouped_by_ct = selected_pool.groupby("ct_path") + total_eligible_cts = len(grouped_by_ct) + + if verbose: + print(f"Dataset: {dataset}") + print(f" Eligible patients: {total_eligible_patients}") + print(f" Selected patients: {total_selected_patients}") + print(f" CT scans (selected): {total_eligible_cts}") + print(f" Eligible nodules (total pool): {total_eligible_nodules}") + + # 4. Build isolation cases — group by CT scan, not patient + rows = [] + case_id = 0 + + for ct_path_key in sorted(grouped_by_ct.groups.keys()): + ct_nodules = grouped_by_ct.get_group(ct_path_key).reset_index(drop=True) + host_n_nodules = len(ct_nodules) + patient_id = ct_nodules.iloc[0]["patient_id"] + + # Optionally cap nodules per patient + if spec.max_nodules_per_patient is not None: + ct_nodules = ct_nodules.head(spec.max_nodules_per_patient) + + for iso_idx, (_, nod) in enumerate(ct_nodules.iterrows()): + ct_rel = str(nod.get("ct_path", "")) + ct_id = PathResolver.extract_ct_id(ct_rel) + ann_id = str(nod.get("annotation_id", "")) + donor_diam = float(nod.get("reinsertion_nodule_diam_mm", 0)) + size_bucket = _diameter_to_bucket(donor_diam) if donor_diam > 0 else "" + + raw_label = nod.get("label") + label_val = int(raw_label) if pd.notna(raw_label) else None + + population_type = "screening" if dataset in SCREENING_DATASETS else "diagnostic" + label_source = "histopathology" if dataset in HISTOPATH_DATASETS else "radiology" + + patient_age, patient_sex, smoking_status, pack_years = self._extract_demographics( + nod, dataset + ) + + host_ct_abs = self._resolver.resolve_ct_path(dataset, ct_rel) + donor_ct_abs = self._resolver.resolve_ct_path(dataset, ct_rel) + + # Safety: host and donor must reference the same CT scan + assert host_ct_abs == donor_ct_abs, ( + f"CT mismatch: host={host_ct_abs} != donor={donor_ct_abs} " + f"for annotation {ann_id}" + ) + + row = { + # Case identity + "case_id": case_id, + "nodule_idx": 0, + "is_primary_nodule": True, + "n_nodules_in_case": 1, + "companion_group_id": case_id, + "trial_name": spec.trial_name, + "trial_template": "", + "bootstrap_id": 0, + # Host CT (same CT scan as the nodule) + "host_patient_id": str(patient_id), + "host_dataset": dataset, + "host_ct_path": host_ct_abs, + "host_organ_seg_path": self._resolver.resolve_organ_seg_path(dataset, ct_id), + # Donor = same CT scan's nodule (native) + "donor_patient_id": str(patient_id), + "donor_annotation_id": ann_id, + "donor_dataset": dataset, + "donor_nodule_mask_path": self._resolver.resolve_nodule_mask_path( + dataset, ann_id, ct_id=ct_id + ), + "donor_ct_path": donor_ct_abs, + "donor_refined_seg_path": self._resolver.resolve_refined_seg_path( + dataset, ct_id + ), + # Insertion — use nodule's own reinsertion coords (profile_faithful) + "insertion_coord_x": float(nod.get("coordX", 0)), + "insertion_coord_y": float(nod.get("coordY", 0)), + "insertion_coord_z": float(nod.get("coordZ", 0)), + "insertion_lobe": str(nod.get("reinsertion_lobe", "")), + "insertion_lobe_cc_pct": float(nod.get("reinsertion_lobe_cc_pct", 0)), + "insertion_lobe_ml_pct": float(nod.get("reinsertion_lobe_ml_pct", 0)), + "insertion_lobe_ap_pct": float(nod.get("reinsertion_lobe_ap_pct", 0)), + "insertion_mode": "profile_faithful", + # Nodule characteristics + "nodule_diam_mm": donor_diam, + "effective_diam_mm": donor_diam, + "scale_factor": 1.0, + "warp_applied": "none", + "label": label_val, + # Anatomy + "nodule_lobe_name": str(nod.get("reinsertion_lobe", "")), + "nodule_lung_side": str(nod.get("reinsertion_lung_side", "")), + "nodule_lung_zone": str(nod.get("reinsertion_lung_zone", "")), + "nodule_central_peripheral": str(nod.get("central_peripheral", "")), + "pleural_distance_mm": nod.get("reinsertion_pleural_dist_mm"), + # Demographics + "patient_age": patient_age, + "patient_sex": patient_sex, + "smoking_status": smoking_status, + "pack_years": pack_years, + # Cohort metadata + "cohort_mode": "native", + "size_bucket": size_bucket, + "population_type": population_type, + "label_source": label_source, + # Digital twin isolation columns + "mode": "digital_twin_isolation", + "target_annotation_id": ann_id, + "target_nodule_mask_path": self._resolver.resolve_nodule_mask_path( + dataset, ann_id, ct_id=ct_id + ), + "target_diameter_mm": donor_diam, + "target_label": label_val, + "target_lobe": str(nod.get("reinsertion_lobe", "")), + "target_side": str(nod.get("reinsertion_lung_side", "")), + "target_zone": str(nod.get("reinsertion_lung_zone", "")), + "host_n_nodules": host_n_nodules, + "isolation_case_index": iso_idx, + } + rows.append(row) + case_id += 1 + + total_generated = len(rows) + + if verbose: + print(f" Generated isolation cases: {total_generated}") + print("\nSummary:") + print(f" Total eligible patients: {total_eligible_patients}") + print(f" Total selected patients: {total_selected_patients}") + print(f" Total CT scans: {total_eligible_cts}") + print(f" Total eligible nodules: {total_eligible_nodules}") + print(f" Total generated cases: {total_generated}") + + df = pd.DataFrame(rows) + + # Create a lightweight TrialSpec wrapper for CohortManifest compatibility + wrapper_spec = TrialSpec( + trial_name=spec.trial_name, + n_cases=total_generated, + cohort_mode="native", + seed=spec.seed, + source_datasets=[dataset], + base_dir=spec.base_dir, + ) + + return CohortManifest(df, wrapper_spec) + + # ── Digital twin complete ───────────────────────────────────────────────── + + def build_digital_twin_complete( + self, + spec: DigitalTwinCompleteSpec, + verbose: bool = True, + ) -> CohortManifest: + """Build a digital twin complete manifest. + + For each CT scan in the dataset, generates ONE case containing + ALL native nodules from that CT. Rows sharing a case_id are processed + sequentially by Stage 2 (insert_manifest), accumulating into one + combined conditioning mask per CT scan. + + Matching is at the CT-scan level: a nodule is only paired with + the CT it was originally annotated from. Patients with multiple + CT scans produce one case per CT (not one case per patient). + + Returns a CohortManifest whose DataFrame uses the extended + COMPLETE_MANIFEST_COLS schema. + """ + from itrialspace.site.sampling import _diameter_to_bucket + + rng = np.random.default_rng(spec.seed) + dataset = spec.dataset + + # 1. Select nodule pool from the target dataset + q = self._index.query().datasets([dataset]) + + # Apply nodule-level filters + ns = spec.nodule_spec + if ns: + if ns.label is not None: + q = q.label(ns.label) + if ns.diameter_range: + lo, hi = ns.diameter_range + if lo is not None: + q = q.reinsertion_diameter(min=lo) + if hi is not None: + q = q.reinsertion_diameter(max=hi) + + pool = q.fetch() + + # Filter out annotations whose mask files are missing on disk + pool = self._filter_missing_masks(pool, dataset, verbose=verbose) + + if len(pool) == 0: + raise ValueError( + f"No eligible nodules found in dataset '{dataset}' with the given filters." + ) + + # 2. Group by patient (for user-facing selection), then by CT scan + grouped_by_patient = pool.groupby("patient_id") + all_patient_ids = sorted(grouped_by_patient.groups.keys()) + + total_eligible_patients = len(all_patient_ids) + total_eligible_nodules = len(pool) + + # 3. Select patients + if spec.all_patients: + selected_ids = all_patient_ids + else: + n = min(spec.max_patients, total_eligible_patients) + indices = rng.choice(total_eligible_patients, size=n, replace=False) + indices.sort() + selected_ids = [all_patient_ids[i] for i in indices] + + total_selected_patients = len(selected_ids) + + # Gather nodules for selected patients, then group by ct_path + selected_pool = pool[pool["patient_id"].isin(selected_ids)] + grouped_by_ct = selected_pool.groupby("ct_path") + total_eligible_cts = len(grouped_by_ct) + + if verbose: + print(f"Dataset: {dataset}") + print(f" Eligible patients: {total_eligible_patients}") + print(f" Selected patients: {total_selected_patients}") + print(f" CT scans (selected): {total_eligible_cts}") + print(f" Eligible nodules (total pool): {total_eligible_nodules}") + + # 4. Build complete cases — one case_id per CT scan, one row per nodule + rows = [] + case_id = 0 + total_nodules = 0 + + for ct_path_key in sorted(grouped_by_ct.groups.keys()): + ct_nodules = grouped_by_ct.get_group(ct_path_key).reset_index(drop=True) + n_nodules = len(ct_nodules) + total_nodules += n_nodules + patient_id = ct_nodules.iloc[0]["patient_id"] + + # Collect per-CT summary lists for the case-level columns + ann_ids_list = [] + diams_list = [] + labels_list = [] + lobes_list = [] + sides_list = [] + zones_list = [] + + for _, nod in ct_nodules.iterrows(): + ann_ids_list.append(str(nod.get("annotation_id", ""))) + diams_list.append(str(round(float(nod.get("reinsertion_nodule_diam_mm", 0)), 2))) + raw_label = nod.get("label") + labels_list.append(str(int(raw_label)) if pd.notna(raw_label) else "") + lobes_list.append(str(nod.get("reinsertion_lobe", ""))) + sides_list.append(str(nod.get("reinsertion_lung_side", ""))) + zones_list.append(str(nod.get("reinsertion_lung_zone", ""))) + + # Semicolon-delimited summary strings + ann_ids_str = ";".join(ann_ids_list) + diams_str = ";".join(diams_list) + labels_str = ";".join(labels_list) + lobes_str = ";".join(lobes_list) + sides_str = ";".join(sides_list) + zones_str = ";".join(zones_list) + + for nod_idx, (_, nod) in enumerate(ct_nodules.iterrows()): + ct_rel = str(nod.get("ct_path", "")) + ct_id = PathResolver.extract_ct_id(ct_rel) + ann_id = str(nod.get("annotation_id", "")) + donor_diam = float(nod.get("reinsertion_nodule_diam_mm", 0)) + size_bucket = _diameter_to_bucket(donor_diam) if donor_diam > 0 else "" + + raw_label = nod.get("label") + label_val = int(raw_label) if pd.notna(raw_label) else None + + population_type = "screening" if dataset in SCREENING_DATASETS else "diagnostic" + label_source = "histopathology" if dataset in HISTOPATH_DATASETS else "radiology" + + patient_age, patient_sex, smoking_status, pack_years = self._extract_demographics( + nod, dataset + ) + + host_ct_abs = self._resolver.resolve_ct_path(dataset, ct_rel) + donor_ct_abs = self._resolver.resolve_ct_path(dataset, ct_rel) + + # Safety: host and donor must reference the same CT scan + assert host_ct_abs == donor_ct_abs, ( + f"CT mismatch: host={host_ct_abs} != donor={donor_ct_abs} " + f"for annotation {ann_id}" + ) + + row = { + # Case identity — same case_id for all nodules in this CT + "case_id": case_id, + "nodule_idx": nod_idx, + "is_primary_nodule": nod_idx == 0, + "n_nodules_in_case": n_nodules, + "companion_group_id": case_id, + "trial_name": spec.trial_name, + "trial_template": "", + "bootstrap_id": 0, + # Host CT (same CT scan as the nodule) + "host_patient_id": str(patient_id), + "host_dataset": dataset, + "host_ct_path": host_ct_abs, + "host_organ_seg_path": self._resolver.resolve_organ_seg_path(dataset, ct_id), + # Donor = same CT scan's nodule (native) + "donor_patient_id": str(patient_id), + "donor_annotation_id": ann_id, + "donor_dataset": dataset, + "donor_nodule_mask_path": self._resolver.resolve_nodule_mask_path( + dataset, ann_id, ct_id=ct_id + ), + "donor_ct_path": donor_ct_abs, + "donor_refined_seg_path": self._resolver.resolve_refined_seg_path( + dataset, ct_id + ), + # Insertion — profile_faithful at native coordinates + "insertion_coord_x": float(nod.get("coordX", 0)), + "insertion_coord_y": float(nod.get("coordY", 0)), + "insertion_coord_z": float(nod.get("coordZ", 0)), + "insertion_lobe": str(nod.get("reinsertion_lobe", "")), + "insertion_lobe_cc_pct": float(nod.get("reinsertion_lobe_cc_pct", 0)), + "insertion_lobe_ml_pct": float(nod.get("reinsertion_lobe_ml_pct", 0)), + "insertion_lobe_ap_pct": float(nod.get("reinsertion_lobe_ap_pct", 0)), + "insertion_mode": "profile_faithful", + # Nodule characteristics + "nodule_diam_mm": donor_diam, + "effective_diam_mm": donor_diam, + "scale_factor": 1.0, + "warp_applied": "none", + "label": label_val, + # Anatomy + "nodule_lobe_name": str(nod.get("reinsertion_lobe", "")), + "nodule_lung_side": str(nod.get("reinsertion_lung_side", "")), + "nodule_lung_zone": str(nod.get("reinsertion_lung_zone", "")), + "nodule_central_peripheral": str(nod.get("central_peripheral", "")), + "pleural_distance_mm": nod.get("reinsertion_pleural_dist_mm"), + # Demographics + "patient_age": patient_age, + "patient_sex": patient_sex, + "smoking_status": smoking_status, + "pack_years": pack_years, + # Cohort metadata + "cohort_mode": "native", + "size_bucket": size_bucket, + "population_type": population_type, + "label_source": label_source, + # Digital twin complete columns + "mode": "digital_twin_complete", + "host_n_nodules": n_nodules, + "annotation_ids": ann_ids_str, + "diameters_mm": diams_str, + "labels": labels_str, + "lobes": lobes_str, + "sides": sides_str, + "zones": zones_str, + } + rows.append(row) + + case_id += 1 + + total_generated_cases = case_id + total_rows = len(rows) + + if verbose: + print(f" Generated cases: {total_generated_cases}") + print(f" Total manifest rows: {total_rows}") + print("\nSummary:") + print(f" Total eligible patients: {total_eligible_patients}") + print(f" Total selected patients: {total_selected_patients}") + print(f" Total CT scans: {total_eligible_cts}") + print(f" Total nodules: {total_nodules}") + print(f" Total generated cases: {total_generated_cases}") + + df = pd.DataFrame(rows) + + # Create a lightweight TrialSpec wrapper for CohortManifest compatibility + wrapper_spec = TrialSpec( + trial_name=spec.trial_name, + n_cases=total_generated_cases, + cohort_mode="native", + seed=spec.seed, + source_datasets=[dataset], + base_dir=spec.base_dir, + ) + + return CohortManifest(df, wrapper_spec) + + # ── Digital twin cross ──────────────────────────────────────────────────── + + def build_digital_twin_cross( + self, + spec: DigitalTwinCrossSpec, + verbose: bool = True, + ) -> CohortManifest: + """Build a digital twin cross manifest. + + Pairs host anatomy from one patient/dataset with donor nodule(s) + from a *different* patient/dataset. Supports three pairing + policies and two donor transfer modes. + + Returns a CohortManifest whose DataFrame uses the extended + CROSS_MANIFEST_COLS schema. + """ + + rng = np.random.default_rng(spec.seed) + + # ── 1. Build host pool ─────────────────────────────────────────── + host_q = self._index.query().datasets([spec.host_dataset]) + if spec.exclude_training_datasets: + host_q = host_q.exclude_datasets(spec.exclude_training_datasets) + host_pool = host_q.fetch() + # Deduplicate to one row per host patient + host_pool = host_pool.drop_duplicates( + subset=["patient_id", "ct_path"], keep="first" + ).reset_index(drop=True) + + total_eligible_hosts = len(host_pool) + if total_eligible_hosts == 0: + raise ValueError(f"No eligible host patients in dataset '{spec.host_dataset}'.") + + # Select hosts + if spec.all_host_patients: + selected_hosts = host_pool + else: + n = min(spec.max_host_patients, total_eligible_hosts) + indices = rng.choice(total_eligible_hosts, size=n, replace=False) + indices.sort() + selected_hosts = host_pool.iloc[indices].reset_index(drop=True) + + # ── 2. Build donor pool ────────────────────────────────────────── + donor_q = self._index.query().datasets([spec.donor_dataset]) + if spec.exclude_training_datasets: + donor_q = donor_q.exclude_datasets(spec.exclude_training_datasets) + + ns = spec.nodule_spec + if ns: + if ns.label is not None: + donor_q = donor_q.label(ns.label) + if ns.diameter_range: + lo, hi = ns.diameter_range + if lo is not None: + donor_q = donor_q.reinsertion_diameter(min=lo) + if hi is not None: + donor_q = donor_q.reinsertion_diameter(max=hi) + + donor_pool = donor_q.fetch() + + if len(donor_pool) == 0: + raise ValueError( + f"No eligible donor nodules in dataset '{spec.donor_dataset}' " + f"with the given filters." + ) + + # Group donors by patient + donor_grouped = donor_pool.groupby("patient_id") + all_donor_patient_ids = sorted(donor_grouped.groups.keys()) + total_eligible_donor_patients = len(all_donor_patient_ids) + total_eligible_donor_nodules = len(donor_pool) + + # Select donor patients + if spec.all_donor_patients: + selected_donor_ids = all_donor_patient_ids + elif spec.max_donor_patients is not None: + n = min(spec.max_donor_patients, total_eligible_donor_patients) + indices = rng.choice(total_eligible_donor_patients, size=n, replace=False) + indices.sort() + selected_donor_ids = [all_donor_patient_ids[i] for i in indices] + else: + # max_donor_nodules: take donors that cover that many nodules + selected_donor_ids = all_donor_patient_ids # will limit nodules below + + # Collect selected donor nodules + donor_nodules = [] + for pid in selected_donor_ids: + patient_nods = donor_grouped.get_group(pid).reset_index(drop=True) + for _, nod in patient_nods.iterrows(): + donor_nodules.append(nod) + + # Apply max_donor_nodules cap + if spec.max_donor_nodules is not None and len(donor_nodules) > spec.max_donor_nodules: + rng.shuffle(donor_nodules) + donor_nodules = donor_nodules[: spec.max_donor_nodules] + + total_selected_hosts = len(selected_hosts) + total_selected_donor_nodules = len(donor_nodules) + + if verbose: + print(f"Host dataset: {spec.host_dataset}") + print(f"Donor dataset: {spec.donor_dataset}") + print(f" Eligible host patients: {total_eligible_hosts}") + print(f" Selected host patients: {total_selected_hosts}") + print(f" Eligible donor patients: {total_eligible_donor_patients}") + print(f" Eligible donor nodules: {total_eligible_donor_nodules}") + print(f" Selected donor nodules: {total_selected_donor_nodules}") + + # ── 3. Build cross cases ───────────────────────────────────────── + rows = [] + case_id = 0 + + if spec.pairing_policy == "one_to_one": + # Each donor nodule paired with one host (round-robin across hosts) + for i, donor_nod in enumerate(donor_nodules): + host_idx = i % total_selected_hosts + host_row = selected_hosts.iloc[host_idx] + new_rows = self._build_cross_case_rows( + case_id=case_id, + spec=spec, + host_row=host_row, + donor_nodules_for_case=[donor_nod], + rng=rng, + ) + rows.extend(new_rows) + case_id += 1 + + elif spec.pairing_policy == "one_to_many_hosts": + # Same donor nodule paired with N hosts + n_hosts = min(spec.n_hosts_per_donor, total_selected_hosts) + for donor_nod in donor_nodules: + # Select N distinct hosts for this donor + host_indices = rng.choice(total_selected_hosts, size=n_hosts, replace=False) + for h_idx in host_indices: + host_row = selected_hosts.iloc[h_idx] + new_rows = self._build_cross_case_rows( + case_id=case_id, + spec=spec, + host_row=host_row, + donor_nodules_for_case=[donor_nod], + rng=rng, + ) + rows.extend(new_rows) + case_id += 1 + + elif spec.pairing_policy == "donor_patient_complete": + # All donor nodules from one donor patient → one host + # Group donor_nodules back by patient + from collections import defaultdict + + by_patient: dict[str, list] = defaultdict(list) + for nod in donor_nodules: + by_patient[str(nod.get("patient_id", ""))].append(nod) + + for i, (donor_pid, nods) in enumerate(by_patient.items()): + host_idx = i % total_selected_hosts + host_row = selected_hosts.iloc[host_idx] + new_rows = self._build_cross_case_rows( + case_id=case_id, + spec=spec, + host_row=host_row, + donor_nodules_for_case=nods, + rng=rng, + ) + rows.extend(new_rows) + case_id += 1 + + total_generated_cases = case_id + total_rows = len(rows) + + if verbose: + print(f"\n Generated cross cases: {total_generated_cases}") + print(f" Total manifest rows: {total_rows}") + print("\nSummary:") + print(f" Total eligible host patients: {total_eligible_hosts}") + print(f" Total selected host patients: {total_selected_hosts}") + print(f" Total eligible donor patients: {total_eligible_donor_patients}") + print(f" Total eligible donor nodules: {total_eligible_donor_nodules}") + print(f" Total selected donor nodules: {total_selected_donor_nodules}") + print(f" Total generated cross cases: {total_generated_cases}") + + df = pd.DataFrame(rows) + + wrapper_spec = TrialSpec( + trial_name=spec.trial_name, + n_cases=total_generated_cases, + cohort_mode="cross", + seed=spec.seed, + host_datasets=[spec.host_dataset], + donor_datasets=[spec.donor_dataset], + base_dir=spec.base_dir, + ) + + return CohortManifest(df, wrapper_spec) + + def _build_cross_case_rows( + self, + case_id: int, + spec: DigitalTwinCrossSpec, + host_row: pd.Series, + donor_nodules_for_case: list[pd.Series], + rng: np.random.Generator, + ) -> list[dict]: + """Assemble manifest rows for a single cross case. + + For donor_transfer_mode="single", donor_nodules_for_case has 1 element. + For "complete" or "donor_patient_complete" pairing, it may have many. + """ + from itrialspace.site.sampling import _diameter_to_bucket + + host_ds = spec.host_dataset + host_pid = str(host_row.get("patient_id", "")) + host_ct_rel = str(host_row.get("ct_path", "")) + host_ct_id = PathResolver.extract_ct_id(host_ct_rel) + + host_age, host_sex, host_smoking, host_pack_years = self._extract_demographics( + host_row, host_ds + ) + + rows = [] + n_nodules = len(donor_nodules_for_case) + + for nod_idx, donor_nod in enumerate(donor_nodules_for_case): + donor_ds = spec.donor_dataset + donor_pid = str(donor_nod.get("patient_id", "")) + donor_ann_id = str(donor_nod.get("annotation_id", "")) + donor_ct_rel = str(donor_nod.get("ct_path", "")) + donor_ct_id = PathResolver.extract_ct_id(donor_ct_rel) + donor_diam = float(donor_nod.get("reinsertion_nodule_diam_mm", 0)) + size_bucket = _diameter_to_bucket(donor_diam) if donor_diam > 0 else "" + + raw_label = donor_nod.get("label") + label_val = int(raw_label) if pd.notna(raw_label) else None + + population_type = "screening" if donor_ds in SCREENING_DATASETS else "diagnostic" + label_source = "histopathology" if donor_ds in HISTOPATH_DATASETS else "radiology" + + # Insertion planning — use donor's reinsertion profile + # profile_faithful_transfer: preserve donor's anatomical coordinates + # host_constrained_transfer: use prescribed mode to resample in host + if spec.placement_strategy == "profile_faithful_transfer": + plan = self._planner.plan( + nodule_row=donor_nod, + mode="profile_faithful", + target_diam_mm=None, + insertion_spec=None, + rng=rng, + ) + else: + # host_constrained_transfer: use prescribed mode with donor's lobe info + from itrialspace.site.spec import InsertionSpec + + insertion_spec = InsertionSpec( + target_lobe=str(donor_nod.get("reinsertion_lobe", "")), + ) + plan = self._planner.plan( + nodule_row=donor_nod, + mode="prescribed", + target_diam_mm=None, + insertion_spec=insertion_spec, + rng=rng, + ) + + row = { + # Case identity + "case_id": case_id, + "nodule_idx": nod_idx, + "is_primary_nodule": nod_idx == 0, + "n_nodules_in_case": n_nodules, + "companion_group_id": case_id, + "trial_name": spec.trial_name, + "trial_template": "", + "bootstrap_id": 0, + # Host CT — from host patient + "host_patient_id": host_pid, + "host_dataset": host_ds, + "host_ct_path": self._resolver.resolve_ct_path(host_ds, host_ct_rel), + "host_organ_seg_path": self._resolver.resolve_organ_seg_path(host_ds, host_ct_id), + # Donor — from different patient/dataset + "donor_patient_id": donor_pid, + "donor_annotation_id": donor_ann_id, + "donor_dataset": donor_ds, + "donor_nodule_mask_path": self._resolver.resolve_nodule_mask_path( + donor_ds, donor_ann_id, ct_id=donor_ct_id + ), + "donor_ct_path": self._resolver.resolve_ct_path(donor_ds, donor_ct_rel), + "donor_refined_seg_path": self._resolver.resolve_refined_seg_path( + donor_ds, donor_ct_id + ), + # Insertion — from planner + "insertion_coord_x": plan.insertion_coord_x, + "insertion_coord_y": plan.insertion_coord_y, + "insertion_coord_z": plan.insertion_coord_z, + "insertion_lobe": plan.insertion_lobe, + "insertion_lobe_cc_pct": plan.insertion_lobe_cc_pct, + "insertion_lobe_ml_pct": plan.insertion_lobe_ml_pct, + "insertion_lobe_ap_pct": plan.insertion_lobe_ap_pct, + "insertion_mode": plan.insertion_mode, + # Nodule characteristics + "nodule_diam_mm": donor_diam, + "effective_diam_mm": ( + plan.effective_diam_mm if plan.effective_diam_mm > 0 else donor_diam + ), + "scale_factor": plan.scale_factor, + "warp_applied": plan.warp_applied, + "label": label_val, + # Anatomy (donor's native anatomy) + "nodule_lobe_name": str(donor_nod.get("reinsertion_lobe", "")), + "nodule_lung_side": str(donor_nod.get("reinsertion_lung_side", "")), + "nodule_lung_zone": str(donor_nod.get("reinsertion_lung_zone", "")), + "nodule_central_peripheral": str(donor_nod.get("central_peripheral", "")), + "pleural_distance_mm": donor_nod.get("reinsertion_pleural_dist_mm"), + # Demographics (from host) + "patient_age": host_age, + "patient_sex": host_sex, + "smoking_status": host_smoking, + "pack_years": host_pack_years, + # Cohort metadata + "cohort_mode": "cross", + "size_bucket": size_bucket, + "population_type": population_type, + "label_source": label_source, + # Digital twin cross columns + "mode": "digital_twin_cross", + "donor_transfer_mode": spec.donor_transfer_mode, + "pairing_policy": spec.pairing_policy, + "placement_strategy": spec.placement_strategy, + "cross_case_group_id": case_id, + } + rows.append(row) + + return rows diff --git a/itrialspace/src/itrialspace/site/config/paths.yaml b/itrialspace/src/itrialspace/site/config/paths.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2403d5cf4b3aa23e4dc43291f759f0527d87ce28 --- /dev/null +++ b/itrialspace/src/itrialspace/site/config/paths.yaml @@ -0,0 +1,61 @@ +# iTrialSpace path layout — unified data directory. +# +# Copy to `configs/paths.yaml` and adjust if your layout differs. ${ITRIALSPACE_DATA_DIR} +# is expanded by itrialspace.config.settings (default: ~/.itrialspace/data). +# +# ${ITRIALSPACE_DATA_DIR}/ +# ├── raw_ct/{DATASET}/ CT scans (resampled NIfTI) +# ├── masks/{DATASET}/ +# │ ├── nodule_seg/ Individual nodule masks +# │ ├── combined_seg/ Combined patient masks +# │ ├── organ_seg/ VISTA3D organ segmentations (raw, deprecated) +# │ └── refined_seg/ Refined organ + body segmentations (used by default) +# ├── profiles/ Nodule profile CSVs +# └── meta/ Original dataset metadata CSVs +# +# ct_path values in profile CSVs are relative to raw_ct/, e.g. +# "DLCS24/DLCS_0001.nii.gz" → ${ITRIALSPACE_DATA_DIR}/raw_ct/DLCS24/DLCS_0001.nii.gz + +# ── Global base directory ────────────────────────────────────────────────── +base_dir: ${ITRIALSPACE_DATA_DIR} + +# ── Per-dataset configuration ────────────────────────────────────────────── +# Only override patterns/flags when they differ from the defaults: +# organ_seg_pattern: "{ct_id}_seg.nii.gz" +# nodule_seg_pattern: "{annotation_id}.nii.gz" +# combined_mask_pattern: "{ct_id}_mask.nii.gz" + +datasets: + + DLCS24: + profile_csv: DLCS24_nodule_profiles.csv + meta_csv: DLCS24_BMdataset_FEB192026_FIT_v1.csv + + LUNA25: + profile_csv: LUNA25_nodule_profiles.csv + meta_csv: LUNA25_dataset_FEB192026_FIT_v1.csv + + LUNA16: + profile_csv: LUNA16_nodule_profiles.csv + meta_csv: LUNA16_dataset_FEB192026_FIT_v1.csv + + LUNGx: + profile_csv: LUNGx_nodule_profiles.csv + meta_csv: LUNGx_dataset_FEB192026_FIT_v1.csv + + LNDbv4: + profile_csv: LNDbv4_nodule_profiles.csv + meta_csv: LNDBv4_dataset_FEB192026_FIT_v1.csv + + NSCLCR: + profile_csv: NSCLCR_nodule_profiles.csv + meta_csv: NSCLCR_dataset_FEB192026_FIT_v1.csv + nodule_seg_pattern: "{annotation_id}.nii.gz" + combined_mask_pattern: "{ct_id}.nii.gz" + + IMDCT: + profile_csv: IMDCT_nodule_profiles.csv + meta_csv: IMDCT_dataset_FEB192026_FIT_v1.csv + nodule_seg_use_ct_id: true + nodule_seg_pattern: "{ct_id}_seg.nii.gz" + combined_mask_pattern: "{ct_id}_seg.nii.gz" diff --git a/itrialspace/src/itrialspace/site/config/trials.yaml b/itrialspace/src/itrialspace/site/config/trials.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f1059ea91828b3a631423a6407986df9ae46f1d7 --- /dev/null +++ b/itrialspace/src/itrialspace/site/config/trials.yaml @@ -0,0 +1,157 @@ +# Published lung cancer screening trial parameters. +# Used by TrialKnowledgeBase to instantiate TrialSpec objects. +# +# Sources: +# NLST: Aberle et al. NEJM 2011; 365:395-409 +# NELSON: de Koning et al. NEJM 2020; 382:503-513 +# UKLS: Field et al. Lancet Respir Med 2016; 4:699-709 +# DANTE: Infante et al. AJRCCM 2009; 180:445-453 +# MILD: Pastorino et al. ERJ 2012; 39:1354-1362 + +trials: + + NLST: + full_name: "National Lung Screening Trial" + publication: "Aberle et al. NEJM 2011" + population: screening + n_participants: 26722 + demographics: + age_range: [55, 74] + age_mean: 61.4 + age_std: 5.0 + sex_ratio_male: 0.59 + smoking_status: ["Current", "Former"] + pack_years_min: 30 + nodule_prevalence: + any_nodule: 0.245 + malignancy_rate: 0.04 + size_distribution: + bucket_weights: + "<5mm": 0.42 + "5-10mm": 0.38 + "10-15mm": 0.11 + "15-20mm": 0.05 + "20-30mm": 0.03 + ">30mm": 0.01 + malignancy_rate_by_size: + "<5mm": 0.01 + "5-10mm": 0.024 + "10-15mm": 0.094 + "15-20mm": 0.178 + "20-30mm": 0.222 + ">30mm": 0.362 + lobe_distribution: + right_lung_upper_lobe: 0.30 + right_lung_middle_lobe: 0.08 + right_lung_lower_lobe: 0.18 + left_lung_upper_lobe: 0.28 + left_lung_lower_lobe: 0.16 + applicable_source_datasets: ["DLCS24", "LUNA25", "LUNA16", "LNDbv4"] + + NELSON: + full_name: "Nederlands-Leuvens Longkanker Screenings Onderzoek" + publication: "de Koning et al. NEJM 2020" + population: screening + n_participants: 7557 + demographics: + age_range: [50, 75] + age_mean: 58.0 + age_std: 5.5 + sex_ratio_male: 0.84 + smoking_status: ["Current", "Former"] + pack_years_min: 15 + nodule_prevalence: + any_nodule: 0.50 + malignancy_rate: 0.022 + size_distribution: + bucket_weights: + "<5mm": 0.55 + "5-10mm": 0.30 + "10-15mm": 0.09 + "15-20mm": 0.04 + ">20mm": 0.02 + malignancy_rate_by_size: + "<5mm": 0.005 + "5-10mm": 0.014 + "10-15mm": 0.063 + "15-20mm": 0.156 + ">20mm": 0.308 + lobe_distribution: + right_lung_upper_lobe: 0.30 + right_lung_middle_lobe: 0.08 + right_lung_lower_lobe: 0.18 + left_lung_upper_lobe: 0.28 + left_lung_lower_lobe: 0.16 + applicable_source_datasets: ["DLCS24", "LUNA25", "LUNA16", "LNDbv4"] + + UKLS: + full_name: "UK Lung Cancer Screening Trial" + publication: "Field et al. Lancet Respir Med 2016" + population: screening + n_participants: 1994 + demographics: + age_range: [50, 75] + sex_ratio_male: 0.52 + smoking_status: ["Current", "Former"] + pack_years_min: 20 + nodule_prevalence: + any_nodule: 0.34 + malignancy_rate: 0.017 + size_distribution: + bucket_weights: + "<5mm": 0.48 + "5-10mm": 0.35 + "10-15mm": 0.10 + "15-20mm": 0.04 + ">20mm": 0.03 + lobe_distribution: + right_lung_upper_lobe: 0.30 + right_lung_middle_lobe: 0.08 + right_lung_lower_lobe: 0.18 + left_lung_upper_lobe: 0.28 + left_lung_lower_lobe: 0.16 + applicable_source_datasets: ["DLCS24", "LUNA25", "LUNA16"] + + DANTE: + full_name: "Detection And screening of early lung Neoplasm with LDCT" + publication: "Infante et al. AJRCCM 2009" + population: screening + n_participants: 1276 + demographics: + age_range: [60, 75] + sex_ratio_male: 1.0 + smoking_status: ["Current", "Former"] + pack_years_min: 20 + nodule_prevalence: + any_nodule: 0.31 + malignancy_rate: 0.028 + size_distribution: + bucket_weights: + "<5mm": 0.40 + "5-10mm": 0.37 + "10-15mm": 0.13 + "15-20mm": 0.06 + ">20mm": 0.04 + applicable_source_datasets: ["DLCS24", "LUNA25"] + + MILD: + full_name: "Multicentric Italian Lung Detection Trial" + publication: "Pastorino et al. ERJ 2012" + population: screening + n_participants: 2376 + demographics: + age_range: [49, 75] + sex_ratio_male: 0.66 + smoking_status: ["Current", "Former"] + pack_years_min: 20 + nodule_prevalence: + any_nodule: 0.28 + malignancy_rate: 0.012 + size_distribution: + bucket_weights: + "<5mm": 0.52 + "5-10mm": 0.33 + "10-15mm": 0.09 + "15-20mm": 0.04 + ">20mm": 0.02 + applicable_source_datasets: ["DLCS24", "LUNA25", "LUNA16"] diff --git a/itrialspace/src/itrialspace/site/insertion_planner.py b/itrialspace/src/itrialspace/site/insertion_planner.py new file mode 100644 index 0000000000000000000000000000000000000000..5f89c04274da92036f9580081a596123067860ac --- /dev/null +++ b/itrialspace/src/itrialspace/site/insertion_planner.py @@ -0,0 +1,264 @@ +""" +Insertion planner — determines insertion coordinates and scaling +for each case in the synthetic cohort. + +Three modes: +- profile_faithful: use reinsertion_* columns directly from the nodule profile +- prescribed: user specifies target anatomy; planner samples from observed distributions +- randomised: uniform sample within target lobe's observed percentile ranges +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import TYPE_CHECKING, Optional + +import numpy as np +import pandas as pd + +if TYPE_CHECKING: + from itrialspace.site.spec import InsertionSpec + + +@dataclass +class InsertionPlan: + """Result of planning a single nodule insertion.""" + + insertion_coord_x: float = 0.0 + insertion_coord_y: float = 0.0 + insertion_coord_z: float = 0.0 + insertion_lobe: str = "unknown" + insertion_lobe_cc_pct: float = 0.0 + insertion_lobe_ml_pct: float = 0.0 + insertion_lobe_ap_pct: float = 0.0 + insertion_mode: str = "profile_faithful" + scale_factor: float = 1.0 + scale_factor_xyz: tuple[float, float, float] = (1.0, 1.0, 1.0) + warp_applied: str = "none" # "none" | "isotropic" | "anisotropic" + effective_diam_mm: float = 0.0 + feasible: bool = True + infeasibility_reason: str = "" + + +class InsertionPlanner: + """Plans insertion coordinates and scaling for synthetic nodule placement.""" + + def __init__(self, index_df: pd.DataFrame): + """ + Args: + index_df: The NoduleIndex DataFrame (used to compute lobe + statistics for prescribed/randomised modes). + """ + self._df = index_df + self._lobe_stats = self._compute_lobe_ranges() + + def plan( + self, + nodule_row: pd.Series, + mode: str, + target_diam_mm: Optional[float] = None, + insertion_spec: Optional["InsertionSpec"] = None, + rng: Optional[np.random.Generator] = None, + ) -> InsertionPlan: + """Dispatch to mode-specific planner. + + Args: + nodule_row: Row from NoduleIndex DataFrame (the donor nodule). + mode: "profile_faithful", "prescribed", or "randomised". + target_diam_mm: Desired diameter (triggers scaling if different from donor). + insertion_spec: InsertionSpec for prescribed/randomised modes. + rng: Random generator (required for prescribed/randomised). + + Returns: + InsertionPlan with coordinates, scaling, and feasibility. + """ + if mode == "profile_faithful": + plan = self._plan_profile_faithful(nodule_row) + elif mode == "prescribed": + if rng is None: + raise ValueError("rng required for prescribed mode") + plan = self._plan_prescribed(nodule_row, insertion_spec, rng) + elif mode == "randomised": + if rng is None: + raise ValueError("rng required for randomised mode") + plan = self._plan_randomised(nodule_row, insertion_spec, rng) + else: + raise ValueError(f"Unknown insertion mode: {mode}") + + # Apply scaling if target diameter specified + if target_diam_mm is not None: + donor_diam = float(nodule_row.get("reinsertion_nodule_diam_mm", 0)) + if donor_diam > 0: + sf, warp = self._compute_scale(donor_diam, target_diam_mm, insertion_spec) + plan.scale_factor = sf + plan.warp_applied = warp + plan.effective_diam_mm = donor_diam * sf + else: + plan.effective_diam_mm = target_diam_mm + else: + plan.effective_diam_mm = float(nodule_row.get("reinsertion_nodule_diam_mm", 0)) + + plan.insertion_mode = mode + return plan + + # ── Mode implementations ────────────────────────────────────────────────── + + def _plan_profile_faithful(self, row: pd.Series) -> InsertionPlan: + """Use reinsertion_* columns directly.""" + return InsertionPlan( + insertion_coord_x=float(row.get("coordX", 0)), + insertion_coord_y=float(row.get("coordY", 0)), + insertion_coord_z=float(row.get("coordZ", 0)), + insertion_lobe=str(row.get("reinsertion_lobe", "unknown")), + insertion_lobe_cc_pct=float(row.get("reinsertion_lobe_cc_pct", 0)), + insertion_lobe_ml_pct=float(row.get("reinsertion_lobe_ml_pct", 0)), + insertion_lobe_ap_pct=float(row.get("reinsertion_lobe_ap_pct", 0)), + ) + + def _plan_prescribed( + self, + row: pd.Series, + spec: Optional["InsertionSpec"], + rng: np.random.Generator, + ) -> InsertionPlan: + """Sample position within prescribed lobe/zone from observed distributions.""" + from itrialspace.site.spec import InsertionSpec + + spec = spec or InsertionSpec() + target_lobe = spec.target_lobe or str(row.get("reinsertion_lobe", "unknown")) + + stats = self._lobe_stats.get(target_lobe) + if stats is None: + return InsertionPlan( + insertion_lobe=target_lobe, + feasible=False, + infeasibility_reason=f"No statistics for lobe '{target_lobe}'", + ) + + cc = rng.uniform(stats["cc_p10"], stats["cc_p90"]) + ml = rng.uniform(stats["ml_p10"], stats["ml_p90"]) + ap = rng.uniform(stats["ap_p10"], stats["ap_p90"]) + + return InsertionPlan( + insertion_lobe=target_lobe, + insertion_lobe_cc_pct=cc, + insertion_lobe_ml_pct=ml, + insertion_lobe_ap_pct=ap, + ) + + def _plan_randomised( + self, + row: pd.Series, + spec: Optional["InsertionSpec"], + rng: np.random.Generator, + ) -> InsertionPlan: + """Uniform sample within target lobe's observed ranges.""" + from itrialspace.site.spec import InsertionSpec + + spec = spec or InsertionSpec() + target_lobe = spec.target_lobe or str(row.get("reinsertion_lobe", "unknown")) + + stats = self._lobe_stats.get(target_lobe) + if stats is None: + return InsertionPlan( + insertion_lobe=target_lobe, + feasible=False, + infeasibility_reason=f"No statistics for lobe '{target_lobe}'", + ) + + cc = rng.uniform(stats["cc_min"], stats["cc_max"]) + ml = rng.uniform(stats["ml_min"], stats["ml_max"]) + ap = rng.uniform(stats["ap_min"], stats["ap_max"]) + + return InsertionPlan( + insertion_lobe=target_lobe, + insertion_lobe_cc_pct=cc, + insertion_lobe_ml_pct=ml, + insertion_lobe_ap_pct=ap, + ) + + # ── Scaling ─────────────────────────────────────────────────────────────── + + @staticmethod + def _compute_scale( + donor_diam: float, + target_diam: float, + spec: Optional["InsertionSpec"], + ) -> tuple[float, str]: + """Compute scale factor and warp type. + + Priority: + 1. Constrained match (within tolerance) → no warp + 2. Isotropic scale → uniform resize + 3. Anisotropic warp → per-axis stretch (opt-in) + + Returns: + (scale_factor, warp_type) where warp_type is "none"|"isotropic"|"anisotropic" + """ + from itrialspace.site.spec import InsertionSpec + + spec = spec or InsertionSpec() + if donor_diam <= 0: + return (1.0, "none") + + ratio = target_diam / donor_diam + + # Within tolerance → no scaling needed + if abs(ratio - 1.0) <= spec.scale_tolerance: + return (1.0, "none") + + # Isotropic scale + if spec.allow_isotropic_scale and ratio <= spec.max_scale_factor: + return (ratio, "isotropic") + + # Anisotropic warp + if spec.allow_anisotropic_warp and ratio <= spec.max_scale_factor: + return (ratio, "anisotropic") + + # Scale factor exceeds maximum — clamp + clamped = min(ratio, spec.max_scale_factor) + warp = "isotropic" if spec.allow_isotropic_scale else "anisotropic" + return (clamped, warp) + + # ── Lobe statistics ─────────────────────────────────────────────────────── + + def _compute_lobe_ranges(self) -> dict[str, dict]: + """Compute per-lobe position statistics from the index. + + Uses reinsertion_* columns (100% complete) to build + min/max/percentile ranges for each lobe. + """ + from itrialspace.core.schema import LOBE_NAMES + + stats: dict[str, dict] = {} + for lobe in LOBE_NAMES: + mask = self._df["reinsertion_lobe"] == lobe + sub = self._df.loc[mask] + if len(sub) < 5: + continue + + cc = sub["reinsertion_lobe_cc_pct"].dropna() + ml = sub["reinsertion_lobe_ml_pct"].dropna() + ap = sub["reinsertion_lobe_ap_pct"].dropna() + + if len(cc) < 5: + continue + + stats[lobe] = { + "n": len(sub), + "cc_min": float(cc.min()), + "cc_max": float(cc.max()), + "cc_p10": float(cc.quantile(0.10)), + "cc_p90": float(cc.quantile(0.90)), + "cc_median": float(cc.median()), + "ml_min": float(ml.min()), + "ml_max": float(ml.max()), + "ml_p10": float(ml.quantile(0.10)), + "ml_p90": float(ml.quantile(0.90)), + "ap_min": float(ap.min()), + "ap_max": float(ap.max()), + "ap_p10": float(ap.quantile(0.10)), + "ap_p90": float(ap.quantile(0.90)), + } + + return stats diff --git a/itrialspace/src/itrialspace/site/knowledge_base.py b/itrialspace/src/itrialspace/site/knowledge_base.py new file mode 100644 index 0000000000000000000000000000000000000000..432ad481c029f4b2c25540fa92139b288f98cbbd --- /dev/null +++ b/itrialspace/src/itrialspace/site/knowledge_base.py @@ -0,0 +1,177 @@ +""" +Clinical trial knowledge base — loads published trial parameters +from trials.yaml and converts them into TrialSpec objects. +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Optional + +import pandas as pd + +try: + import yaml +except ImportError: + yaml = None # type: ignore[assignment] + +from itrialspace.site.spec import ( + DemographicSpec, + NoduleSpec, + SizeDistribution, + TrialSpec, +) + +_DEFAULT_YAML = Path(__file__).parent / "config" / "trials.yaml" + + +class TrialKnowledgeBase: + """Loads published trial parameters and produces TrialSpec objects.""" + + def __init__(self, yaml_path: Optional[str] = None): + if yaml is None: + raise ImportError("pyyaml is required: pip install pyyaml") + path = Path(yaml_path) if yaml_path else _DEFAULT_YAML + with open(path) as f: + data = yaml.safe_load(f) + self._trials: dict[str, dict] = data.get("trials", {}) + + @property + def available_trials(self) -> list[str]: + return list(self._trials.keys()) + + def get_template(self, trial_name: str) -> dict: + if trial_name not in self._trials: + raise KeyError(f"Unknown trial '{trial_name}'. " f"Available: {self.available_trials}") + return self._trials[trial_name] + + def to_trial_spec( + self, + trial_name: str, + n_cases: int = 500, + cohort_mode: str = "synthetic", + insertion_mode: str = "profile_faithful", + overrides: Optional[dict] = None, + seed: int = 42, + ) -> TrialSpec: + """Convert a published trial template into a TrialSpec. + + Args: + trial_name: Template name (e.g. "NLST", "NELSON"). + n_cases: Number of cases in the cohort. + cohort_mode: "native", "matched", or "synthetic". + insertion_mode: "profile_faithful", "prescribed", or "randomised". + overrides: Dict to patch any TrialSpec field after construction. + seed: Random seed for reproducibility. + + Returns: + Fully populated TrialSpec. + """ + tmpl = self.get_template(trial_name) + + # Demographics + demo = None + if "demographics" in tmpl: + d = tmpl["demographics"] + age_range = tuple(d["age_range"]) if "age_range" in d else None + demo = DemographicSpec( + age_range=age_range, + age_mean=d.get("age_mean"), + age_std=d.get("age_std"), + sex_ratio_male=d.get("sex_ratio_male"), + smoking_status=d.get("smoking_status"), + pack_years_min=d.get("pack_years_min"), + ) + + # Size distribution + size_dist = None + if "size_distribution" in tmpl: + sd = tmpl["size_distribution"] + size_dist = SizeDistribution( + bucket_weights=sd.get("bucket_weights"), + ) + + # Nodule spec + nodule_spec = NoduleSpec(size_distribution=size_dist) + + # Prevalence + mal_prev = None + if "nodule_prevalence" in tmpl: + mal_prev = tmpl["nodule_prevalence"].get("malignancy_rate") + + # Source datasets + source_ds = tmpl.get("applicable_source_datasets") + + spec = TrialSpec( + trial_name=f"{trial_name}_cohort", + trial_template=trial_name, + description=f"Cohort based on {tmpl.get('full_name', trial_name)} " + f"({tmpl.get('publication', 'N/A')})", + seed=seed, + n_cases=n_cases, + cohort_mode=cohort_mode, + demographics=demo, + nodule_spec=nodule_spec, + malignancy_prevalence=mal_prev, + source_datasets=source_ds, + insertion_mode=insertion_mode, + ) + + # Apply overrides + if overrides: + for k, v in overrides.items(): + if hasattr(spec, k): + setattr(spec, k, v) + + return spec + + def describe(self, trial_name: str) -> str: + """Human-readable summary of a trial template.""" + tmpl = self.get_template(trial_name) + lines = [ + f"=== {tmpl.get('full_name', trial_name)} ===", + f"Publication: {tmpl.get('publication', 'N/A')}", + f"Population: {tmpl.get('population', 'N/A')}", + f"N participants: {tmpl.get('n_participants', 'N/A')}", + ] + if "demographics" in tmpl: + d = tmpl["demographics"] + lines.append(f"Age range: {d.get('age_range', 'N/A')}") + lines.append(f"Male ratio: {d.get('sex_ratio_male', 'N/A')}") + lines.append(f"Min pack-years: {d.get('pack_years_min', 'N/A')}") + if "nodule_prevalence" in tmpl: + np_ = tmpl["nodule_prevalence"] + lines.append(f"Any nodule prevalence: {np_.get('any_nodule', 'N/A')}") + lines.append(f"Malignancy rate: {np_.get('malignancy_rate', 'N/A')}") + if "size_distribution" in tmpl: + sd = tmpl["size_distribution"] + if "bucket_weights" in sd: + lines.append("Size distribution:") + for bucket, w in sd["bucket_weights"].items(): + lines.append(f" {bucket}: {w:.0%}") + lines.append(f"Source datasets: {tmpl.get('applicable_source_datasets', 'N/A')}") + return "\n".join(lines) + + def compare(self, trial_names: Optional[list[str]] = None) -> pd.DataFrame: + """Side-by-side comparison table of trial templates.""" + if trial_names is None: + trial_names = self.available_trials + + rows = [] + for name in trial_names: + tmpl = self.get_template(name) + demo = tmpl.get("demographics", {}) + prev = tmpl.get("nodule_prevalence", {}) + row = { + "trial": name, + "population": tmpl.get("population"), + "n_participants": tmpl.get("n_participants"), + "age_range": str(demo.get("age_range", "")), + "male_ratio": demo.get("sex_ratio_male"), + "pack_years_min": demo.get("pack_years_min"), + "nodule_prevalence": prev.get("any_nodule"), + "malignancy_rate": prev.get("malignancy_rate"), + } + rows.append(row) + + return pd.DataFrame(rows).set_index("trial") diff --git a/itrialspace/src/itrialspace/site/manifest.py b/itrialspace/src/itrialspace/site/manifest.py new file mode 100644 index 0000000000000000000000000000000000000000..9df91edceddc844dafa3048cf5989ac95f226d57 --- /dev/null +++ b/itrialspace/src/itrialspace/site/manifest.py @@ -0,0 +1,345 @@ +""" +CohortManifest — the final output of iTrialSpace. + +A structured manifest describing every case in a synthetic trial +cohort. Wraps a DataFrame with export, audit, and path verification. +""" + +from __future__ import annotations + +import json +import os + +import pandas as pd + +from itrialspace.site.spec import TrialSpec + +# ── Manifest column schema ──────────────────────────────────────────────────── + +MANIFEST_COLS = [ + # Case identity + "case_id", + "nodule_idx", + "is_primary_nodule", + "n_nodules_in_case", + "companion_group_id", + "trial_name", + "trial_template", + "bootstrap_id", + # Host CT + "host_patient_id", + "host_dataset", + "host_ct_path", + "host_organ_seg_path", + # Donor nodule + "donor_patient_id", + "donor_annotation_id", + "donor_dataset", + "donor_nodule_mask_path", + "donor_ct_path", + "donor_refined_seg_path", + # Insertion parameters + "insertion_coord_x", + "insertion_coord_y", + "insertion_coord_z", + "insertion_lobe", + "insertion_lobe_cc_pct", + "insertion_lobe_ml_pct", + "insertion_lobe_ap_pct", + "insertion_mode", + # Nodule characteristics + "nodule_diam_mm", + "effective_diam_mm", + "scale_factor", + "warp_applied", + "label", + # Anatomy + "nodule_lobe_name", + "nodule_lung_side", + "nodule_lung_zone", + "nodule_central_peripheral", + "pleural_distance_mm", + # Demographics + "patient_age", + "patient_sex", + "smoking_status", + "pack_years", + # Cohort metadata + "cohort_mode", + "size_bucket", + "population_type", + "label_source", +] + +# Additional columns for digital twin isolation manifests. +# These are appended to MANIFEST_COLS when the mode is digital_twin_isolation. +ISOLATION_MANIFEST_COLS = MANIFEST_COLS + [ + "mode", + "target_annotation_id", + "target_nodule_mask_path", + "target_diameter_mm", + "target_label", + "target_lobe", + "target_side", + "target_zone", + "host_n_nodules", + "isolation_case_index", +] + +# Additional columns for digital twin complete manifests. +# One row per nodule, all nodules for the same patient share a case_id. +COMPLETE_MANIFEST_COLS = MANIFEST_COLS + [ + "mode", + "host_n_nodules", + "annotation_ids", + "diameters_mm", + "labels", + "lobes", + "sides", + "zones", +] + +# Additional columns for digital twin cross manifests. +# Explicit host/donor provenance with placement and pairing metadata. +CROSS_MANIFEST_COLS = MANIFEST_COLS + [ + "mode", + "donor_transfer_mode", + "pairing_policy", + "placement_strategy", + "cross_case_group_id", +] + + +class CohortManifest: + """Structured manifest for a synthetic imaging trial cohort.""" + + def __init__(self, df: pd.DataFrame, spec: TrialSpec): + self._df = df + self._spec = spec + + @property + def df(self) -> pd.DataFrame: + return self._df + + @property + def spec(self) -> TrialSpec: + return self._spec + + def __len__(self) -> int: + return len(self._df) + + def __repr__(self) -> str: + n_mal = (self._df["label"] == 1).sum() + n_ben = (self._df["label"] == 0).sum() + # Show total rows vs unique cases when companions present + if "is_primary_nodule" in self._df.columns: + n_primary = int(self._df["is_primary_nodule"].sum()) + if n_primary < len(self): + return ( + f"CohortManifest('{self._spec.trial_name}' | " + f"{n_primary} cases ({len(self)} total rows) | " + f"{n_mal} malignant, {n_ben} benign)" + ) + return ( + f"CohortManifest('{self._spec.trial_name}' | " + f"{len(self)} cases | {n_mal} malignant, {n_ben} benign)" + ) + + # ── Export ───────────────────────────────────────────────────────────────── + + def to_csv(self, path: str) -> None: + os.makedirs(os.path.dirname(path) or ".", exist_ok=True) + self._df.to_csv(path, index=False) + + def to_json(self, path: str) -> None: + os.makedirs(os.path.dirname(path) or ".", exist_ok=True) + records = self._df.to_dict(orient="records") + with open(path, "w") as f: + json.dump( + { + "trial_name": self._spec.trial_name, + "trial_template": self._spec.trial_template, + "n_cases": len(self), + "cohort_mode": self._spec.cohort_mode, + "seed": self._spec.seed, + "cases": records, + }, + f, + indent=2, + default=str, + ) + + def to_dataframe(self) -> pd.DataFrame: + return self._df.copy() + + # ── Summary ─────────────────────────────────────────────────────────────── + + def summary(self) -> dict: + """Summary statistics of the manifest.""" + df = self._df + s: dict = { + "trial_name": self._spec.trial_name, + "n_cases": len(df), + "cohort_mode": self._spec.cohort_mode, + } + + if "label" in df.columns: + labels = df["label"].dropna() + s["n_malignant"] = int((labels == 1).sum()) + s["n_benign"] = int((labels == 0).sum()) + s["n_unlabelled"] = int(df["label"].isna().sum()) + if len(labels) > 0: + s["malignancy_rate"] = round(float((labels == 1).mean()), 4) + + if "size_bucket" in df.columns: + s["size_distribution"] = df["size_bucket"].value_counts().to_dict() + + if "insertion_lobe" in df.columns: + s["lobe_distribution"] = df["insertion_lobe"].value_counts().to_dict() + + if "donor_dataset" in df.columns: + s["donor_datasets"] = df["donor_dataset"].value_counts().to_dict() + + if "host_dataset" in df.columns: + s["host_datasets"] = df["host_dataset"].value_counts().to_dict() + + if "warp_applied" in df.columns: + s["warp_distribution"] = df["warp_applied"].value_counts().to_dict() + + # Multi-nodule statistics + if "is_primary_nodule" in df.columns: + n_primary = int(df["is_primary_nodule"].sum()) + n_companion = len(df) - n_primary + if n_companion > 0: + s["n_primary_cases"] = n_primary + s["n_companion_insertions"] = n_companion + s["total_manifest_rows"] = len(df) + # Count cases with >1 nodule + if "n_nodules_in_case" in df.columns: + primary_rows = df[df["is_primary_nodule"] == True] + s["multi_nodule_cases"] = int((primary_rows["n_nodules_in_case"] > 1).sum()) + + return s + + def audit(self) -> pd.DataFrame: + """Compare actual manifest statistics to TrialSpec targets. + + Returns: + DataFrame with columns: metric, target, actual, deviation. + """ + rows = [] + spec = self._spec + df = self._df + + # Prevalence + if spec.malignancy_prevalence is not None and "label" in df.columns: + labels = df["label"].dropna() + actual_prev = float((labels == 1).mean()) if len(labels) > 0 else 0.0 + rows.append( + { + "metric": "malignancy_prevalence", + "target": spec.malignancy_prevalence, + "actual": round(actual_prev, 4), + "deviation": round(actual_prev - spec.malignancy_prevalence, 4), + } + ) + + # N cases + rows.append( + { + "metric": "n_cases", + "target": spec.n_cases, + "actual": len(df), + "deviation": len(df) - spec.n_cases, + } + ) + + # Size distribution + if ( + spec.nodule_spec + and spec.nodule_spec.size_distribution + and spec.nodule_spec.size_distribution.bucket_weights + and "size_bucket" in df.columns + ): + actual_dist = df["size_bucket"].value_counts(normalize=True) + for bucket, target_w in spec.nodule_spec.size_distribution.bucket_weights.items(): + actual_w = actual_dist.get(bucket, 0.0) + rows.append( + { + "metric": f"size_{bucket}", + "target": round(target_w, 3), + "actual": round(float(actual_w), 3), + "deviation": round(float(actual_w) - target_w, 3), + } + ) + + # Companion nodule audit + if "is_primary_nodule" in df.columns: + n_companion = int((df["is_primary_nodule"] == False).sum()) + if n_companion > 0: + rows.append( + { + "metric": "companion_nodules_added", + "target": "N/A", + "actual": n_companion, + "deviation": 0, + } + ) + + return pd.DataFrame(rows) + + # ── Path verification ───────────────────────────────────────────────────── + + def verify_paths(self) -> pd.DataFrame: + """Check which files actually exist on disk. + + Returns: + DataFrame of missing files with columns: case_id, path_type, path. + """ + path_cols = [ + "host_ct_path", + "host_organ_seg_path", + "donor_nodule_mask_path", + "donor_ct_path", + ] + missing = [] + for _, row in self._df.iterrows(): + for col in path_cols: + if col in row and pd.notna(row[col]): + path = str(row[col]) + if not os.path.exists(path): + missing.append( + { + "case_id": row.get("case_id", ""), + "path_type": col, + "path": path, + } + ) + return pd.DataFrame(missing) + + # ── Subsetting ──────────────────────────────────────────────────────────── + + def malignant_cases(self) -> CohortManifest: + return CohortManifest( + self._df[self._df["label"] == 1].reset_index(drop=True), + self._spec, + ) + + def benign_cases(self) -> CohortManifest: + return CohortManifest( + self._df[self._df["label"] == 0].reset_index(drop=True), + self._spec, + ) + + def filter_lobe(self, lobe: str) -> CohortManifest: + return CohortManifest( + self._df[self._df["insertion_lobe"] == lobe].reset_index(drop=True), + self._spec, + ) + + def filter_size(self, min_mm: float, max_mm: float) -> CohortManifest: + mask = (self._df["effective_diam_mm"] >= min_mm) & (self._df["effective_diam_mm"] <= max_mm) + return CohortManifest( + self._df[mask].reset_index(drop=True), + self._spec, + ) diff --git a/itrialspace/src/itrialspace/site/path_resolver.py b/itrialspace/src/itrialspace/site/path_resolver.py new file mode 100644 index 0000000000000000000000000000000000000000..56f1c854299bb1cc641ea6de921903aebbca86a3 --- /dev/null +++ b/itrialspace/src/itrialspace/site/path_resolver.py @@ -0,0 +1,182 @@ +""" +Path resolution — turns relative CSV paths and annotation IDs +into absolute server paths for CT scans, nodule masks, organ +segmentations, and refined segmentations. + +Configuration is loaded from config/paths.yaml. The unified +iTrialSpace layout uses a single base_dir with standardised +subdirectories: + + base_dir/ + ├── raw_ct/{DATASET}/ CT scans + ├── masks/{DATASET}/ + │ ├── nodule_seg/ Individual nodule masks + │ ├── combined_seg/ Combined patient masks + │ ├── organ_seg/ VISTA3D organ segmentations (raw, deprecated) + │ └── refined_seg/ Refined organ + body segmentations (default) + ├── profiles/ Nodule profile CSVs + └── meta/ Dataset metadata CSVs +""" + +from __future__ import annotations + +import os +from pathlib import Path +from typing import Optional + +import pandas as pd + +from itrialspace.config import settings + +_DEFAULT_PATHS_YAML = Path(__file__).parent / "config" / "paths.yaml" + + +class PathResolver: + """Config-driven path resolver for iTrialSpace datasets. + + Loads per-dataset path layouts from a YAML config file. + All paths resolve relative to a single base_dir. + """ + + def __init__( + self, + config_path: Optional[str] = None, + base_dir: Optional[str] = None, + ): + """ + Args: + config_path: Path to paths.yaml. Defaults to bundled config. + base_dir: Override the global base_dir from config. + """ + # Resolve the config file: explicit arg → top-level configs/ → package default. + if config_path: + path = Path(config_path) + else: + path = settings.find_config("paths.yaml", package_default=_DEFAULT_PATHS_YAML) + + # load_yaml expands ${ITRIALSPACE_DATA_DIR} and other ${VAR} placeholders. + cfg = settings.load_yaml(path) + + self._base_dir = base_dir or cfg.get("base_dir") or str(settings.data_dir()) + self._datasets: dict[str, dict] = cfg.get("datasets", {}) + + @property + def base_dir(self) -> str: + return self._base_dir + + @property + def available_datasets(self) -> list[str]: + return list(self._datasets.keys()) + + def _get_ds(self, dataset: str) -> dict: + if dataset not in self._datasets: + raise KeyError( + f"Unknown dataset '{dataset}'. " + f"Available: {self.available_datasets}. " + f"Add it to config/paths.yaml." + ) + return self._datasets[dataset] + + # ── Individual resolvers ────────────────────────────────────────────────── + + def resolve_ct_path(self, dataset: str, ct_path_relative: str) -> str: + """Resolve ct_path column value to an absolute path. + + ct_path_relative is e.g. "DLCS24/DLCS_0001.nii.gz", + resolved as base_dir/raw_ct/{ct_path_relative}. + """ + return os.path.join(self._base_dir, "raw_ct", ct_path_relative) + + def resolve_nodule_mask_path( + self, + dataset: str, + annotation_id: str, + ct_id: Optional[str] = None, + ) -> str: + """Individual nodule mask. + + Some datasets (e.g. IMDCT) have one nodule per CT and store masks + keyed by ct_id rather than annotation_id. Set ``nodule_seg_use_ct_id: true`` + in the dataset config to activate this. + """ + ds = self._get_ds(dataset) + pattern = ds.get("nodule_seg_pattern", "{annotation_id}.nii.gz") + if ds.get("nodule_seg_use_ct_id", False) and ct_id is not None: + filename = pattern.format(ct_id=ct_id, annotation_id=annotation_id) + else: + filename = pattern.format(annotation_id=annotation_id) + return os.path.join(self._base_dir, "masks", dataset, "nodule_seg", filename) + + def resolve_organ_seg_path(self, dataset: str, ct_id: str) -> str: + """Organ + body segmentation (refined_seg preferred over organ_seg).""" + ds = self._get_ds(dataset) + pattern = ds.get("organ_seg_pattern", "{ct_id}_seg.nii.gz") + filename = pattern.format(ct_id=ct_id) + return os.path.join(self._base_dir, "masks", dataset, "refined_seg", filename) + + def resolve_combined_mask_path(self, dataset: str, ct_id: str) -> str: + """Combined (all nodules in one file) segmentation mask.""" + ds = self._get_ds(dataset) + pattern = ds.get("combined_mask_pattern", "{ct_id}_mask.nii.gz") + filename = pattern.format(ct_id=ct_id) + return os.path.join(self._base_dir, "masks", dataset, "combined_seg", filename) + + def resolve_refined_seg_path(self, dataset: str, ct_id: str) -> str: + """Refined segmentation.""" + return os.path.join( + self._base_dir, + "masks", + dataset, + "refined_seg", + f"{ct_id}_seg.nii.gz", + ) + + def resolve_profile_csv_path(self, dataset: str) -> str: + """Nodule profile CSV for a dataset.""" + ds = self._get_ds(dataset) + csv_name = ds.get("profile_csv", f"{dataset}_nodule_profiles.csv") + return os.path.join(self._base_dir, "profiles", csv_name) + + def resolve_meta_csv_path(self, dataset: str) -> str: + """Dataset metadata CSV.""" + ds = self._get_ds(dataset) + csv_name = ds.get("meta_csv", "") + if not csv_name: + return "" + return os.path.join(self._base_dir, "meta", csv_name) + + # ── Batch resolver ──────────────────────────────────────────────────────── + + @staticmethod + def extract_ct_id(ct_path: str) -> str: + """Extract ct_id from a ct_path for organ seg / mask lookup. + + E.g. "DLCS24/DLCS_0001.nii.gz" → "DLCS_0001" + "LUNA25/1.2.840...nii.gz" → "1.2.840..." + """ + basename = os.path.basename(ct_path) + if basename.endswith(".nii.gz"): + return basename[:-7] + if basename.endswith(".nii"): + return basename[:-4] + return basename + + def resolve_all_paths(self, row: pd.Series) -> dict[str, str]: + """Resolve all paths from a NoduleIndex DataFrame row. + + Returns dict with keys: + ct_path, nodule_mask_path, organ_seg_path, + combined_mask_path, refined_seg_path + """ + dataset = row["dataset"] + ct_rel = row["ct_path"] + annotation_id = row["annotation_id"] + ct_id = self.extract_ct_id(ct_rel) + + return { + "ct_path": self.resolve_ct_path(dataset, ct_rel), + "nodule_mask_path": self.resolve_nodule_mask_path(dataset, annotation_id, ct_id=ct_id), + "organ_seg_path": self.resolve_organ_seg_path(dataset, ct_id), + "combined_mask_path": self.resolve_combined_mask_path(dataset, ct_id), + "refined_seg_path": self.resolve_refined_seg_path(dataset, ct_id), + } diff --git a/itrialspace/src/itrialspace/site/sampling.py b/itrialspace/src/itrialspace/site/sampling.py new file mode 100644 index 0000000000000000000000000000000000000000..cb1f314db39bb008464770b57a3aac082263688e --- /dev/null +++ b/itrialspace/src/itrialspace/site/sampling.py @@ -0,0 +1,142 @@ +""" +Distribution sampling utilities — stateless helper functions for +sampling nodule sizes, labels, and lobe assignments from trial +specifications. +""" + +from __future__ import annotations + +import numpy as np + +from itrialspace.site.spec import SIZE_BUCKET_ALIASES, SIZE_BUCKET_RANGES + + +class DistributionSampler: + """Stateless sampling helpers for trial cohort generation.""" + + @staticmethod + def sample_size_from_buckets( + bucket_weights: dict[str, float], + n: int, + rng: np.random.Generator, + ) -> np.ndarray: + """Sample n diameters from weighted size buckets. + + Within each bucket, diameters are uniformly distributed + over the bucket's range. + + Returns: + Array of float diameters in mm, shape (n,). + """ + buckets = list(bucket_weights.keys()) + weights = np.array([bucket_weights[b] for b in buckets], dtype=float) + weights /= weights.sum() + + bucket_indices = rng.choice(len(buckets), size=n, p=weights) + diameters = np.empty(n, dtype=float) + + for i, idx in enumerate(bucket_indices): + b = buckets[idx] + rng_lohi = SIZE_BUCKET_RANGES.get(b) or SIZE_BUCKET_ALIASES.get(b) + if rng_lohi is None: + raise KeyError( + f"Unknown size bucket {b!r}; valid: " + f"{list(SIZE_BUCKET_RANGES) + list(SIZE_BUCKET_ALIASES)}" + ) + lo, hi = rng_lohi + diameters[i] = rng.uniform(lo, hi) + + return diameters + + @staticmethod + def sample_size_lognormal( + n: int, + mean_log_mm: float, + std_log_mm: float, + min_mm: float, + max_mm: float, + rng: np.random.Generator, + ) -> np.ndarray: + """Sample n diameters from a truncated log-normal distribution.""" + samples = [] + while len(samples) < n: + batch = rng.lognormal(mean_log_mm, std_log_mm, size=n * 2) + valid = batch[(batch >= min_mm) & (batch <= max_mm)] + samples.extend(valid.tolist()) + return np.array(samples[:n]) + + @staticmethod + def sample_labels( + n: int, + malignancy_rate: float, + rng: np.random.Generator, + ) -> np.ndarray: + """Sample n binary labels at given malignancy rate. + + Returns: + Array of int (0 or 1), shape (n,). + """ + return rng.binomial(1, malignancy_rate, size=n).astype(int) + + @staticmethod + def sample_labels_by_size( + sizes: np.ndarray, + rate_by_bucket: dict[str, float], + rng: np.random.Generator, + ) -> np.ndarray: + """Assign labels conditioned on nodule size. + + Uses per-bucket malignancy rates from clinical trial data. + More realistic than a flat prevalence. + """ + labels = np.zeros(len(sizes), dtype=int) + for i, d in enumerate(sizes): + bucket = _diameter_to_bucket(d) + rate = rate_by_bucket.get(bucket, 0.0) + labels[i] = rng.binomial(1, rate) + return labels + + @staticmethod + def sample_lobe_distribution( + lobe_weights: dict[str, float], + n: int, + rng: np.random.Generator, + ) -> np.ndarray: + """Sample n lobe assignments from weighted distribution. + + Returns: + Array of str lobe names, shape (n,). + """ + lobes = list(lobe_weights.keys()) + weights = np.array([lobe_weights[l] for l in lobes], dtype=float) + weights /= weights.sum() + indices = rng.choice(len(lobes), size=n, p=weights) + return np.array([lobes[i] for i in indices]) + + @staticmethod + def assign_no_nodule_cases( + n: int, + no_nodule_fraction: float, + rng: np.random.Generator, + ) -> np.ndarray: + """Return boolean mask where True = no nodule (clean case). + + Returns: + Array of bool, shape (n,). + """ + return rng.random(n) < no_nodule_fraction + + +def _diameter_to_bucket(d: float) -> str: + """Map a diameter in mm to its size bucket string.""" + if d < 5: + return "<5mm" + if d < 10: + return "5-10mm" + if d < 15: + return "10-15mm" + if d < 20: + return "15-20mm" + if d < 30: + return "20-30mm" + return ">30mm" diff --git a/itrialspace/src/itrialspace/site/spec.py b/itrialspace/src/itrialspace/site/spec.py new file mode 100644 index 0000000000000000000000000000000000000000..a0866acb59a065622fac2fe8bc4ed05dc41d1b54 --- /dev/null +++ b/itrialspace/src/itrialspace/site/spec.py @@ -0,0 +1,382 @@ +""" +Trial specification dataclasses — pure data, no logic. + +These define what a synthetic imaging trial looks like: +demographics, nodule characteristics, prevalence, insertion mode, etc. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Optional + +from itrialspace.config import settings + + +def _default_base_dir() -> str: + """Resolve the data root at instantiation time (env-portable).""" + return str(settings.data_dir()) + + +# Datasets that have been permanently removed and must be rejected at all entry points. +_REMOVED_DATASETS = {"NLST3D"} + + +def validate_dataset_names(names: list[str] | None) -> None: + """Raise ValueError if any removed dataset is specified.""" + if names is None: + return + bad = _REMOVED_DATASETS.intersection(names) + if bad: + raise ValueError( + f"Dataset(s) {bad} removed due to quality issues and cannot be used. " + f"Remove them from your dataset list." + ) + + +# ── Size distribution ──────────────────────────────────────────────────────── + +SIZE_BUCKETS = ["<5mm", "5-10mm", "10-15mm", "15-20mm", "20-30mm", ">30mm"] + +SIZE_BUCKET_RANGES: dict[str, tuple[float, float]] = { + "<5mm": (1.0, 5.0), + "5-10mm": (5.0, 10.0), + "10-15mm": (10.0, 15.0), + "15-20mm": (15.0, 20.0), + "20-30mm": (20.0, 30.0), + ">30mm": (30.0, 60.0), +} + +# Open-ended aggregate buckets used by some published trial templates (UKLS, DANTE, +# NELSON, MILD) in their reported size distributions. These are NOT part of the +# canonical SIZE_BUCKETS; the sampler resolves them via SIZE_BUCKET_RANGES first, +# then these aliases. +SIZE_BUCKET_ALIASES: dict[str, tuple[float, float]] = { + ">20mm": (20.0, 60.0), # i.e. >=20mm, up to the max nodule diameter +} + + +@dataclass +class SizeDistribution: + """How to sample nodule diameters. + + Either discrete bucket weights or continuous log-normal parameters. + Exactly one mode should be specified. + """ + + # Discrete: keys from SIZE_BUCKETS, weights summing to ~1.0 + bucket_weights: Optional[dict[str, float]] = None + + # Continuous: truncated log-normal + mean_log_mm: Optional[float] = None + std_log_mm: Optional[float] = None + min_mm: float = 3.0 + max_mm: float = 60.0 + + +# ── Demographics ───────────────────────────────────────────────────────────── + + +@dataclass +class DemographicSpec: + """Demographics constraints (best-effort; only DLCS24/LUNA25 have these).""" + + age_range: Optional[tuple[int, int]] = None + age_mean: Optional[float] = None + age_std: Optional[float] = None + sex_ratio_male: Optional[float] = None # 0.0–1.0 + smoking_status: Optional[list[str]] = None # ["Current", "Former", ...] + pack_years_min: Optional[float] = None + + +# ── Nodule specification ───────────────────────────────────────────────────── + +HISTOPATH_DATASETS = ["DLCS24", "LUNA25", "NSCLCR", "IMDCT", "LUNGx"] +RADIOLOGY_DATASETS = ["LUNA16", "LNDbv4"] +SCREENING_DATASETS = ["DLCS24", "LUNA16", "LUNA25", "LNDbv4"] +DIAGNOSTIC_DATASETS = ["NSCLCR", "IMDCT", "LUNGx"] + +# Valid values for label_source and population_type filters +LABEL_SOURCE_VALUES = ["histopathology", "radiology", "all"] +POPULATION_TYPE_VALUES = ["screening", "diagnostic", "all"] + +# Mapping from label_source / population_type → dataset lists +LABEL_SOURCE_MAP: dict[str, list[str]] = { + "histopathology": HISTOPATH_DATASETS, + "radiology": RADIOLOGY_DATASETS, +} +POPULATION_TYPE_MAP: dict[str, list[str]] = { + "screening": SCREENING_DATASETS, + "diagnostic": DIAGNOSTIC_DATASETS, +} + +# Valid values for multi-nodule controls +N_NODULES_FILTER_VALUES = ["any", "single_only", "multi_only"] +COMPANION_STRATEGY_VALUES = ["none", "all_companions", "ipsilateral", "same_lobe"] + + +@dataclass +class NoduleSpec: + """Constraints on which nodules to include in the cohort.""" + + label: Optional[int] = None # 0, 1, or None=any + diameter_range: Optional[tuple[float, float]] = None # (min_mm, max_mm) + size_distribution: Optional[SizeDistribution] = None + lobe: Optional[list[str]] = None + zone: Optional[list[str]] = None + side: Optional[str] = None + central_peripheral: Optional[str] = None + pleural_distance_range: Optional[tuple[float, float]] = None + exclude_all_malignant_datasets: bool = False # skip NSCLCR + + # ── Label source filter ──────────────────────────────────── + # Controls which datasets are eligible based on how labels were obtained. + # "histopathology" → DLCS24, LUNA25, NSCLCR, IMDCT, LUNGx + # "radiology" → LUNA16, LNDbv4 (radiologist suspicion level / RSL) + # "all" → no restriction (default) + # None → same as "all" + label_source: Optional[str] = None + + # ── Population type filter ───────────────────────────────── + # Controls whether to draw from screening or diagnostic populations. + # "screening" → DLCS24, LUNA16, LUNA25, LNDbv4 + # "diagnostic" → NSCLCR, IMDCT, LUNGx + # "all" → no restriction (default) + # None → same as "all" + population_type: Optional[str] = None + + # Deprecated: use label_source="histopathology" instead + require_histopath_label: bool = False + + # ── Multi-nodule donor pool filter ───────────────────────── + # Controls which nodules are eligible based on how many nodules + # the donor patient has. + # "any" → no filter (default, current behavior) + # "single_only" → only n_nodules_in_patient == 1 + # "multi_only" → only n_nodules_in_patient >= 2 + # None → same as "any" + n_nodules_filter: Optional[str] = None + + +# ── Insertion specification ────────────────────────────────────────────────── + + +@dataclass +class InsertionSpec: + """Controls for the insertion planner.""" + + target_lobe: Optional[str] = None + target_zone: Optional[str] = None + target_side: Optional[str] = None + scale_tolerance: float = 0.20 # max fractional mismatch before scaling + allow_isotropic_scale: bool = True + allow_anisotropic_warp: bool = False + max_scale_factor: float = 1.5 # never scale more than 50% + min_pleural_dist_mm: float = 2.0 # safety margin from pleura + + +# ── Top-level trial specification ──────────────────────────────────────────── + + +@dataclass +class TrialSpec: + """Complete specification of a synthetic imaging trial.""" + + # ── Identity ────────────────────────────────────────────── + trial_name: str = "untitled_trial" + trial_template: Optional[str] = None # e.g. "NLST" (from knowledge base) + description: str = "" + seed: int = 42 + + # ── Cohort size ─────────────────────────────────────────── + n_cases: int = 500 + cohort_mode: str = "synthetic" # "native" | "matched" | "synthetic" + + # ── Demographics ────────────────────────────────────────── + demographics: Optional[DemographicSpec] = None + + # ── Nodule specification ────────────────────────────────── + nodule_spec: Optional[NoduleSpec] = None + + # ── Prevalence ──────────────────────────────────────────── + malignancy_prevalence: Optional[float] = None # e.g. 0.04 for 4% + no_nodule_fraction: float = 0.0 # fraction of clean cases + + # ── Dataset constraints ─────────────────────────────────── + source_datasets: Optional[list[str]] = None + exclude_datasets: Optional[list[str]] = None + host_datasets: Optional[list[str]] = None # CTs for matched/synthetic + donor_datasets: Optional[list[str]] = None # nodules for matched/synthetic + + # ── Training exclusion ───────────────────────────────────── + # Datasets the model was trained on — excluded from BOTH donor and host pools. + # Use this to ensure test cohorts have zero data leakage from training. + # e.g. exclude_training_datasets=["LUNA16", "LNDbv4"] + exclude_training_datasets: Optional[list[str]] = None + + # ── Multi-nodule companion inclusion ────────────────────── + # When a donor nodule comes from a multi-nodule patient, controls + # whether sibling nodules are also added to the manifest for that case. + # "none" → one nodule per case (default, current behavior) + # "all_companions" → include all sibling nodules from donor patient + # "ipsilateral" → include only same-side companions + # "same_lobe" → include only same-lobe companions + companion_strategy: str = "none" + + # ── Insertion ───────────────────────────────────────────── + insertion_mode: str = "profile_faithful" + insertion_spec: Optional[InsertionSpec] = None + + # ── Stratification ──────────────────────────────────────── + stratify_by: Optional[list[str]] = None # e.g. ["lobe_name", "label"] + + # ── Bootstrapping ───────────────────────────────────────── + n_bootstrap: int = 1 + bootstrap_replace: bool = True + + # ── Path config ─────────────────────────────────────────── + base_dir: str = field(default_factory=_default_base_dir) + + def __post_init__(self): + for attr in ( + "source_datasets", + "exclude_datasets", + "host_datasets", + "donor_datasets", + "exclude_training_datasets", + ): + validate_dataset_names(getattr(self, attr, None)) + + +# ── Digital twin isolation specification ───────────────────────────────────── + + +@dataclass +class DigitalTwinIsolationSpec: + """Specification for a digital twin isolation study. + + This spec is fundamentally different from TrialSpec: instead of + specifying n_cases with donor-host pairing, it selects host patients + from a single dataset and generates one isolation case per native nodule. + + The host body/anatomy segmentation masks are already nodule-free. + Each native nodule has its own individual mask file. + """ + + trial_name: str = "digital_twin_isolation" + dataset: str = "" # Single source dataset + max_patients: Optional[int] = None # Max host patients + all_patients: bool = False # Use all eligible patients + max_nodules_per_patient: Optional[int] = ( + None # Cap isolation cases per CT scan (applied per-CT, not per-patient) + ) + nodule_spec: Optional[NoduleSpec] = None # Nodule filters + seed: int = 42 + exclude_training_datasets: Optional[list[str]] = None + base_dir: str = field(default_factory=_default_base_dir) + + def __post_init__(self): + validate_dataset_names(self.exclude_training_datasets) + + +# ── Digital twin complete specification ────────────────────────────────────── + + +@dataclass +class DigitalTwinCompleteSpec: + """Specification for a digital twin complete study. + + Complementary to DigitalTwinIsolationSpec: instead of one case per + nodule, this mode produces one case per patient containing ALL native + nodules. The host body/anatomy segmentation masks are already + nodule-free; each native nodule has its own individual mask file. + + Stage 2 will insert all nodule masks into the host anatomy with + label value 23, producing a single combined conditioning mask per case. + """ + + trial_name: str = "digital_twin_complete" + dataset: str = "" # Single source dataset + max_patients: Optional[int] = None # Max host patients + all_patients: bool = False # Use all eligible patients + nodule_spec: Optional[NoduleSpec] = None # Nodule filters + seed: int = 42 + exclude_training_datasets: Optional[list[str]] = None + base_dir: str = field(default_factory=_default_base_dir) + + def __post_init__(self): + validate_dataset_names(self.exclude_training_datasets) + + +# ── Digital twin cross specification ───────────────────────────────────────── + +# Valid values for donor_transfer_mode and pairing_policy +DONOR_TRANSFER_MODES = ["single", "complete"] +PAIRING_POLICIES = ["one_to_one", "one_to_many_hosts", "donor_patient_complete"] +PLACEMENT_STRATEGIES = ["profile_faithful_transfer", "host_constrained_transfer"] + + +@dataclass +class DigitalTwinCrossSpec: + """Specification for a digital twin cross study. + + Pairs host anatomy from one patient with donor nodule(s) from a + *different* patient — potentially from a different dataset. + + This enables controlled counterfactual experiments: + - Same donor nodule, different host anatomies + - Same host anatomy, different donor nodules + - Cross-dataset anatomy/nodule mixing + + The host body/anatomy segmentation masks are already nodule-free. + Each donor nodule has its own individual mask file. + """ + + trial_name: str = "digital_twin_cross" + + # Host pool configuration + host_dataset: str = "" # Dataset for host anatomies + max_host_patients: Optional[int] = None # Max host patients to select + all_host_patients: bool = False # Use all eligible host patients + + # Donor pool configuration + donor_dataset: str = "" # Dataset for donor nodules + max_donor_patients: Optional[int] = None # Max donor patients to select + all_donor_patients: bool = False # Use all eligible donor patients + max_donor_nodules: Optional[int] = None # Max donor nodules to use + + # Cross-patient pairing configuration + donor_transfer_mode: str = "single" # "single" | "complete" + pairing_policy: str = ( + "one_to_one" # "one_to_one" | "one_to_many_hosts" | "donor_patient_complete" + ) + n_hosts_per_donor: int = 3 # For one_to_many_hosts policy + + # Placement strategy + placement_strategy: str = ( + "profile_faithful_transfer" # "profile_faithful_transfer" | "host_constrained_transfer" + ) + + # Nodule filters + nodule_spec: Optional[NoduleSpec] = None + + seed: int = 42 + exclude_training_datasets: Optional[list[str]] = None + base_dir: str = field(default_factory=_default_base_dir) + + def __post_init__(self): + validate_dataset_names(self.exclude_training_datasets) + if self.donor_transfer_mode not in DONOR_TRANSFER_MODES: + raise ValueError( + f"donor_transfer_mode must be one of {DONOR_TRANSFER_MODES}, " + f"got '{self.donor_transfer_mode}'" + ) + if self.pairing_policy not in PAIRING_POLICIES: + raise ValueError( + f"pairing_policy must be one of {PAIRING_POLICIES}, " f"got '{self.pairing_policy}'" + ) + if self.placement_strategy not in PLACEMENT_STRATEGIES: + raise ValueError( + f"placement_strategy must be one of {PLACEMENT_STRATEGIES}, " + f"got '{self.placement_strategy}'" + ) diff --git a/itrialspace/src/itrialspace/site/trial_modes.py b/itrialspace/src/itrialspace/site/trial_modes.py new file mode 100644 index 0000000000000000000000000000000000000000..9c66cb4fe954f778b806805390f2fa9bdfd1eda1 --- /dev/null +++ b/itrialspace/src/itrialspace/site/trial_modes.py @@ -0,0 +1,715 @@ +""" +Pre-wired trial mode factories — convenience functions that produce +TrialSpec objects for the 13 scientific trial modes. + +Each function returns either a single TrialSpec or a list of TrialSpecs, +ready to be passed to CohortBuilder.build() (or, for digital twin modes, +to CohortBuilder.build_digital_twin_isolation() / build_digital_twin_complete() +/ build_digital_twin_cross()). +""" + +from __future__ import annotations + +from typing import Optional + +from itrialspace.core.schema import LOBE_NAMES +from itrialspace.site.spec import ( + SIZE_BUCKETS, + DemographicSpec, + DigitalTwinCompleteSpec, + DigitalTwinCrossSpec, + DigitalTwinIsolationSpec, + InsertionSpec, + NoduleSpec, + TrialSpec, +) + + +def _apply_nodule_filters( + spec: TrialSpec, + label_source: Optional[str], + population_type: Optional[str], + n_nodules_filter: Optional[str] = None, +) -> None: + """Apply label_source, population_type, and n_nodules_filter to a spec's NoduleSpec (in-place).""" + if label_source is None and population_type is None and n_nodules_filter is None: + return + if spec.nodule_spec is None: + spec.nodule_spec = NoduleSpec() + if label_source: + spec.nodule_spec.label_source = label_source + if population_type: + spec.nodule_spec.population_type = population_type + if n_nodules_filter: + spec.nodule_spec.n_nodules_filter = n_nodules_filter + + +def controlled_prevalence_study( + n_cases: int = 1000, + prevalence: float = 0.05, + template: Optional[str] = "NLST", + seed: int = 42, + exclude_training_datasets: Optional[list[str]] = None, + label_source: Optional[str] = None, + population_type: Optional[str] = None, + companion_strategy: str = "none", + n_nodules_filter: Optional[str] = None, + **overrides, +) -> TrialSpec: + """Mode 1: Fixed malignancy prevalence. + + Produces n_cases with exactly `prevalence` fraction malignant. + Uses a template trial for demographics and size distribution if provided. + + Args: + exclude_training_datasets: Datasets to exclude (e.g. model was trained on them). + label_source: "histopathology", "radiology", or "all". + population_type: "screening", "diagnostic", or "all". + companion_strategy: "none", "all_companions", "ipsilateral", or "same_lobe". + n_nodules_filter: "any", "single_only", or "multi_only". + """ + if template: + from itrialspace.site.knowledge_base import TrialKnowledgeBase + + kb = TrialKnowledgeBase() + spec = kb.to_trial_spec( + template, + n_cases=n_cases, + cohort_mode="synthetic", + seed=seed, + overrides={"malignancy_prevalence": prevalence, **overrides}, + ) + else: + spec = TrialSpec( + trial_name=f"prevalence_{prevalence:.0%}", + n_cases=n_cases, + malignancy_prevalence=prevalence, + cohort_mode="synthetic", + seed=seed, + ) + for k, v in overrides.items(): + if hasattr(spec, k): + setattr(spec, k, v) + + # Apply filters + if exclude_training_datasets: + spec.exclude_training_datasets = exclude_training_datasets + spec.companion_strategy = companion_strategy + _apply_nodule_filters(spec, label_source, population_type, n_nodules_filter) + return spec + + +def size_detection_curve( + n_per_bucket: int = 100, + size_buckets: Optional[list[str]] = None, + label: int = 1, + template: Optional[str] = "NLST", + seed: int = 42, + exclude_training_datasets: Optional[list[str]] = None, + label_source: Optional[str] = None, + population_type: Optional[str] = None, + **overrides, +) -> list[TrialSpec]: + """Mode 2: One TrialSpec per size bucket. + + Returns list of specs (one per bucket), each with n_per_bucket cases + of a fixed label. Use for FROC size-detection curves. + """ + if size_buckets is None: + size_buckets = SIZE_BUCKETS + + from itrialspace.site.spec import SIZE_BUCKET_RANGES + + specs = [] + for i, bucket in enumerate(size_buckets): + lo, hi = SIZE_BUCKET_RANGES[bucket] + spec = TrialSpec( + trial_name=f"size_curve_{bucket}", + trial_template=template, + n_cases=n_per_bucket, + cohort_mode="synthetic", + malignancy_prevalence=1.0 if label == 1 else 0.0, + nodule_spec=NoduleSpec( + label=label, + diameter_range=(lo, hi), + ), + seed=seed + i, + ) + for k, v in overrides.items(): + if hasattr(spec, k): + setattr(spec, k, v) + if exclude_training_datasets: + spec.exclude_training_datasets = exclude_training_datasets + _apply_nodule_filters(spec, label_source, population_type) + specs.append(spec) + return specs + + +def location_sensitivity( + n_per_lobe: int = 100, + label: int = 1, + diameter_range: tuple[float, float] = (6.0, 15.0), + template: Optional[str] = "NLST", + seed: int = 42, + exclude_training_datasets: Optional[list[str]] = None, + label_source: Optional[str] = None, + population_type: Optional[str] = None, + **overrides, +) -> list[TrialSpec]: + """Mode 3: One TrialSpec per lobe. + + Same nodule size range, varies only location. + Measures detection sensitivity by anatomical position. + """ + specs = [] + for i, lobe in enumerate(LOBE_NAMES): + spec = TrialSpec( + trial_name=f"lobe_{lobe}", + trial_template=template, + n_cases=n_per_lobe, + cohort_mode="synthetic", + malignancy_prevalence=1.0 if label == 1 else 0.0, + nodule_spec=NoduleSpec( + label=label, + diameter_range=diameter_range, + lobe=[lobe], + ), + insertion_mode="prescribed", + insertion_spec=InsertionSpec(target_lobe=lobe), + seed=seed + i, + ) + for k, v in overrides.items(): + if hasattr(spec, k): + setattr(spec, k, v) + if exclude_training_datasets: + spec.exclude_training_datasets = exclude_training_datasets + _apply_nodule_filters(spec, label_source, population_type) + specs.append(spec) + return specs + + +def demographic_stratification( + n_per_stratum: int = 200, + strata: Optional[list[dict]] = None, + template: str = "NLST", + seed: int = 42, + exclude_training_datasets: Optional[list[str]] = None, + label_source: Optional[str] = None, + population_type: Optional[str] = None, + **overrides, +) -> list[TrialSpec]: + """Mode 4: Separate cohorts by demographic strata. + + Each stratum dict can contain: + sex (str), age_range (tuple), smoking_status (list), pack_years_min (float) + """ + if strata is None: + strata = [ + {"sex_ratio_male": 1.0, "age_range": (55, 65)}, + {"sex_ratio_male": 1.0, "age_range": (65, 75)}, + {"sex_ratio_male": 0.0, "age_range": (55, 65)}, + {"sex_ratio_male": 0.0, "age_range": (65, 75)}, + ] + + from itrialspace.site.knowledge_base import TrialKnowledgeBase + + kb = TrialKnowledgeBase() + + specs = [] + for i, stratum in enumerate(strata): + demo = DemographicSpec( + age_range=stratum.get("age_range"), + sex_ratio_male=stratum.get("sex_ratio_male"), + smoking_status=stratum.get("smoking_status"), + pack_years_min=stratum.get("pack_years_min"), + ) + spec = kb.to_trial_spec( + template, + n_cases=n_per_stratum, + cohort_mode="synthetic", + seed=seed + i, + overrides={"demographics": demo, **overrides}, + ) + spec.trial_name = f"demo_stratum_{i}" + if exclude_training_datasets: + spec.exclude_training_datasets = exclude_training_datasets + _apply_nodule_filters(spec, label_source, population_type) + specs.append(spec) + return specs + + +def counterfactual_cohort( + n_cases: int = 500, + template: str = "NLST", + vary_param: str = "malignancy_prevalence", + values: Optional[list] = None, + seed: int = 42, + exclude_training_datasets: Optional[list[str]] = None, + label_source: Optional[str] = None, + population_type: Optional[str] = None, +) -> list[TrialSpec]: + """Mode 5: Same base cohort with one parameter varied. + + Useful for measuring the effect of a single variable on algorithm performance. + """ + if values is None: + values = [0.01, 0.02, 0.05, 0.10, 0.20] + + from itrialspace.site.knowledge_base import TrialKnowledgeBase + + kb = TrialKnowledgeBase() + + specs = [] + for i, val in enumerate(values): + spec = kb.to_trial_spec( + template, + n_cases=n_cases, + cohort_mode="synthetic", + seed=seed, # same seed for same base cohort + overrides={vary_param: val}, + ) + spec.trial_name = f"counterfactual_{vary_param}={val}" + if exclude_training_datasets: + spec.exclude_training_datasets = exclude_training_datasets + _apply_nodule_filters(spec, label_source, population_type) + specs.append(spec) + return specs + + +def cross_dataset_generalization( + n_cases: int = 300, + datasets: Optional[list[str]] = None, + seed: int = 42, + exclude_training_datasets: Optional[list[str]] = None, + label_source: Optional[str] = None, + population_type: Optional[str] = None, + **overrides, +) -> list[TrialSpec]: + """Mode 6: One spec per dataset as sole donor. + + Tests whether algorithm performance varies by data source. + """ + if datasets is None: + datasets = ["DLCS24", "LUNA25", "LNDbv4", "IMDCT", "LUNGx"] + + specs = [] + for i, ds in enumerate(datasets): + spec = TrialSpec( + trial_name=f"cross_ds_{ds}", + n_cases=n_cases, + cohort_mode="synthetic", + donor_datasets=[ds], + seed=seed + i, + ) + for k, v in overrides.items(): + if hasattr(spec, k): + setattr(spec, k, v) + if exclude_training_datasets: + spec.exclude_training_datasets = exclude_training_datasets + _apply_nodule_filters(spec, label_source, population_type) + specs.append(spec) + return specs + + +def bootstrap_confidence( + base_spec: TrialSpec, + n_bootstrap: int = 100, +) -> TrialSpec: + """Mode 7: Set n_bootstrap on a spec for confidence interval estimation. + + CohortBuilder.build_all() will produce n_bootstrap independent manifests. + """ + base_spec.n_bootstrap = n_bootstrap + return base_spec + + +def algorithm_comparison( + n_cases: int = 500, + template: str = "NLST", + seed: int = 42, + exclude_training_datasets: Optional[list[str]] = None, + label_source: Optional[str] = None, + population_type: Optional[str] = None, + companion_strategy: str = "none", + n_nodules_filter: Optional[str] = None, + **overrides, +) -> TrialSpec: + """Mode 8: Single standardised cohort for comparing algorithms. + + Fixed seed ensures identical manifest across runs. + Use the same manifest to evaluate multiple models. + + Args: + companion_strategy: "none", "all_companions", "ipsilateral", or "same_lobe". + n_nodules_filter: "any", "single_only", or "multi_only". + """ + from itrialspace.site.knowledge_base import TrialKnowledgeBase + + kb = TrialKnowledgeBase() + spec = kb.to_trial_spec( + template, + n_cases=n_cases, + cohort_mode="synthetic", + seed=seed, + overrides=overrides, + ) + spec.trial_name = f"algo_comparison_{template}_{n_cases}" + if exclude_training_datasets: + spec.exclude_training_datasets = exclude_training_datasets + spec.companion_strategy = companion_strategy + _apply_nodule_filters(spec, label_source, population_type, n_nodules_filter) + return spec + + +def screening_protocol_simulation( + template: str = "NLST", + n_rounds: int = 3, + n_cases_per_round: int = 500, + prevalence_decay: float = 0.7, + seed: int = 42, + exclude_training_datasets: Optional[list[str]] = None, + label_source: Optional[str] = None, + population_type: Optional[str] = None, + **overrides, +) -> list[TrialSpec]: + """Mode 9: Multi-round screening protocol simulation. + + Each round has decreasing malignancy prevalence (simulating + that cancers caught in round 1 are removed from later rounds). + """ + from itrialspace.site.knowledge_base import TrialKnowledgeBase + + kb = TrialKnowledgeBase() + + base_spec = kb.to_trial_spec( + template, + n_cases=n_cases_per_round, + cohort_mode="synthetic", + seed=seed, + ) + base_prev = base_spec.malignancy_prevalence or 0.04 + + specs = [] + for r in range(n_rounds): + round_prev = base_prev * (prevalence_decay**r) + spec = kb.to_trial_spec( + template, + n_cases=n_cases_per_round, + cohort_mode="synthetic", + seed=seed + r, + overrides={"malignancy_prevalence": round_prev, **overrides}, + ) + spec.trial_name = f"screening_round_{r+1}_prev={round_prev:.3f}" + if exclude_training_datasets: + spec.exclude_training_datasets = exclude_training_datasets + _apply_nodule_filters(spec, label_source, population_type) + specs.append(spec) + return specs + + +def multi_nodule_realism_study( + n_cases: int = 500, + multi_nodule_fraction: float = 0.25, + companion_strategy: str = "all_companions", + template: Optional[str] = "NLST", + seed: int = 42, + exclude_training_datasets: Optional[list[str]] = None, + label_source: Optional[str] = None, + population_type: Optional[str] = None, + **overrides, +) -> list[TrialSpec]: + """Mode 10: Multi-nodule realism study. + + Creates two sub-cohorts: + 1. Single-nodule cases (1 - multi_nodule_fraction) + 2. Multi-nodule cases with companions (multi_nodule_fraction) + + Allows measuring the impact of multi-nodule context on detection + performance. In NLST, ~25% of screened patients have multiple nodules. + + Args: + multi_nodule_fraction: Fraction of cases drawn from multi-nodule patients. + companion_strategy: How to include companion nodules ("all_companions", + "ipsilateral", "same_lobe"). + """ + n_multi = int(n_cases * multi_nodule_fraction) + n_single = n_cases - n_multi + + # Single-nodule sub-cohort + single_spec = TrialSpec( + trial_name="multi_nodule_study_single", + trial_template=template, + n_cases=n_single, + cohort_mode="synthetic", + nodule_spec=NoduleSpec(n_nodules_filter="single_only"), + companion_strategy="none", + seed=seed, + ) + for k, v in overrides.items(): + if hasattr(single_spec, k): + setattr(single_spec, k, v) + if exclude_training_datasets: + single_spec.exclude_training_datasets = exclude_training_datasets + _apply_nodule_filters(single_spec, label_source, population_type) + + # Multi-nodule sub-cohort + multi_spec = TrialSpec( + trial_name="multi_nodule_study_multi", + trial_template=template, + n_cases=n_multi, + cohort_mode="synthetic", + nodule_spec=NoduleSpec(n_nodules_filter="multi_only"), + companion_strategy=companion_strategy, + seed=seed + 1, + ) + for k, v in overrides.items(): + if hasattr(multi_spec, k): + setattr(multi_spec, k, v) + if exclude_training_datasets: + multi_spec.exclude_training_datasets = exclude_training_datasets + _apply_nodule_filters(multi_spec, label_source, population_type) + + return [single_spec, multi_spec] + + +def digital_twin_isolation( + dataset: str, + max_patients: Optional[int] = None, + all_patients: bool = False, + max_nodules_per_patient: Optional[int] = None, + label: Optional[int] = None, + diameter_min: Optional[float] = None, + diameter_max: Optional[float] = None, + seed: int = 42, + exclude_training_datasets: Optional[list[str]] = None, +) -> DigitalTwinIsolationSpec: + """Mode 11: Digital twin isolation study. + + For each host patient in the selected dataset, generate one trial case + per native nodule. Each case uses the host's own clean anatomy mask + paired with exactly one of its native nodule masks. + + Scientific purpose: + • Isolate lesion behaviour within fixed host anatomy + • Remove multi-nodule interference + • Enable lesion-level evaluation + • Allow later comparison with complete multi-nodule digital twin trials + + Args: + dataset: Source dataset name (e.g. "DLCS24", "LUNA16"). + max_patients: Process at most N eligible host patients. + Mutually exclusive with all_patients. + all_patients: Process every eligible host patient. + Mutually exclusive with max_patients. + max_nodules_per_patient: Cap the number of isolation cases per patient. + label: Filter nodules by label (0=benign, 1=malignant, None=any). + diameter_min: Minimum nodule diameter in mm (inclusive). + diameter_max: Maximum nodule diameter in mm (inclusive). + seed: Random seed for patient sampling when max_patients is set. + exclude_training_datasets: Datasets to exclude entirely. + + Returns: + DigitalTwinIsolationSpec carrying the full configuration. + + Raises: + ValueError: If both max_patients and all_patients are specified, or neither. + """ + if max_patients is not None and all_patients: + raise ValueError("--max-patients and --all-patients are mutually exclusive") + if max_patients is None and not all_patients: + raise ValueError("Specify either --max-patients N or --all-patients") + + nodule_spec = NoduleSpec( + label=label, + diameter_range=( + (diameter_min, diameter_max) + if (diameter_min is not None or diameter_max is not None) + else None + ), + ) + + return DigitalTwinIsolationSpec( + trial_name=f"digital_twin_isolation_{dataset}", + dataset=dataset, + max_patients=max_patients, + all_patients=all_patients, + max_nodules_per_patient=max_nodules_per_patient, + nodule_spec=nodule_spec, + seed=seed, + exclude_training_datasets=exclude_training_datasets, + ) + + +def digital_twin_complete( + dataset: str, + max_patients: Optional[int] = None, + all_patients: bool = False, + label: Optional[int] = None, + diameter_min: Optional[float] = None, + diameter_max: Optional[float] = None, + seed: int = 42, + exclude_training_datasets: Optional[list[str]] = None, +) -> DigitalTwinCompleteSpec: + """Mode 12: Digital twin complete study. + + For each host patient in the selected dataset, generate one trial case + containing ALL native nodules. The host's clean anatomy mask is paired + with every native nodule mask belonging to that patient. + + This is the complement to digital_twin_isolation (Mode 11): + - Isolation → one nodule per case (N nodules → N cases) + - Complete → all nodules per case (N nodules → 1 case) + + Scientific purpose: + • Reconstruct the complete native nodule burden + • Compare with isolation trials to measure multi-nodule detection suppression + • Identify context-dependent model behaviour and lesion-specific failures + + Args: + dataset: Source dataset name (e.g. "DLCS24", "LUNA16"). + max_patients: Process at most N eligible host patients. + Mutually exclusive with all_patients. + all_patients: Process every eligible host patient. + Mutually exclusive with max_patients. + label: Filter nodules by label (0=benign, 1=malignant, None=any). + diameter_min: Minimum nodule diameter in mm (inclusive). + diameter_max: Maximum nodule diameter in mm (inclusive). + seed: Random seed for patient sampling when max_patients is set. + exclude_training_datasets: Datasets to exclude entirely. + + Returns: + DigitalTwinCompleteSpec carrying the full configuration. + + Raises: + ValueError: If both max_patients and all_patients are specified, or neither. + """ + if max_patients is not None and all_patients: + raise ValueError("--max-patients and --all-patients are mutually exclusive") + if max_patients is None and not all_patients: + raise ValueError("Specify either --max-patients N or --all-patients") + + nodule_spec = NoduleSpec( + label=label, + diameter_range=( + (diameter_min, diameter_max) + if (diameter_min is not None or diameter_max is not None) + else None + ), + ) + + return DigitalTwinCompleteSpec( + trial_name=f"digital_twin_complete_{dataset}", + dataset=dataset, + max_patients=max_patients, + all_patients=all_patients, + nodule_spec=nodule_spec, + seed=seed, + exclude_training_datasets=exclude_training_datasets, + ) + + +def digital_twin_cross( + host_dataset: str, + donor_dataset: str, + max_host_patients: Optional[int] = None, + all_host_patients: bool = False, + max_donor_patients: Optional[int] = None, + all_donor_patients: bool = False, + max_donor_nodules: Optional[int] = None, + donor_transfer_mode: str = "single", + pairing_policy: str = "one_to_one", + n_hosts_per_donor: int = 3, + placement_strategy: str = "profile_faithful_transfer", + label: Optional[int] = None, + diameter_min: Optional[float] = None, + diameter_max: Optional[float] = None, + seed: int = 42, + exclude_training_datasets: Optional[list[str]] = None, +) -> DigitalTwinCrossSpec: + """Mode 13: Digital twin cross study. + + Pairs host anatomy from one patient with donor nodule(s) from a + *different* patient, potentially from a different dataset. + + This enables controlled counterfactual experiments: + - Same donor nodule across multiple host anatomies + - Same host anatomy with different donor nodules + - Cross-dataset anatomy/nodule mixing + - Full donor burden transfer to new anatomy + + Supported pairing policies: + - one_to_one: each donor nodule paired with one host + - one_to_many_hosts: same donor paired with N hosts (crucial for anatomy-dependent analysis) + - donor_patient_complete: all nodules from one donor patient paired to one host + + Supported donor transfer modes: + - single: one donor nodule per case + - complete: all donor nodules from the donor patient per case + + Args: + host_dataset: Dataset for host anatomies (e.g. "DLCS24"). + donor_dataset: Dataset for donor nodules (e.g. "LUNA25"). + max_host_patients: Process at most N host patients. + Mutually exclusive with all_host_patients. + all_host_patients: Use all eligible host patients. + Mutually exclusive with max_host_patients. + max_donor_patients: Process at most N donor patients. + Mutually exclusive with all_donor_patients. + all_donor_patients: Use all eligible donor patients. + Mutually exclusive with max_donor_patients. + max_donor_nodules: Max total donor nodules used. + donor_transfer_mode: "single" or "complete". + pairing_policy: "one_to_one", "one_to_many_hosts", or "donor_patient_complete". + n_hosts_per_donor: Number of hosts per donor (one_to_many_hosts policy). + placement_strategy: "profile_faithful_transfer" or "host_constrained_transfer". + label: Filter donor nodules by label (0=benign, 1=malignant, None=any). + diameter_min: Min donor nodule diameter in mm (inclusive). + diameter_max: Max donor nodule diameter in mm (inclusive). + seed: Random seed for patient sampling. + exclude_training_datasets: Datasets to exclude entirely. + + Returns: + DigitalTwinCrossSpec carrying the full configuration. + + Raises: + ValueError: If mutual exclusion constraints are violated. + """ + if max_host_patients is not None and all_host_patients: + raise ValueError("--max-host-patients and --all-host-patients are mutually exclusive") + if max_host_patients is None and not all_host_patients: + raise ValueError("Specify either --max-host-patients N or --all-host-patients") + if max_donor_patients is not None and all_donor_patients: + raise ValueError("--max-donor-patients and --all-donor-patients are mutually exclusive") + if max_donor_patients is None and not all_donor_patients and max_donor_nodules is None: + raise ValueError( + "Specify either --max-donor-patients N, --all-donor-patients, or --max-donor-nodules N" + ) + + nodule_spec = NoduleSpec( + label=label, + diameter_range=( + (diameter_min, diameter_max) + if (diameter_min is not None or diameter_max is not None) + else None + ), + ) + + trial_name = f"digital_twin_cross_{host_dataset}_x_{donor_dataset}" + + return DigitalTwinCrossSpec( + trial_name=trial_name, + host_dataset=host_dataset, + donor_dataset=donor_dataset, + max_host_patients=max_host_patients, + all_host_patients=all_host_patients, + max_donor_patients=max_donor_patients, + all_donor_patients=all_donor_patients, + max_donor_nodules=max_donor_nodules, + donor_transfer_mode=donor_transfer_mode, + pairing_policy=pairing_policy, + n_hosts_per_donor=n_hosts_per_donor, + placement_strategy=placement_strategy, + nodule_spec=nodule_spec, + seed=seed, + exclude_training_datasets=exclude_training_datasets, + ) diff --git a/itrialspace/src/itrialspace/site/validation.py b/itrialspace/src/itrialspace/site/validation.py new file mode 100644 index 0000000000000000000000000000000000000000..0c24bec97b9b4beb32b17cc1a23d53e9be5a74d3 --- /dev/null +++ b/itrialspace/src/itrialspace/site/validation.py @@ -0,0 +1,264 @@ +""" +Spec validation — checks a TrialSpec against the available NoduleIndex +for feasibility and correctness. +""" + +from __future__ import annotations + +import pandas as pd + +from itrialspace.core.schema import CP_VALUES, DATASET_NAMES, LOBE_NAMES, SIDE_NAMES, ZONE_NAMES +from itrialspace.site.spec import ( + COMPANION_STRATEGY_VALUES, + HISTOPATH_DATASETS, + LABEL_SOURCE_MAP, + LABEL_SOURCE_VALUES, + N_NODULES_FILTER_VALUES, + POPULATION_TYPE_MAP, + POPULATION_TYPE_VALUES, + TrialSpec, +) + + +class SpecValidator: + """Validates a TrialSpec against the available NoduleIndex.""" + + def __init__(self, index_df: pd.DataFrame): + self._df = index_df + + def validate(self, spec: TrialSpec) -> list[str]: + """Returns list of error messages. Empty = valid.""" + errors: list[str] = [] + + # Cohort mode + if spec.cohort_mode not in ("native", "matched", "synthetic"): + errors.append(f"Invalid cohort_mode: '{spec.cohort_mode}'") + + # Insertion mode + if spec.insertion_mode not in ("profile_faithful", "prescribed", "randomised"): + errors.append(f"Invalid insertion_mode: '{spec.insertion_mode}'") + + # Prevalence bounds + if spec.malignancy_prevalence is not None: + if not 0.0 <= spec.malignancy_prevalence <= 1.0: + errors.append( + f"malignancy_prevalence must be in [0,1], got {spec.malignancy_prevalence}" + ) + + if not 0.0 <= spec.no_nodule_fraction <= 1.0: + errors.append(f"no_nodule_fraction must be in [0,1], got {spec.no_nodule_fraction}") + + # Dataset names + for ds_list_name in ( + "source_datasets", + "exclude_datasets", + "host_datasets", + "donor_datasets", + "exclude_training_datasets", + ): + ds_list = getattr(spec, ds_list_name) + if ds_list: + for ds in ds_list: + if ds not in DATASET_NAMES: + errors.append(f"Unknown dataset '{ds}' in {ds_list_name}") + + # N cases + if spec.n_cases < 1: + errors.append(f"n_cases must be >= 1, got {spec.n_cases}") + + # Nodule spec validation + ns = spec.nodule_spec + if ns: + if ns.label is not None and ns.label not in (0, 1): + errors.append(f"NoduleSpec.label must be 0, 1, or None, got {ns.label}") + + if ns.lobe: + for l in ns.lobe: + if l not in LOBE_NAMES: + errors.append(f"Unknown lobe '{l}' in NoduleSpec") + + if ns.zone: + for z in ns.zone: + if z not in ZONE_NAMES: + errors.append(f"Unknown zone '{z}' in NoduleSpec") + + if ns.side and ns.side not in SIDE_NAMES: + errors.append(f"Unknown side '{ns.side}' in NoduleSpec") + + if ns.central_peripheral and ns.central_peripheral not in CP_VALUES: + errors.append(f"Unknown central_peripheral '{ns.central_peripheral}'") + + if ns.diameter_range: + lo, hi = ns.diameter_range + if lo >= hi: + errors.append(f"diameter_range min ({lo}) >= max ({hi})") + + if ns.size_distribution and ns.size_distribution.bucket_weights: + total = sum(ns.size_distribution.bucket_weights.values()) + if abs(total - 1.0) > 0.05: + errors.append(f"Size distribution weights sum to {total:.3f}, expected ~1.0") + + if ns.label_source and ns.label_source not in LABEL_SOURCE_VALUES: + errors.append( + f"NoduleSpec.label_source must be one of {LABEL_SOURCE_VALUES}, " + f"got '{ns.label_source}'" + ) + + if ns.population_type and ns.population_type not in POPULATION_TYPE_VALUES: + errors.append( + f"NoduleSpec.population_type must be one of {POPULATION_TYPE_VALUES}, " + f"got '{ns.population_type}'" + ) + + if ns.n_nodules_filter and ns.n_nodules_filter not in N_NODULES_FILTER_VALUES: + errors.append( + f"NoduleSpec.n_nodules_filter must be one of {N_NODULES_FILTER_VALUES}, " + f"got '{ns.n_nodules_filter}'" + ) + + # Companion strategy validation + if spec.companion_strategy not in COMPANION_STRATEGY_VALUES: + errors.append( + f"companion_strategy must be one of {COMPANION_STRATEGY_VALUES}, " + f"got '{spec.companion_strategy}'" + ) + + # Insertion spec validation + ispec = spec.insertion_spec + if ispec: + if ispec.target_lobe and ispec.target_lobe not in LOBE_NAMES: + errors.append(f"Unknown target_lobe '{ispec.target_lobe}'") + if ispec.target_zone and ispec.target_zone not in ZONE_NAMES: + errors.append(f"Unknown target_zone '{ispec.target_zone}'") + if ispec.max_scale_factor < 1.0: + errors.append(f"max_scale_factor must be >= 1.0, got {ispec.max_scale_factor}") + + return errors + + def feasibility_report(self, spec: TrialSpec) -> dict: + """Detailed feasibility analysis against available data. + + Returns dict with: + pool_size: total matching nodules + malignant_pool: count of malignant nodules in pool + benign_pool: count of benign nodules in pool + n_requested_malignant / n_requested_benign: derived from spec + feasible: bool + warnings: list of strings + """ + df = self._df.copy() + warnings: list[str] = [] + + # Apply dataset filters + if spec.source_datasets: + df = df[df["dataset"].isin(spec.source_datasets)] + if spec.exclude_datasets: + df = df[~df["dataset"].isin(spec.exclude_datasets)] + if spec.donor_datasets: + df = df[df["dataset"].isin(spec.donor_datasets)] + if spec.exclude_training_datasets: + df = df[~df["dataset"].isin(spec.exclude_training_datasets)] + + # Apply nodule spec filters + ns = spec.nodule_spec + if ns: + if ns.diameter_range: + lo, hi = ns.diameter_range + df = df[ + (df["reinsertion_nodule_diam_mm"] >= lo) + & (df["reinsertion_nodule_diam_mm"] <= hi) + ] + if ns.lobe: + df = df[df["reinsertion_lobe"].isin(ns.lobe)] + if ns.zone: + df = df[df["reinsertion_lung_zone"].isin(ns.zone)] + if ns.side: + df = df[df["reinsertion_lung_side"] == ns.side] + if ns.exclude_all_malignant_datasets: + df = df[~df["dataset"].isin(["NSCLCR"])] + + # Label source filter + if ns.label_source and ns.label_source != "all": + allowed = LABEL_SOURCE_MAP.get(ns.label_source) + if allowed: + df = df[df["dataset"].isin(allowed)] + elif ns.require_histopath_label: + df = df[df["dataset"].isin(HISTOPATH_DATASETS)] + + # Population type filter + if ns.population_type and ns.population_type != "all": + allowed = POPULATION_TYPE_MAP.get(ns.population_type) + if allowed: + df = df[df["dataset"].isin(allowed)] + + # Multi-nodule filter + if ns.n_nodules_filter == "single_only": + df = df[df["n_nodules_in_patient"] == 1] + elif ns.n_nodules_filter == "multi_only": + df = df[df["n_nodules_in_patient"] >= 2] + + pool_size = len(df) + mal_pool = int((df["label"] == 1).sum()) if "label" in df.columns else 0 + ben_pool = int((df["label"] == 0).sum()) if "label" in df.columns else 0 + + # Compute requested counts + n_nodule_cases = int(spec.n_cases * (1.0 - spec.no_nodule_fraction)) + n_mal = 0 + n_ben = 0 + if spec.malignancy_prevalence is not None: + n_mal = int(n_nodule_cases * spec.malignancy_prevalence) + n_ben = n_nodule_cases - n_mal + else: + n_ben = n_nodule_cases # no prevalence constraint + + # Multi-nodule pool statistics + n_multi = ( + int((df["n_nodules_in_patient"] >= 2).sum()) + if "n_nodules_in_patient" in df.columns + else 0 + ) + n_single = ( + int((df["n_nodules_in_patient"] == 1).sum()) + if "n_nodules_in_patient" in df.columns + else pool_size + ) + + feasible = True + if pool_size < n_nodule_cases: + warnings.append( + f"Pool size ({pool_size}) < requested cases ({n_nodule_cases}). " + f"Sampling with replacement may be needed." + ) + if spec.malignancy_prevalence is not None: + if mal_pool < n_mal: + warnings.append(f"Malignant pool ({mal_pool}) < requested malignant ({n_mal})") + feasible = False + if ben_pool < n_ben: + warnings.append(f"Benign pool ({ben_pool}) < requested benign ({n_ben})") + + # Companion strategy feasibility + if spec.companion_strategy != "none": + multi_patients = ( + df[df["n_nodules_in_patient"] >= 2]["patient_id"].nunique() + if "patient_id" in df.columns + else 0 + ) + if multi_patients < n_nodule_cases * 0.1: + warnings.append( + f"companion_strategy='{spec.companion_strategy}' requested but only " + f"{multi_patients} multi-nodule patients in pool" + ) + + return { + "pool_size": pool_size, + "malignant_pool": mal_pool, + "benign_pool": ben_pool, + "n_requested_malignant": n_mal, + "n_requested_benign": n_ben, + "n_nodule_cases": n_nodule_cases, + "datasets_in_pool": df["dataset"].unique().tolist() if len(df) > 0 else [], + "multi_nodule_pool": n_multi, + "single_nodule_pool": n_single, + "feasible": feasible, + "warnings": warnings, + } diff --git a/itrialspace/src/itrialspace/synthesis/__init__.py b/itrialspace/src/itrialspace/synthesis/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/itrialspace/src/itrialspace/synthesis/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..52c0a82c6504d80a5aa5e7c345799bc6dafddbb0 Binary files /dev/null and b/itrialspace/src/itrialspace/synthesis/__pycache__/__init__.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/synthesis/configs/config_maisi3d-rflow.json b/itrialspace/src/itrialspace/synthesis/configs/config_maisi3d-rflow.json new file mode 100644 index 0000000000000000000000000000000000000000..1f2ee4619b464ba47e619191085214bcf042752e --- /dev/null +++ b/itrialspace/src/itrialspace/synthesis/configs/config_maisi3d-rflow.json @@ -0,0 +1,150 @@ +{ + "spatial_dims": 3, + "image_channels": 1, + "latent_channels": 4, + "include_body_region": false, + "mask_generation_latent_shape": [ + 4, + 64, + 64, + 64 + ], + "autoencoder_def": { + "_target_": "monai.apps.generation.maisi.networks.autoencoderkl_maisi.AutoencoderKlMaisi", + "spatial_dims": "@spatial_dims", + "in_channels": "@image_channels", + "out_channels": "@image_channels", + "latent_channels": "@latent_channels", + "num_channels": [ + 64, + 128, + 256 + ], + "num_res_blocks": [2,2,2], + "norm_num_groups": 32, + "norm_eps": 1e-06, + "attention_levels": [ + false, + false, + false + ], + "with_encoder_nonlocal_attn": false, + "with_decoder_nonlocal_attn": false, + "use_checkpointing": false, + "use_convtranspose": false, + "norm_float16": true, + "num_splits": 4, + "dim_split": 1 + }, + "diffusion_unet_def": { + "_target_": "monai.apps.generation.maisi.networks.diffusion_model_unet_maisi.DiffusionModelUNetMaisi", + "spatial_dims": "@spatial_dims", + "in_channels": "@latent_channels", + "out_channels": "@latent_channels", + "num_channels": [64, 128, 256, 512], + "attention_levels": [ + false, + false, + true, + true + ], + "num_head_channels": [ + 0, + 0, + 32, + 32 + ], + "num_res_blocks": 2, + "use_flash_attention": true, + "include_top_region_index_input": "@include_body_region", + "include_bottom_region_index_input": "@include_body_region", + "include_spacing_input": true, + "num_class_embeds": 128, + "resblock_updown": true, + "include_fc": true + }, + "controlnet_def": { + "_target_": "monai.apps.generation.maisi.networks.controlnet_maisi.ControlNetMaisi", + "spatial_dims": "@spatial_dims", + "in_channels": "@latent_channels", + "num_channels": [64, 128, 256, 512], + "attention_levels": [ + false, + false, + true, + true + ], + "num_head_channels": [ + 0, + 0, + 32, + 32 + ], + "num_res_blocks": 2, + "use_flash_attention": true, + "conditioning_embedding_in_channels": 8, + "conditioning_embedding_num_channels": [8, 32, 64], + "num_class_embeds": 128, + "resblock_updown": true, + "include_fc": true + }, + "mask_generation_autoencoder_def": { + "_target_": "monai.apps.generation.maisi.networks.autoencoderkl_maisi.AutoencoderKlMaisi", + "spatial_dims": "@spatial_dims", + "in_channels": 8, + "out_channels": 125, + "latent_channels": "@latent_channels", + "num_channels": [ + 32, + 64, + 128 + ], + "num_res_blocks": [1, 2, 2], + "norm_num_groups": 32, + "norm_eps": 1e-06, + "attention_levels": [ + false, + false, + false + ], + "with_encoder_nonlocal_attn": false, + "with_decoder_nonlocal_attn": false, + "use_flash_attention": false, + "use_checkpointing": true, + "use_convtranspose": true, + "norm_float16": true, + "num_splits": 8, + "dim_split": 1 + }, + "mask_generation_diffusion_def": { + "_target_": "monai.networks.nets.diffusion_model_unet.DiffusionModelUNet", + "spatial_dims": "@spatial_dims", + "in_channels": "@latent_channels", + "out_channels": "@latent_channels", + "channels":[64, 128, 256, 512], + "attention_levels":[false, false, true, true], + "num_head_channels":[0, 0, 32, 32], + "num_res_blocks": 2, + "use_flash_attention": true, + "with_conditioning": true, + "upcast_attention": true, + "cross_attention_dim": 10 + }, + "mask_generation_scale_factor": 1.0055984258651733, + "noise_scheduler": { + "_target_": "monai.networks.schedulers.rectified_flow.RFlowScheduler", + "num_train_timesteps": 1000, + "use_discrete_timesteps": false, + "use_timestep_transform": true, + "sample_method": "uniform", + "scale":1.4 + }, + "mask_generation_noise_scheduler": { + "_target_": "monai.networks.schedulers.ddpm.DDPMScheduler", + "num_train_timesteps": 1000, + "beta_start": 0.0015, + "beta_end": 0.0195, + "schedule": "scaled_linear_beta", + "clip_sample": false + } +} diff --git a/itrialspace/src/itrialspace/synthesis/configs/infr_config_NoMAISI_controlnet.json b/itrialspace/src/itrialspace/synthesis/configs/infr_config_NoMAISI_controlnet.json new file mode 100644 index 0000000000000000000000000000000000000000..95f5dee643dfb75659cc11b0c8c77feaf1a5ff54 --- /dev/null +++ b/itrialspace/src/itrialspace/synthesis/configs/infr_config_NoMAISI_controlnet.json @@ -0,0 +1,17 @@ +{ + "controlnet_train": { + "batch_size": 2, + "cache_rate": 0.0, + "fold": 1, + "lr": 1e-5, + "n_epochs": 500, + "weighted_loss_label": [23], + "weighted_loss": 100 + }, + "controlnet_infer": { + "num_inference_steps": 30, + "autoencoder_sliding_window_infer_size": [80, 80, 64], + "autoencoder_sliding_window_infer_overlap": 0.25, + "modality": 1 + } +} diff --git a/itrialspace/src/itrialspace/synthesis/configs/infr_env_NoMAISI_DLCSD24_demo.json b/itrialspace/src/itrialspace/synthesis/configs/infr_env_NoMAISI_DLCSD24_demo.json new file mode 100644 index 0000000000000000000000000000000000000000..812c7b7ec6984b96ec9a1378152cff68c01f1567 --- /dev/null +++ b/itrialspace/src/itrialspace/synthesis/configs/infr_env_NoMAISI_DLCSD24_demo.json @@ -0,0 +1,15 @@ +{ + "model_dir": "${NODMAISI_MODELS_DIR}/", + "output_dir": "${ITRIALSPACE_OUTPUT_DIR}/synthesis_demo/NoMAISI_DLCSD24_demo_512xy_256z_771p25m", + "tfevent_path": "${ITRIALSPACE_OUTPUT_DIR}/synthesis_demo/tfevent", + "trained_autoencoder_path": "${NODMAISI_MODELS_DIR}/autoencoder.pt", + "trained_diffusion_path": "${NODMAISI_MODELS_DIR}/diffusion_unet.pt", + "trained_controlnet_path": "${NODMAISI_MODELS_DIR}/Experiments_NoMAISI_512xy_256z_771p25m_finetune_500epoch_best.pt", + "exp_name": "NoMAISI_DLCSD24_demo_512xy_256z_771p25m", + "data_base_dir": [ + "${ITRIALSPACE_ROOT}/src/itrialspace/synthesis/data" + ], + "json_data_list": [ + "${ITRIALSPACE_ROOT}/src/itrialspace/synthesis/data/infr_NoMAISI_DLCSD24_demo_512xy_256z_771p25m_dataset.json" + ] +} \ No newline at end of file diff --git a/itrialspace/src/itrialspace/synthesis/scripts/__init__.py b/itrialspace/src/itrialspace/synthesis/scripts/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8ab6ee9afaf6fa15a7502da0525f01279f04f578 --- /dev/null +++ b/itrialspace/src/itrialspace/synthesis/scripts/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. diff --git a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad4ab4c5a0fb9d235bb1dfc8b61129f09c92483a Binary files /dev/null and b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/__init__.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/augmentation.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/augmentation.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..281a112fb0484bd24c2dd2e4ecc5ebde0c53f61f Binary files /dev/null and b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/augmentation.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/compute_fid_2-5d_ct.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/compute_fid_2-5d_ct.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ad9f76b0843c879a2138245df5809e30510f81a Binary files /dev/null and b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/compute_fid_2-5d_ct.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/diff_model_create_training_data.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/diff_model_create_training_data.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..991ed478e63b414193eda835503fd95a01804c1e Binary files /dev/null and b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/diff_model_create_training_data.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/diff_model_infer.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/diff_model_infer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..257bbfc6bc22f3521a0b362019ef5ad5b224648a Binary files /dev/null and b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/diff_model_infer.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/diff_model_setting.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/diff_model_setting.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2c15011ff32e44db9e138aaff8a3ed26da43dbca Binary files /dev/null and b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/diff_model_setting.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/diff_model_train.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/diff_model_train.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..785083143920d0e6ab0c99b202e674a0c22da573 Binary files /dev/null and b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/diff_model_train.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/find_masks.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/find_masks.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..115c1dcebeada61cce3ba903aa79e3db082cfb01 Binary files /dev/null and b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/find_masks.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/infer_controlnet.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/infer_controlnet.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..42f80da35807310b7344346199516bc78abeaf51 Binary files /dev/null and b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/infer_controlnet.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/infer_testV2_controlnet.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/infer_testV2_controlnet.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1a6e0957cb883a4c3c995a4709d7d740764a0534 Binary files /dev/null and b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/infer_testV2_controlnet.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/infer_test_controlnet.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/infer_test_controlnet.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..50f3e896a0bbc275efcda131016f5c85a22b309d Binary files /dev/null and b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/infer_test_controlnet.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/inference.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/inference.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..850ae937849d3771f54288630ccf38d476f722f9 Binary files /dev/null and b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/inference.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/quality_check.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/quality_check.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..09b8912c8cecf3d089bf19de348d31eed4b38232 Binary files /dev/null and b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/quality_check.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/rectified_flow.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/rectified_flow.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..abc44bf5c1f4eac3090dad3ce95cf2694c7e43c1 Binary files /dev/null and b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/rectified_flow.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/sample.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/sample.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6fabbbc06510520fc02060fccb40d32ede45b758 Binary files /dev/null and b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/sample.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/scheduler.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/scheduler.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ebb02e92296f32e09cd5d36be22abf88e0dbcd8f Binary files /dev/null and b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/scheduler.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/train_controlnet.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/train_controlnet.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b1ccac8c5556fcba53c7a50891412aa7abaa757a Binary files /dev/null and b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/train_controlnet.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/transforms.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/transforms.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1058550bc7c668220c38644bc018efce5ed1e4ec Binary files /dev/null and b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/transforms.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/utils.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9e9e267b3e8a6b7bcc396c0a17f5d207a9ea12da Binary files /dev/null and b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/utils.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/utils_plot.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/utils_plot.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..956012164f7101551873b626ff84242bd95318e1 Binary files /dev/null and b/itrialspace/src/itrialspace/synthesis/scripts/__pycache__/utils_plot.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/synthesis/scripts/augmentation.py b/itrialspace/src/itrialspace/synthesis/scripts/augmentation.py new file mode 100644 index 0000000000000000000000000000000000000000..ceef69eaa41afa6d63299bdcf5322880f2910b91 --- /dev/null +++ b/itrialspace/src/itrialspace/synthesis/scripts/augmentation.py @@ -0,0 +1,399 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import numpy as np +import torch +import torch.nn.functional as F +from monai.transforms import Rand3DElastic, RandAffine, RandZoom +from monai.utils import ensure_tuple_rep + + +def erode3d(input_tensor, erosion=3): + # Define the structuring element + erosion = ensure_tuple_rep(erosion, 3) + structuring_element = torch.ones(1, 1, erosion[0], erosion[1], erosion[2]).to( + input_tensor.device + ) + + # Pad the input tensor to handle border pixels + input_padded = F.pad( + input_tensor.float().unsqueeze(0).unsqueeze(0), + ( + erosion[0] // 2, + erosion[0] // 2, + erosion[1] // 2, + erosion[1] // 2, + erosion[2] // 2, + erosion[2] // 2, + ), + mode="constant", + value=1.0, + ) + + # Apply erosion operation + output = F.conv3d(input_padded, structuring_element, padding=0) + + # Set output values based on the minimum value within the structuring element + output = torch.where(output == torch.sum(structuring_element), 1.0, 0.0) + + return output.squeeze(0).squeeze(0) + + +def dilate3d(input_tensor, erosion=3): + # Define the structuring element + erosion = ensure_tuple_rep(erosion, 3) + structuring_element = torch.ones(1, 1, erosion[0], erosion[1], erosion[2]).to( + input_tensor.device + ) + + # Pad the input tensor to handle border pixels + input_padded = F.pad( + input_tensor.float().unsqueeze(0).unsqueeze(0), + ( + erosion[0] // 2, + erosion[0] // 2, + erosion[1] // 2, + erosion[1] // 2, + erosion[2] // 2, + erosion[2] // 2, + ), + mode="constant", + value=1.0, + ) + + # Apply erosion operation + output = F.conv3d(input_padded, structuring_element, padding=0) + + # Set output values based on the minimum value within the structuring element + output = torch.where(output > 0, 1.0, 0.0) + + return output.squeeze(0).squeeze(0) + + +def augmentation_tumor_bone(pt_nda, output_size, random_seed=None): + volume = pt_nda.squeeze(0) + real_l_volume_ = torch.zeros_like(volume) + real_l_volume_[volume == 128] = 1 + real_l_volume_ = real_l_volume_.to(torch.uint8) + + elastic = RandAffine( + mode="nearest", + prob=1.0, + translate_range=(5, 5, 0), + rotate_range=(0, 0, 0.1), + scale_range=(0.15, 0.15, 0), + padding_mode="zeros", + ) + elastic.set_random_state(seed=random_seed) + + tumor_szie = torch.sum((real_l_volume_ > 0).float()) + ########################### + # remove pred in pseudo_label in real lesion region + volume[real_l_volume_ > 0] = 200 + ########################### + if tumor_szie > 0: + # get organ mask + organ_mask = ( + torch.logical_and(33 <= volume, volume <= 56).float() + + torch.logical_and(63 <= volume, volume <= 97).float() + + (volume == 127).float() + + (volume == 114).float() + + real_l_volume_ + ) + organ_mask = (organ_mask > 0).float() + cnt = 0 + while True: + threshold = 0.8 if cnt < 40 else 0.75 + real_l_volume = real_l_volume_ + # random distor mask + distored_mask = elastic( + (real_l_volume > 0).cuda(), spatial_size=tuple(output_size) + ).as_tensor() + real_l_volume = distored_mask * organ_mask + cnt += 1 + print(torch.sum(real_l_volume), "|", tumor_szie * threshold) + if torch.sum(real_l_volume) >= tumor_szie * threshold: + real_l_volume = dilate3d(real_l_volume.squeeze(0), erosion=5) + real_l_volume = erode3d(real_l_volume, erosion=5).unsqueeze(0).to(torch.uint8) + break + else: + real_l_volume = real_l_volume_ + + volume[real_l_volume == 1] = 128 + + pt_nda = volume.unsqueeze(0) + return pt_nda + + +def augmentation_tumor_liver(pt_nda, output_size, random_seed=None): + volume = pt_nda.squeeze(0) + real_l_volume_ = torch.zeros_like(volume) + real_l_volume_[volume == 1] = 1 + real_l_volume_[volume == 26] = 2 + real_l_volume_ = real_l_volume_.to(torch.uint8) + + elastic = Rand3DElastic( + mode="nearest", + prob=1.0, + sigma_range=(5, 8), + magnitude_range=(100, 200), + translate_range=(10, 10, 10), + rotate_range=(np.pi / 36, np.pi / 36, np.pi / 36), + scale_range=(0.2, 0.2, 0.2), + padding_mode="zeros", + ) + elastic.set_random_state(seed=random_seed) + + tumor_szie = torch.sum(real_l_volume_ == 2) + ########################### + # remove pred organ labels + volume[volume == 1] = 0 + volume[volume == 26] = 0 + # before move tumor maks, full the original location by organ labels + volume[real_l_volume_ == 1] = 1 + volume[real_l_volume_ == 2] = 1 + ########################### + while True: + real_l_volume = real_l_volume_ + # random distor mask + real_l_volume = elastic( + (real_l_volume == 2).cuda(), spatial_size=tuple(output_size) + ).as_tensor() + # get organ mask + organ_mask = (real_l_volume_ == 1).float() + (real_l_volume_ == 2).float() + + organ_mask = dilate3d(organ_mask.squeeze(0), erosion=5) + organ_mask = erode3d(organ_mask, erosion=5).unsqueeze(0) + real_l_volume = real_l_volume * organ_mask + print(torch.sum(real_l_volume), "|", tumor_szie * 0.80) + if torch.sum(real_l_volume) >= tumor_szie * 0.80: + real_l_volume = dilate3d(real_l_volume.squeeze(0), erosion=5) + real_l_volume = erode3d(real_l_volume, erosion=5).unsqueeze(0) + break + + volume[real_l_volume == 1] = 26 + + pt_nda = volume.unsqueeze(0) + return pt_nda + + +def augmentation_tumor_lung(pt_nda, output_size, random_seed=None): + volume = pt_nda.squeeze(0) + real_l_volume_ = torch.zeros_like(volume) + real_l_volume_[volume == 23] = 1 + real_l_volume_ = real_l_volume_.to(torch.uint8) + + elastic = Rand3DElastic( + mode="nearest", + prob=1.0, + sigma_range=(5, 8), + magnitude_range=(100, 200), + translate_range=(20, 20, 20), + rotate_range=(np.pi / 36, np.pi / 36, np.pi), + scale_range=(0.15, 0.15, 0.15), + padding_mode="zeros", + ) + elastic.set_random_state(seed=random_seed) + + tumor_szie = torch.sum(real_l_volume_) + # before move lung tumor maks, full the original location by lung labels + new_real_l_volume_ = dilate3d(real_l_volume_.squeeze(0), erosion=3) + new_real_l_volume_ = new_real_l_volume_.unsqueeze(0) + new_real_l_volume_[real_l_volume_ > 0] = 0 + new_real_l_volume_[volume < 28] = 0 + new_real_l_volume_[volume > 32] = 0 + tmp = volume[(volume * new_real_l_volume_).nonzero(as_tuple=True)].view(-1) + + mode = torch.mode(tmp, 0)[0].item() + print(mode) + assert 28 <= mode <= 32 + volume[real_l_volume_.bool()] = mode + ########################### + if tumor_szie > 0: + # aug + while True: + real_l_volume = real_l_volume_ + # random distor mask + real_l_volume = elastic(real_l_volume, spatial_size=tuple(output_size)).as_tensor() + # get lung mask v2 (133 order) + lung_mask = ( + (volume == 28).float() + + (volume == 29).float() + + (volume == 30).float() + + (volume == 31).float() + + (volume == 32).float() + ) + + lung_mask = dilate3d(lung_mask.squeeze(0), erosion=5) + lung_mask = erode3d(lung_mask, erosion=5).unsqueeze(0) + real_l_volume = real_l_volume * lung_mask + print(torch.sum(real_l_volume), "|", tumor_szie * 0.85) + if torch.sum(real_l_volume) >= tumor_szie * 0.85: + real_l_volume = dilate3d(real_l_volume.squeeze(0), erosion=5) + real_l_volume = erode3d(real_l_volume, erosion=5).unsqueeze(0).to(torch.uint8) + break + else: + real_l_volume = real_l_volume_ + + volume[real_l_volume == 1] = 23 + + pt_nda = volume.unsqueeze(0) + return pt_nda + + +def augmentation_tumor_pancreas(pt_nda, output_size, random_seed=None): + volume = pt_nda.squeeze(0) + real_l_volume_ = torch.zeros_like(volume) + real_l_volume_[volume == 4] = 1 + real_l_volume_[volume == 24] = 2 + real_l_volume_ = real_l_volume_.to(torch.uint8) + + elastic = Rand3DElastic( + mode="nearest", + prob=1.0, + sigma_range=(5, 8), + magnitude_range=(100, 200), + translate_range=(15, 15, 15), + rotate_range=(np.pi / 36, np.pi / 36, np.pi / 36), + scale_range=(0.1, 0.1, 0.1), + padding_mode="zeros", + ) + elastic.set_random_state(seed=random_seed) + + tumor_szie = torch.sum(real_l_volume_ == 2) + ########################### + # remove pred organ labels + volume[volume == 24] = 0 + volume[volume == 4] = 0 + # before move tumor maks, full the original location by organ labels + volume[real_l_volume_ == 1] = 4 + volume[real_l_volume_ == 2] = 4 + ########################### + while True: + real_l_volume = real_l_volume_ + # random distor mask + real_l_volume = elastic( + (real_l_volume == 2).cuda(), spatial_size=tuple(output_size) + ).as_tensor() + # get organ mask + organ_mask = (real_l_volume_ == 1).float() + (real_l_volume_ == 2).float() + + organ_mask = dilate3d(organ_mask.squeeze(0), erosion=5) + organ_mask = erode3d(organ_mask, erosion=5).unsqueeze(0) + real_l_volume = real_l_volume * organ_mask + print(torch.sum(real_l_volume), "|", tumor_szie * 0.80) + if torch.sum(real_l_volume) >= tumor_szie * 0.80: + real_l_volume = dilate3d(real_l_volume.squeeze(0), erosion=5) + real_l_volume = erode3d(real_l_volume, erosion=5).unsqueeze(0) + break + + volume[real_l_volume == 1] = 24 + + pt_nda = volume.unsqueeze(0) + return pt_nda + + +def augmentation_tumor_colon(pt_nda, output_size, random_seed=None): + volume = pt_nda.squeeze(0) + real_l_volume_ = torch.zeros_like(volume) + real_l_volume_[volume == 27] = 1 + real_l_volume_ = real_l_volume_.to(torch.uint8) + + elastic = Rand3DElastic( + mode="nearest", + prob=1.0, + sigma_range=(5, 8), + magnitude_range=(100, 200), + translate_range=(5, 5, 5), + rotate_range=(np.pi / 36, np.pi / 36, np.pi / 36), + scale_range=(0.1, 0.1, 0.1), + padding_mode="zeros", + ) + elastic.set_random_state(seed=random_seed) + + tumor_szie = torch.sum(real_l_volume_) + ########################### + # before move tumor maks, full the original location by organ labels + volume[real_l_volume_.bool()] = 62 + ########################### + if tumor_szie > 0: + # get organ mask + organ_mask = (volume == 62).float() + organ_mask = dilate3d(organ_mask.squeeze(0), erosion=5) + organ_mask = erode3d(organ_mask, erosion=5).unsqueeze(0) + # cnt = 0 + cnt = 0 + while True: + threshold = 0.8 + real_l_volume = real_l_volume_ + if cnt < 20: + # random distor mask + distored_mask = elastic( + (real_l_volume == 1).cuda(), spatial_size=tuple(output_size) + ).as_tensor() + real_l_volume = distored_mask * organ_mask + elif 20 <= cnt < 40: + threshold = 0.75 + else: + break + + real_l_volume = real_l_volume * organ_mask + print(torch.sum(real_l_volume), "|", tumor_szie * threshold) + cnt += 1 + if torch.sum(real_l_volume) >= tumor_szie * threshold: + real_l_volume = dilate3d(real_l_volume.squeeze(0), erosion=5) + real_l_volume = erode3d(real_l_volume, erosion=5).unsqueeze(0).to(torch.uint8) + break + else: + real_l_volume = real_l_volume_ + # break + volume[real_l_volume == 1] = 27 + + pt_nda = volume.unsqueeze(0) + return pt_nda + + +def augmentation_body(pt_nda, random_seed=None): + volume = pt_nda.squeeze(0) + + zoom = RandZoom(min_zoom=0.99, max_zoom=1.01, mode="nearest", align_corners=None, prob=1.0) + zoom.set_random_state(seed=random_seed) + + volume = zoom(volume) + + pt_nda = volume.unsqueeze(0) + return pt_nda + + +def augmentation(pt_nda, output_size, random_seed=None): + label_list = torch.unique(pt_nda) + label_list = list(label_list.cpu().numpy()) + + if 128 in label_list: + print("augmenting bone lesion/tumor") + pt_nda = augmentation_tumor_bone(pt_nda, output_size, random_seed) + elif 26 in label_list: + print("augmenting liver tumor") + pt_nda = augmentation_tumor_liver(pt_nda, output_size, random_seed) + elif 23 in label_list: + print("augmenting lung tumor") + pt_nda = augmentation_tumor_lung(pt_nda, output_size, random_seed) + elif 24 in label_list: + print("augmenting pancreas tumor") + pt_nda = augmentation_tumor_pancreas(pt_nda, output_size, random_seed) + elif 27 in label_list: + print("augmenting colon tumor") + pt_nda = augmentation_tumor_colon(pt_nda, output_size, random_seed) + else: + print("augmenting body") + pt_nda = augmentation_body(pt_nda, random_seed) + + return pt_nda diff --git a/itrialspace/src/itrialspace/synthesis/scripts/compute_fid_2-5d_ct.py b/itrialspace/src/itrialspace/synthesis/scripts/compute_fid_2-5d_ct.py new file mode 100644 index 0000000000000000000000000000000000000000..698818bf18ec9f3a757c3416c79fa2c208ef1efe --- /dev/null +++ b/itrialspace/src/itrialspace/synthesis/scripts/compute_fid_2-5d_ct.py @@ -0,0 +1,760 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at: +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, +# either express or implied. +# See the License for the specific language governing permissions +# and limitations under the License. + +""" +Compute 2.5D FID using distributed GPU processing. + +SHELL Usage Example: +------------------- + #!/bin/bash + + export CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6 + NUM_GPUS=7 + + torchrun --nproc_per_node=${NUM_GPUS} compute_fid_2-5d_ct.py \ + --model_name "radimagenet_resnet50" \ + --real_dataset_root "path/to/datasetA" \ + --real_filelist "path/to/filelistA.txt" \ + --real_features_dir "datasetA" \ + --synth_dataset_root "path/to/datasetB" \ + --synth_filelist "path/to/filelistB.txt" \ + --synth_features_dir "datasetB" \ + --enable_center_slices_ratio 0.4 \ + --enable_padding True \ + --enable_center_cropping True \ + --enable_resampling_spacing "1.0x1.0x1.0" \ + --ignore_existing True \ + --num_images 100 \ + --output_root "./features/features-512x512x512" \ + --target_shape "512x512x512" + +This script loads two datasets (real vs. synthetic) in 3D medical format (NIfTI) +and extracts feature maps via a 2.5D approach. It then computes the Frechet +Inception Distance (FID) across three orthogonal planes. Data parallelism +is implemented using torch.distributed with an NCCL backend. + +Function Arguments (main): +-------------------------- + real_dataset_root (str): + Root folder for the real dataset. + + real_filelist (str): + Text file listing 3D images for the real dataset. + + real_features_dir (str): + Subdirectory (under `output_root`) in which to store feature files + extracted from the real dataset. + + synth_dataset_root (str): + Root folder for the synthetic dataset. + + synth_filelist (str): + Text file listing 3D images for the synthetic dataset. + + synth_features_dir (str): + Subdirectory (under `output_root`) in which to store feature files + extracted from the synthetic dataset. + + enable_center_slices_ratio (float or None): + - If not None, only slices around the specified center ratio will be used + (analogous to "enable_center_slices=True" with that ratio). + - If None, no center-slice selection is performed + (analogous to "enable_center_slices=False"). + + enable_padding (bool): + Whether to pad images to `target_shape`. + + enable_center_cropping (bool): + Whether to center-crop images to `target_shape`. + + enable_resampling_spacing (str or None): + - If not None, resample images to the specified voxel spacing (e.g. "1.0x1.0x1.0") + (analogous to "enable_resampling=True" with that spacing). + - If None, resampling is skipped + (analogous to "enable_resampling=False"). + + ignore_existing (bool): + If True, ignore any existing .pt feature files and force re-extraction. + + model_name (str): + Model identifier. Typically "radimagenet_resnet50" or "squeezenet1_1". + + num_images (int): + Max number of images to process from each dataset (truncate if more are present). + + output_root (str): + Folder where extracted .pt feature files, logs, and results are saved. + + target_shape (str): + Target shape as "XxYxZ" for padding, cropping, or resampling operations. +""" + +from __future__ import annotations + +import logging +import os +import re +import sys +from datetime import timedelta +from pathlib import Path + +import fire +import monai +import torch +import torch.distributed as dist +import torch.nn.functional as F +from monai.metrics.fid import FIDMetric +from monai.transforms import Compose + +# ------------------------------------------------------------------------------ +# Create logger +# ------------------------------------------------------------------------------ +logger = logging.getLogger("fid_2-5d_ct") +if not logger.handlers: + # Configure logger only if it has no handlers (avoid reconfiguring in multi-rank scenarios) + logging.basicConfig(stream=sys.stdout, level=logging.INFO) +logger.setLevel(logging.INFO) + + +def drop_empty_slice(slices, empty_threshold: float): + """ + Decide which 2D slices to keep by checking if their maximum intensity + is below a certain threshold. + + Args: + slices (tuple or list of Tensors): Each element is (B, C, H, W). + empty_threshold (float): If the slice's maximum value is below this threshold, + it is considered "empty". + + Returns: + list[bool]: A list of booleans indicating for each slice whether to keep it. + """ + outputs = [] + n_drop = 0 + for s in slices: + largest_unique = torch.max(torch.unique(s)) + if largest_unique < empty_threshold: + outputs.append(False) + n_drop += 1 + else: + outputs.append(True) + + logger.info(f"Empty slice drop rate {round((n_drop/len(slices))*100,1)}%") + return outputs + + +def subtract_mean(x: torch.Tensor) -> torch.Tensor: + """ + Subtract per-channel means (ImageNet-like: [0.406, 0.456, 0.485]) + from the input 4D or 5D tensor. Expects channels in the first dimension + after the batch dimension: (B, C, H, W) or (B, C, H, W, D). + """ + mean = [0.406, 0.456, 0.485] + x[:, 0, ...] -= mean[0] + x[:, 1, ...] -= mean[1] + x[:, 2, ...] -= mean[2] + return x + + +def spatial_average(x: torch.Tensor, keepdim: bool = True) -> torch.Tensor: + """ + Average out the spatial dimensions of a tensor, preserving or removing them + according to `keepdim`. This is used to produce a 1D feature vector + out of a feature map. + + Args: + x (torch.Tensor): Input tensor (B, C, H, W, ...) or (B, C, H, W). + keepdim (bool): Whether to keep dimension or not after averaging. + + Returns: + torch.Tensor: Tensor with reduced spatial dimensions. + """ + dim = len(x.shape) + # 2D -> no average + if dim == 2: + return x + # 3D -> average over last dim + if dim == 3: + return x.mean([2], keepdim=keepdim) + # 4D -> average over H,W + if dim == 4: + return x.mean([2, 3], keepdim=keepdim) + # 5D -> average over H,W,D + if dim == 5: + return x.mean([2, 3, 4], keepdim=keepdim) + return x + + +def medicalnet_intensity_normalisation(volume: torch.Tensor) -> torch.Tensor: + """ + Intensity normalization approach from MedicalNet: + (volume - mean) / (std + 1e-5) across spatial dims. + Expects (B, C, H, W) or (B, C, H, W, D). + """ + dim = len(volume.shape) + if dim == 4: + mean = volume.mean([2, 3], keepdim=True) + std = volume.std([2, 3], keepdim=True) + elif dim == 5: + mean = volume.mean([2, 3, 4], keepdim=True) + std = volume.std([2, 3, 4], keepdim=True) + else: + return volume + return (volume - mean) / (std + 1e-5) + + +def radimagenet_intensity_normalisation(volume: torch.Tensor, norm2d: bool = False) -> torch.Tensor: + """ + Intensity normalization for radimagenet_resnet. Optionally normalizes each 2D slice individually. + + Args: + volume (torch.Tensor): Input (B, C, H, W) or (B, C, H, W, D). + norm2d (bool): If True, normalizes each (H,W) slice to [0,1], then subtracts the ImageNet mean. + """ + logger.info(f"norm2d: {norm2d}") + dim = len(volume.shape) + # If norm2d is True, only meaningful for 4D data (B, C, H, W): + if dim == 4 and norm2d: + max2d, _ = torch.max(volume, dim=2, keepdim=True) + max2d, _ = torch.max(max2d, dim=3, keepdim=True) + min2d, _ = torch.min(volume, dim=2, keepdim=True) + min2d, _ = torch.min(min2d, dim=3, keepdim=True) + # Scale each slice to 0..1 + volume = (volume - min2d) / (max2d - min2d + 1e-10) + # Subtract channel mean + return subtract_mean(volume) + elif dim == 4: + # 4D but no per-slice normalization + max3d = torch.max(volume) + min3d = torch.min(volume) + volume = (volume - min3d) / (max3d - min3d + 1e-10) + return subtract_mean(volume) + # Fallback for e.g. 5D data is simply a min-max over entire volume + if dim == 5: + maxval = torch.max(volume) + minval = torch.min(volume) + volume = (volume - minval) / (maxval - minval + 1e-10) + return subtract_mean(volume) + return volume + + +def get_features_2p5d( + image: torch.Tensor, + feature_network: torch.nn.Module, + center_slices: bool = False, + center_slices_ratio: float = 1.0, + sample_every_k: int = 1, + xy_only: bool = True, + drop_empty: bool = False, + empty_threshold: float = -700, +) -> tuple[torch.Tensor | None, torch.Tensor | None, torch.Tensor | None]: + """ + Extract 2.5D features from a 3D image by slicing it along XY, YZ, ZX planes. + + Args: + image (torch.Tensor): Input 5D tensor in shape (B, C, H, W, D). + feature_network (torch.nn.Module): Model that processes 2D slices (C,H,W). + center_slices (bool): Whether to slice only the center portion of each axis. + center_slices_ratio (float): Ratio of slices to keep in the center if `center_slices` is True. + sample_every_k (int): Downsampling factor along each axis when slicing. + xy_only (bool): If True, return only the XY-plane features. + drop_empty (bool): Drop slices that are deemed "empty" below `empty_threshold`. + empty_threshold (float): Threshold to decide emptiness of slices. + + Returns: + tuple of torch.Tensor or None: (XY_features, YZ_features, ZX_features). + """ + logger.info(f"center_slices: {center_slices}, ratio: {center_slices_ratio}") + + # If there's only 1 channel, replicate to 3 channels + if image.shape[1] == 1: + image = image.repeat(1, 3, 1, 1, 1) + + # Convert from 'RGB'→(R,G,B) to (B,G,R) + image = image[:, [2, 1, 0], ...] + + B, C, H, W, D = image.size() + with torch.no_grad(): + # ---------------------- XY-plane slicing along D ---------------------- + if center_slices: + start_d = int((1.0 - center_slices_ratio) / 2.0 * D) + end_d = int((1.0 + center_slices_ratio) / 2.0 * D) + slices = torch.unbind(image[:, :, :, :, start_d:end_d:sample_every_k], dim=-1) + else: + slices = torch.unbind(image, dim=-1) + + if drop_empty: + mapping_index = drop_empty_slice(slices, empty_threshold) + else: + mapping_index = [True for _ in range(len(slices))] + + images_2d = torch.cat(slices, dim=0) + images_2d = radimagenet_intensity_normalisation(images_2d) + images_2d = images_2d[mapping_index] + + feature_image_xy = feature_network.forward(images_2d) + feature_image_xy = spatial_average(feature_image_xy, keepdim=False) + if xy_only: + return feature_image_xy, None, None + + # ---------------------- YZ-plane slicing along H ---------------------- + if center_slices: + start_h = int((1.0 - center_slices_ratio) / 2.0 * H) + end_h = int((1.0 + center_slices_ratio) / 2.0 * H) + slices = torch.unbind(image[:, :, start_h:end_h:sample_every_k, :, :], dim=2) + else: + slices = torch.unbind(image, dim=2) + + if drop_empty: + mapping_index = drop_empty_slice(slices, empty_threshold) + else: + mapping_index = [True for _ in range(len(slices))] + + images_2d = torch.cat(slices, dim=0) + images_2d = radimagenet_intensity_normalisation(images_2d) + images_2d = images_2d[mapping_index] + + feature_image_yz = feature_network.forward(images_2d) + feature_image_yz = spatial_average(feature_image_yz, keepdim=False) + + # ---------------------- ZX-plane slicing along W ---------------------- + if center_slices: + start_w = int((1.0 - center_slices_ratio) / 2.0 * W) + end_w = int((1.0 + center_slices_ratio) / 2.0 * W) + slices = torch.unbind(image[:, :, :, start_w:end_w:sample_every_k, :], dim=3) + else: + slices = torch.unbind(image, dim=3) + + if drop_empty: + mapping_index = drop_empty_slice(slices, empty_threshold) + else: + mapping_index = [True for _ in range(len(slices))] + + images_2d = torch.cat(slices, dim=0) + images_2d = radimagenet_intensity_normalisation(images_2d) + images_2d = images_2d[mapping_index] + + feature_image_zx = feature_network.forward(images_2d) + feature_image_zx = spatial_average(feature_image_zx, keepdim=False) + + return feature_image_xy, feature_image_yz, feature_image_zx + + +def pad_to_max_size( + tensor: torch.Tensor, max_size: int, padding_value: float = 0.0 +) -> torch.Tensor: + """ + Zero-pad a 2D feature map or other tensor along the first dimension to match a specified size. + + Args: + tensor (torch.Tensor): The feature tensor to pad. + max_size (int): Desired size along the first dimension. + padding_value (float): Value to fill during padding. + + Returns: + torch.Tensor: Padded tensor matching `max_size` along dim=0. + """ + pad_size = [0, 0] * (len(tensor.shape) - 1) + [0, max_size - tensor.shape[0]] + return F.pad(tensor, pad_size, "constant", padding_value) + + +def main( + real_dataset_root: str = "path/to/datasetA", + real_filelist: str = "path/to/filelistA.txt", + real_features_dir: str = "datasetA", + synth_dataset_root: str = "path/to/datasetB", + synth_filelist: str = "path/to/filelistB.txt", + synth_features_dir: str = "datasetB", + enable_center_slices_ratio: float = None, + enable_padding: bool = True, + enable_center_cropping: bool = True, + enable_resampling_spacing: str = None, + ignore_existing: bool = False, + model_name: str = "radimagenet_resnet50", + num_images: int = 100, + output_root: str = "./features/features-512x512x512", + target_shape: str = "512x512x512", +): + """ + Compute 2.5D FID using distributed GPU processing. + + This function loads two datasets (real vs. synthetic) in 3D medical format (NIfTI) + and extracts feature maps via a 2.5D approach, then computes the Frechet Inception + Distance (FID) across three orthogonal planes. Data parallelism is implemented + using torch.distributed with an NCCL backend. + + Args: + real_dataset_root (str): + Root folder for the real dataset. + real_filelist (str): + Path to a text file listing 3D images (e.g., NIfTI files) for the real dataset. + Each line in this file should contain a relative path (or filename) to a NIfTI file. + For example, your "real_filelist.txt" could look like: + case001.nii.gz + case002.nii.gz + case003.nii.gz + ... + These entries will be appended to `real_dataset_root`. + real_features_dir (str): + Name of the directory under `output_root` in which to store + extracted features for the real dataset. + + synth_dataset_root (str): + Root folder for the synthetic dataset. + synth_filelist (str): + Path to a text file listing 3D images (e.g., NIfTI files) for the synthetic dataset. + The format is the same as the real dataset file list, for example: + synth_case001.nii.gz + synth_case002.nii.gz + synth_case003.nii.gz + ... + These entries will be appended to `synth_dataset_root`. + synth_features_dir (str): + Name of the directory under `output_root` in which to store + extracted features for the synthetic dataset. + + enable_center_slices_ratio (float or None): + - If not None, only slices around the specified center ratio are used. + (similar to "enable_center_slices=True" with that ratio in an earlier script). + - If None, no center-slice selection is performed + (similar to "enable_center_slices=False"). + + enable_padding (bool): + Whether to pad images to `target_shape`. + + enable_center_cropping (bool): + Whether to center-crop images to `target_shape`. + + enable_resampling_spacing (str or None): + - If not None, resample images to this voxel spacing (e.g. "1.0x1.0x1.0") + (similar to "enable_resampling=True" with that spacing). + - If None, skip resampling (similar to "enable_resampling=False"). + + ignore_existing (bool): + If True, ignore any existing .pt feature files and force re-computation. + + model_name (str): + Model identifier. Typically "radimagenet_resnet50" or "squeezenet1_1". + + num_images (int): + Maximum number of images to load from each dataset (truncate if more are present). + + output_root (str): + Parent folder where extracted .pt files and logs will be saved. + + target_shape (str): + Target shape, e.g. "512x512x512", for padding, cropping, or resampling operations. + + Returns: + None + """ + # ------------------------------------------------------------------------- + # Initialize Process Group (Distributed) + # ------------------------------------------------------------------------- + dist.init_process_group(backend="nccl", init_method="env://", timeout=timedelta(seconds=7200)) + + local_rank = int(os.environ["LOCAL_RANK"]) + world_size = int(dist.get_world_size()) + device = torch.device("cuda", local_rank) + torch.cuda.set_device(device) + logger.info(f"[INFO] Running process on {device} of total {world_size} ranks.") + + # Convert potential string bools to actual bools (if using Fire or similar) + if not isinstance(enable_padding, bool): + enable_padding = enable_padding.lower() == "true" + if not isinstance(enable_center_cropping, bool): + enable_center_cropping = enable_center_cropping.lower() == "true" + if not isinstance(ignore_existing, bool): + ignore_existing = ignore_existing.lower() == "true" + + # Merge logic for center slices + enable_center_slices = enable_center_slices_ratio is not None + + # Merge logic for resampling + enable_resampling = enable_resampling_spacing is not None + + # Print out some flags on rank 0 + if local_rank == 0: + logger.info(f"Real dataset root: {real_dataset_root}") + logger.info(f"Synth dataset root: {synth_dataset_root}") + logger.info(f"enable_center_slices_ratio: {enable_center_slices_ratio}") + logger.info(f"enable_center_slices: {enable_center_slices}") + logger.info(f"enable_padding: {enable_padding}") + logger.info(f"enable_center_cropping: {enable_center_cropping}") + logger.info(f"enable_resampling_spacing: {enable_resampling_spacing}") + logger.info(f"enable_resampling: {enable_resampling}") + logger.info(f"ignore_existing: {ignore_existing}") + + # ------------------------------------------------------------------------- + # Load feature extraction model + # ------------------------------------------------------------------------- + if model_name == "radimagenet_resnet50": + feature_network = torch.hub.load( + "Warvito/radimagenet-models", + model="radimagenet_resnet50", + verbose=True, + trust_repo=True, + ) + suffix = "radimagenet_resnet50" + else: + import torchvision + + feature_network = torchvision.models.squeezenet1_1(pretrained=True) + suffix = "squeezenet1_1" + + feature_network.to(device) + feature_network.eval() + + # ------------------------------------------------------------------------- + # Parse shape/spacings + # ------------------------------------------------------------------------- + t_shape = [int(x) for x in target_shape.split("x")] + target_shape_tuple = tuple(t_shape) + + # If not None, parse the resampling spacing + if enable_resampling: + rs_spacing = [float(x) for x in enable_resampling_spacing.split("x")] + rs_spacing_tuple = tuple(rs_spacing) + if local_rank == 0: + logger.info(f"Resampling spacing: {rs_spacing_tuple}") + else: + rs_spacing_tuple = (1.0, 1.0, 1.0) + + # Use the ratio if provided, otherwise 1.0 + center_slices_ratio_final = enable_center_slices_ratio if enable_center_slices else 1.0 + if local_rank == 0: + logger.info(f"center_slices_ratio: {center_slices_ratio_final}") + + # ------------------------------------------------------------------------- + # Prepare Real Dataset + # ------------------------------------------------------------------------- + output_root_real = os.path.join(output_root, real_features_dir) + with open(real_filelist, "r") as rf: + real_lines = [l.strip() for l in rf.readlines()] + real_lines.sort() + real_lines = real_lines[:num_images] + + real_filenames = [{"image": os.path.join(real_dataset_root, f)} for f in real_lines] + real_filenames = monai.data.partition_dataset( + data=real_filenames, shuffle=False, num_partitions=world_size, even_divisible=False + )[local_rank] + + # ------------------------------------------------------------------------- + # Prepare Synthetic Dataset + # ------------------------------------------------------------------------- + output_root_synth = os.path.join(output_root, synth_features_dir) + with open(synth_filelist, "r") as sf: + synth_lines = [l.strip() for l in sf.readlines()] + synth_lines.sort() + synth_lines = synth_lines[:num_images] + + synth_filenames = [{"image": os.path.join(synth_dataset_root, f)} for f in synth_lines] + synth_filenames = monai.data.partition_dataset( + data=synth_filenames, shuffle=False, num_partitions=world_size, even_divisible=False + )[local_rank] + + # ------------------------------------------------------------------------- + # Build MONAI transforms + # ------------------------------------------------------------------------- + transform_list = [ + monai.transforms.LoadImaged(keys=["image"]), + monai.transforms.EnsureChannelFirstd(keys=["image"]), + monai.transforms.Orientationd(keys=["image"], axcodes="RAS"), + ] + + if enable_resampling: + transform_list.append( + monai.transforms.Spacingd(keys=["image"], pixdim=rs_spacing_tuple, mode=["bilinear"]) + ) + + if enable_padding: + transform_list.append( + monai.transforms.SpatialPadd( + keys=["image"], spatial_size=target_shape_tuple, mode="constant", value=-1000 + ) + ) + + if enable_center_cropping: + transform_list.append( + monai.transforms.CenterSpatialCropd(keys=["image"], roi_size=target_shape_tuple) + ) + + transform_list.append( + monai.transforms.ScaleIntensityRanged( + keys=["image"], a_min=-1000, a_max=1000, b_min=-1000, b_max=1000, clip=True + ) + ) + transforms = Compose(transform_list) + + # ------------------------------------------------------------------------- + # Create DataLoaders + # ------------------------------------------------------------------------- + real_ds = monai.data.Dataset(data=real_filenames, transform=transforms) + real_loader = monai.data.DataLoader(real_ds, num_workers=6, batch_size=1, shuffle=False) + + synth_ds = monai.data.Dataset(data=synth_filenames, transform=transforms) + synth_loader = monai.data.DataLoader(synth_ds, num_workers=6, batch_size=1, shuffle=False) + + # ------------------------------------------------------------------------- + # Extract features for Real Dataset + # ------------------------------------------------------------------------- + real_features_xy, real_features_yz, real_features_zx = [], [], [] + for idx, batch_data in enumerate(real_loader, start=1): + img = batch_data["image"].to(device) + fn = img.meta["filename_or_obj"][0] + logger.info(f"[Rank {local_rank}] Real data {idx}/{len(real_filenames)}: {fn}") + + out_fp = fn.replace(real_dataset_root, output_root_real).replace(".nii.gz", ".pt") + out_fp = Path(out_fp) + out_fp.parent.mkdir(parents=True, exist_ok=True) + + if (not ignore_existing) and os.path.isfile(out_fp): + feats = torch.load(out_fp, weights_only=True) + else: + img_t = img.as_tensor() + logger.info(f"image shape: {tuple(img_t.shape)}") + + feats = get_features_2p5d( + img_t, + feature_network, + center_slices=enable_center_slices, + center_slices_ratio=center_slices_ratio_final, + xy_only=False, + ) + logger.info(f"feats shapes: {feats[0].shape}, {feats[1].shape}, {feats[2].shape}") + torch.save(feats, out_fp) + + real_features_xy.append(feats[0]) + real_features_yz.append(feats[1]) + real_features_zx.append(feats[2]) + + real_features_xy = torch.vstack(real_features_xy) + real_features_yz = torch.vstack(real_features_yz) + real_features_zx = torch.vstack(real_features_zx) + logger.info( + f"Real feature shapes: {real_features_xy.shape}, " + f"{real_features_yz.shape}, {real_features_zx.shape}" + ) + + # ------------------------------------------------------------------------- + # Extract features for Synthetic Dataset + # ------------------------------------------------------------------------- + synth_features_xy, synth_features_yz, synth_features_zx = [], [], [] + for idx, batch_data in enumerate(synth_loader, start=1): + img = batch_data["image"].to(device) + fn = img.meta["filename_or_obj"][0] + logger.info(f"[Rank {local_rank}] Synth data {idx}/{len(synth_filenames)}: {fn}") + + out_fp = fn.replace(synth_dataset_root, output_root_synth).replace(".nii.gz", ".pt") + out_fp = Path(out_fp) + out_fp.parent.mkdir(parents=True, exist_ok=True) + + if (not ignore_existing) and os.path.isfile(out_fp): + feats = torch.load(out_fp, weights_only=True) + else: + img_t = img.as_tensor() + logger.info(f"image shape: {tuple(img_t.shape)}") + + feats = get_features_2p5d( + img_t, + feature_network, + center_slices=enable_center_slices, + center_slices_ratio=center_slices_ratio_final, + xy_only=False, + ) + logger.info(f"feats shapes: {feats[0].shape}, {feats[1].shape}, {feats[2].shape}") + torch.save(feats, out_fp) + + synth_features_xy.append(feats[0]) + synth_features_yz.append(feats[1]) + synth_features_zx.append(feats[2]) + + synth_features_xy = torch.vstack(synth_features_xy) + synth_features_yz = torch.vstack(synth_features_yz) + synth_features_zx = torch.vstack(synth_features_zx) + logger.info( + f"Synth feature shapes: {synth_features_xy.shape}, " + f"{synth_features_yz.shape}, {synth_features_zx.shape}" + ) + + # ------------------------------------------------------------------------- + # All-reduce / gather features across ranks + # ------------------------------------------------------------------------- + features = [ + real_features_xy, + real_features_yz, + real_features_zx, + synth_features_xy, + synth_features_yz, + synth_features_zx, + ] + + # 1) Gather local feature sizes across ranks + local_sizes = [] + for ft_idx in range(len(features)): + local_size = torch.tensor([features[ft_idx].shape[0]], dtype=torch.int64, device=device) + local_sizes.append(local_size) + + all_sizes = [] + for ft_idx in range(len(features)): + rank_sizes = [ + torch.tensor([0], dtype=torch.int64, device=device) for _ in range(world_size) + ] + dist.all_gather(rank_sizes, local_sizes[ft_idx]) + all_sizes.append(rank_sizes) + + # 2) Pad and gather all features + all_tensors_list = [] + for ft_idx, ft in enumerate(features): + max_size = max(all_sizes[ft_idx]).item() + ft_padded = pad_to_max_size(ft, max_size) + + gather_list = [torch.empty_like(ft_padded) for _ in range(world_size)] + dist.all_gather(gather_list, ft_padded) + + # Trim each gather back to the real size + for rk in range(world_size): + gather_list[rk] = gather_list[rk][: all_sizes[ft_idx][rk], :] + + all_tensors_list.append(gather_list) + + # On rank 0, compute FID + if local_rank == 0: + real_xy = torch.vstack(all_tensors_list[0]) + real_yz = torch.vstack(all_tensors_list[1]) + real_zx = torch.vstack(all_tensors_list[2]) + + synth_xy = torch.vstack(all_tensors_list[3]) + synth_yz = torch.vstack(all_tensors_list[4]) + synth_zx = torch.vstack(all_tensors_list[5]) + + logger.info(f"Final Real shapes: {real_xy.shape}, {real_yz.shape}, {real_zx.shape}") + logger.info(f"Final Synth shapes: {synth_xy.shape}, {synth_yz.shape}, {synth_zx.shape}") + + fid = FIDMetric() + logger.info(f"Computing FID for: {output_root_real} | {output_root_synth}") + fid_res_xy = fid(synth_xy, real_xy) + fid_res_yz = fid(synth_yz, real_yz) + fid_res_zx = fid(synth_zx, real_zx) + + logger.info(f"FID XY: {fid_res_xy}") + logger.info(f"FID YZ: {fid_res_yz}") + logger.info(f"FID ZX: {fid_res_zx}") + fid_avg = (fid_res_xy + fid_res_yz + fid_res_zx) / 3.0 + logger.info(f"FID Avg: {fid_avg}") + + dist.destroy_process_group() + + +if __name__ == "__main__": + fire.Fire(main) diff --git a/itrialspace/src/itrialspace/synthesis/scripts/diff_model_create_training_data.py b/itrialspace/src/itrialspace/synthesis/scripts/diff_model_create_training_data.py new file mode 100644 index 0000000000000000000000000000000000000000..da515aef0c853e4cac886940ecf0251046259270 --- /dev/null +++ b/itrialspace/src/itrialspace/synthesis/scripts/diff_model_create_training_data.py @@ -0,0 +1,242 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import argparse +import json +import logging +import os +from pathlib import Path + +import monai +import nibabel as nib +import numpy as np +import torch +import torch.distributed as dist +from monai.transforms import Compose +from monai.utils import set_determinism + +from .diff_model_setting import initialize_distributed, load_config, setup_logging +from .utils import define_instance + +# Set the random seed for reproducibility +set_determinism(seed=0) + + +def create_transforms(dim: tuple = None) -> Compose: + """ + Create a set of MONAI transforms for preprocessing. + + Args: + dim (tuple, optional): New dimensions for resizing. Defaults to None. + + Returns: + Compose: Composed MONAI transforms. + """ + if dim: + return Compose( + [ + monai.transforms.LoadImaged(keys="image"), + monai.transforms.EnsureChannelFirstd(keys="image"), + monai.transforms.Orientationd(keys="image", axcodes="RAS"), + monai.transforms.EnsureTyped(keys="image", dtype=torch.float32), + monai.transforms.ScaleIntensityRanged( + keys="image", a_min=-1000, a_max=1000, b_min=0, b_max=1, clip=True + ), + monai.transforms.Resized(keys="image", spatial_size=dim, mode="trilinear"), + ] + ) + else: + return Compose( + [ + monai.transforms.LoadImaged(keys="image"), + monai.transforms.EnsureChannelFirstd(keys="image"), + monai.transforms.Orientationd(keys="image", axcodes="RAS"), + ] + ) + + +def round_number(number: int, base_number: int = 128) -> int: + """ + Round the number to the nearest multiple of the base number, with a minimum value of the base number. + + Args: + number (int): Number to be rounded. + base_number (int): Number to be common divisor. + + Returns: + int: Rounded number. + """ + new_number = max(round(float(number) / float(base_number)), 1.0) * float(base_number) + return int(new_number) + + +def load_filenames(data_list_path: str) -> list: + """ + Load filenames from the JSON data list. + + Args: + data_list_path (str): Path to the JSON data list file. + + Returns: + list: List of filenames. + """ + with open(data_list_path, "r") as file: + json_data = json.load(file) + filenames_raw = json_data["training"] + return [_item["image"] for _item in filenames_raw] + + +def process_file( + filepath: str, + args: argparse.Namespace, + autoencoder: torch.nn.Module, + device: torch.device, + plain_transforms: Compose, + new_transforms: Compose, + logger: logging.Logger, +) -> None: + """ + Process a single file to create training data. + + Args: + filepath (str): Path to the file to be processed. + args (argparse.Namespace): Configuration arguments. + autoencoder (torch.nn.Module): Autoencoder model. + device (torch.device): Device to process the file on. + plain_transforms (Compose): Plain transforms. + new_transforms (Compose): New transforms. + logger (logging.Logger): Logger for logging information. + """ + out_filename_base = filepath.replace(".gz", "").replace(".nii", "") + out_filename_base = os.path.join(args.embedding_base_dir, out_filename_base) + out_filename = out_filename_base + "_emb.nii.gz" + + if os.path.isfile(out_filename): + return + + test_data = {"image": os.path.join(args.data_base_dir, filepath)} + transformed_data = plain_transforms(test_data) + nda = transformed_data["image"] + + dim = [int(nda.meta["dim"][_i]) for _i in range(1, 4)] + spacing = [float(nda.meta["pixdim"][_i]) for _i in range(1, 4)] + + logger.info(f"old dim: {dim}, old spacing: {spacing}") + + new_data = new_transforms(test_data) + nda_image = new_data["image"] + + new_affine = nda_image.meta["affine"].numpy() + nda_image = nda_image.numpy().squeeze() + + logger.info(f"new dim: {nda_image.shape}, new affine: {new_affine}") + + try: + out_path = Path(out_filename) + out_path.parent.mkdir(parents=True, exist_ok=True) + logger.info(f"out_filename: {out_filename}") + + with torch.amp.autocast("cuda"): + pt_nda = torch.from_numpy(nda_image).float().to(device).unsqueeze(0).unsqueeze(0) + z = autoencoder.encode_stage_2_inputs(pt_nda) + logger.info(f"z: {z.size()}, {z.dtype}") + + out_nda = z.squeeze().cpu().detach().numpy().transpose(1, 2, 3, 0) + out_img = nib.Nifti1Image(np.float32(out_nda), affine=new_affine) + nib.save(out_img, out_filename) + except Exception as e: + logger.error(f"Error processing {filepath}: {e}") + + +@torch.inference_mode() +def diff_model_create_training_data( + env_config_path: str, model_config_path: str, model_def_path: str, num_gpus: int +) -> None: + """ + Create training data for the diffusion model. + + Args: + env_config_path (str): Path to the environment configuration file. + model_config_path (str): Path to the model configuration file. + model_def_path (str): Path to the model definition file. + """ + args = load_config(env_config_path, model_config_path, model_def_path) + local_rank, world_size, device = initialize_distributed(num_gpus=num_gpus) + logger = setup_logging("creating training data") + logger.info(f"Using device {device}") + + autoencoder = define_instance(args, "autoencoder_def").to(device) + try: + checkpoint_autoencoder = torch.load(args.trained_autoencoder_path, weights_only=True) + autoencoder.load_state_dict(checkpoint_autoencoder) + except Exception: + logger.error("The trained_autoencoder_path does not exist!") + + Path(args.embedding_base_dir).mkdir(parents=True, exist_ok=True) + + filenames_raw = load_filenames(args.json_data_list) + logger.info(f"filenames_raw: {filenames_raw}") + + plain_transforms = create_transforms(dim=None) + + for _iter in range(len(filenames_raw)): + if _iter % world_size != local_rank: + continue + + filepath = filenames_raw[_iter] + new_dim = tuple( + round_number( + int( + plain_transforms({"image": os.path.join(args.data_base_dir, filepath)})[ + "image" + ].meta["dim"][_i] + ) + ) + for _i in range(1, 4) + ) + new_transforms = create_transforms(new_dim) + + process_file(filepath, args, autoencoder, device, plain_transforms, new_transforms, logger) + + if dist.is_initialized(): + dist.destroy_process_group() + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Diffusion Model Training Data Creation") + parser.add_argument( + "--env_config", + type=str, + default="./configs/environment_maisi_diff_model_train.json", + help="Path to environment configuration file", + ) + parser.add_argument( + "--model_config", + type=str, + default="./configs/config_maisi_diff_model_train.json", + help="Path to model training/inference configuration", + ) + parser.add_argument( + "--model_def", + type=str, + default="./configs/config_maisi.json", + help="Path to model definition file", + ) + parser.add_argument( + "--num_gpus", type=int, default=1, help="Number of GPUs to use for distributed training" + ) + + args = parser.parse_args() + diff_model_create_training_data( + args.env_config, args.model_config, args.model_def, args.num_gpus + ) diff --git a/itrialspace/src/itrialspace/synthesis/scripts/diff_model_infer.py b/itrialspace/src/itrialspace/synthesis/scripts/diff_model_infer.py new file mode 100644 index 0000000000000000000000000000000000000000..eaacaa5398a82906f2e342d68d8bd8dca2d4fd0e --- /dev/null +++ b/itrialspace/src/itrialspace/synthesis/scripts/diff_model_infer.py @@ -0,0 +1,376 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import argparse +import logging +import os +import random +from datetime import datetime + +import nibabel as nib +import numpy as np +import torch +import torch.distributed as dist +from monai.inferers import sliding_window_inference +from monai.inferers.inferer import SlidingWindowInferer +from monai.networks.schedulers import RFlowScheduler +from monai.utils import set_determinism +from tqdm import tqdm + +from .diff_model_setting import initialize_distributed, load_config, setup_logging +from .sample import ReconModel, check_input +from .utils import define_instance, dynamic_infer + + +def set_random_seed(seed: int) -> int: + """ + Set random seed for reproducibility. + + Args: + seed (int): Random seed. + + Returns: + int: Set random seed. + """ + random_seed = random.randint(0, 99999) if seed is None else seed + set_determinism(random_seed) + return random_seed + + +def load_models(args: argparse.Namespace, device: torch.device, logger: logging.Logger) -> tuple: + """ + Load the autoencoder and UNet models. + + Args: + args (argparse.Namespace): Configuration arguments. + device (torch.device): Device to load models on. + logger (logging.Logger): Logger for logging information. + + Returns: + tuple: Loaded autoencoder, UNet model, and scale factor. + """ + autoencoder = define_instance(args, "autoencoder_def").to(device) + try: + checkpoint_autoencoder = torch.load(args.trained_autoencoder_path, weights_only=True) + autoencoder.load_state_dict(checkpoint_autoencoder) + except Exception: + logger.error("The trained_autoencoder_path does not exist!") + + unet = define_instance(args, "diffusion_unet_def").to(device) + checkpoint = torch.load( + f"{args.model_dir}/{args.model_filename}", map_location=device, weights_only=False + ) + unet.load_state_dict(checkpoint["unet_state_dict"], strict=True) + logger.info(f"checkpoints {args.model_dir}/{args.model_filename} loaded.") + + scale_factor = checkpoint["scale_factor"] + logger.info(f"scale_factor -> {scale_factor}.") + + return autoencoder, unet, scale_factor + + +def prepare_tensors(args: argparse.Namespace, device: torch.device) -> tuple: + """ + Prepare necessary tensors for inference. + + Args: + args (argparse.Namespace): Configuration arguments. + device (torch.device): Device to load tensors on. + + Returns: + tuple: Prepared top_region_index_tensor, bottom_region_index_tensor, and spacing_tensor. + """ + top_region_index_tensor = ( + np.array(args.diffusion_unet_inference["top_region_index"]).astype(float) * 1e2 + ) + bottom_region_index_tensor = ( + np.array(args.diffusion_unet_inference["bottom_region_index"]).astype(float) * 1e2 + ) + spacing_tensor = np.array(args.diffusion_unet_inference["spacing"]).astype(float) * 1e2 + + top_region_index_tensor = ( + torch.from_numpy(top_region_index_tensor[np.newaxis, :]).half().to(device) + ) + bottom_region_index_tensor = ( + torch.from_numpy(bottom_region_index_tensor[np.newaxis, :]).half().to(device) + ) + spacing_tensor = torch.from_numpy(spacing_tensor[np.newaxis, :]).half().to(device) + modality_tensor = args.diffusion_unet_inference["modality"] * torch.ones( + (len(spacing_tensor)), dtype=torch.long + ).to(device) + + return top_region_index_tensor, bottom_region_index_tensor, spacing_tensor, modality_tensor + + +def run_inference( + args: argparse.Namespace, + device: torch.device, + autoencoder: torch.nn.Module, + unet: torch.nn.Module, + scale_factor: float, + top_region_index_tensor: torch.Tensor, + bottom_region_index_tensor: torch.Tensor, + spacing_tensor: torch.Tensor, + modality_tensor: torch.Tensor, + output_size: tuple, + divisor: int, + logger: logging.Logger, +) -> np.ndarray: + """ + Run the inference to generate synthetic images. + + Args: + args (argparse.Namespace): Configuration arguments. + device (torch.device): Device to run inference on. + autoencoder (torch.nn.Module): Autoencoder model. + unet (torch.nn.Module): UNet model. + scale_factor (float): Scale factor for the model. + top_region_index_tensor (torch.Tensor): Top region index tensor. + bottom_region_index_tensor (torch.Tensor): Bottom region index tensor. + spacing_tensor (torch.Tensor): Spacing tensor. + modality_tensor (torch.Tensor): Modality tensor. + output_size (tuple): Output size of the synthetic image. + divisor (int): Divisor for downsample level. + logger (logging.Logger): Logger for logging information. + + Returns: + np.ndarray: Generated synthetic image data. + """ + include_body_region = unet.include_top_region_index_input + include_modality = unet.num_class_embeds is not None + + noise = torch.randn( + ( + 1, + args.latent_channels, + output_size[0] // divisor, + output_size[1] // divisor, + output_size[2] // divisor, + ), + device=device, + ) + logger.info(f"noise: {noise.device}, {noise.dtype}, {type(noise)}") + + image = noise + noise_scheduler = define_instance(args, "noise_scheduler") + if isinstance(noise_scheduler, RFlowScheduler): + noise_scheduler.set_timesteps( + num_inference_steps=args.diffusion_unet_inference["num_inference_steps"], + input_img_size_numel=torch.prod(torch.tensor(noise.shape[2:])), + ) + else: + noise_scheduler.set_timesteps( + num_inference_steps=args.diffusion_unet_inference["num_inference_steps"] + ) + + recon_model = ReconModel(autoencoder=autoencoder, scale_factor=scale_factor).to(device) + autoencoder.eval() + unet.eval() + + all_timesteps = noise_scheduler.timesteps + all_next_timesteps = torch.cat( + (all_timesteps[1:], torch.tensor([0], dtype=all_timesteps.dtype)) + ) + progress_bar = tqdm( + zip(all_timesteps, all_next_timesteps), + total=min(len(all_timesteps), len(all_next_timesteps)), + ) + with torch.amp.autocast("cuda", enabled=True): + for t, next_t in progress_bar: + # Create a dictionary to store the inputs + unet_inputs = { + "x": image, + "timesteps": torch.Tensor((t,)).to(device), + "spacing_tensor": spacing_tensor, + } + + # Add extra arguments if include_body_region is True + if include_body_region: + unet_inputs.update( + { + "top_region_index_tensor": top_region_index_tensor, + "bottom_region_index_tensor": bottom_region_index_tensor, + } + ) + + if include_modality: + unet_inputs.update( + { + "class_labels": modality_tensor, + } + ) + model_output = unet(**unet_inputs) + if not isinstance(noise_scheduler, RFlowScheduler): + image, _ = noise_scheduler.step(model_output, t, image) # type: ignore + else: + image, _ = noise_scheduler.step(model_output, t, image, next_t) # type: ignore + + inferer = SlidingWindowInferer( + roi_size=[80, 80, 80], + sw_batch_size=1, + progress=True, + mode="gaussian", + overlap=0.4, + sw_device=device, + device=device, + ) + synthetic_images = dynamic_infer(inferer, recon_model, image) + data = synthetic_images.squeeze().cpu().detach().numpy() + a_min, a_max, b_min, b_max = -1000, 1000, 0, 1 + data = (data - b_min) / (b_max - b_min) * (a_max - a_min) + a_min + data = np.clip(data, a_min, a_max) + return np.int16(data) + + +def save_image( + data: np.ndarray, + output_size: tuple, + out_spacing: tuple, + output_path: str, + logger: logging.Logger, +) -> None: + """ + Save the generated synthetic image to a file. + + Args: + data (np.ndarray): Synthetic image data. + output_size (tuple): Output size of the image. + out_spacing (tuple): Spacing of the output image. + output_path (str): Path to save the output image. + logger (logging.Logger): Logger for logging information. + """ + out_affine = np.eye(4) + for i in range(3): + out_affine[i, i] = out_spacing[i] + + new_image = nib.Nifti1Image(data, affine=out_affine) + os.makedirs(os.path.dirname(output_path), exist_ok=True) + nib.save(new_image, output_path) + logger.info(f"Saved {output_path}.") + + +@torch.inference_mode() +def diff_model_infer( + env_config_path: str, model_config_path: str, model_def_path: str, num_gpus: int +) -> None: + """ + Main function to run the diffusion model inference. + + Args: + env_config_path (str): Path to the environment configuration file. + model_config_path (str): Path to the model configuration file. + model_def_path (str): Path to the model definition file. + """ + args = load_config(env_config_path, model_config_path, model_def_path) + local_rank, world_size, device = initialize_distributed(num_gpus) + logger = setup_logging("inference") + random_seed = set_random_seed( + args.diffusion_unet_inference["random_seed"] + local_rank + if args.diffusion_unet_inference["random_seed"] + else None + ) + logger.info(f"Using {device} of {world_size} with random seed: {random_seed}") + + output_size = tuple(args.diffusion_unet_inference["dim"]) + out_spacing = tuple(args.diffusion_unet_inference["spacing"]) + output_prefix = args.output_prefix + ckpt_filepath = f"{args.model_dir}/{args.model_filename}" + + if local_rank == 0: + logger.info(f"[config] ckpt_filepath -> {ckpt_filepath}.") + logger.info(f"[config] random_seed -> {random_seed}.") + logger.info(f"[config] output_prefix -> {output_prefix}.") + logger.info(f"[config] output_size -> {output_size}.") + logger.info(f"[config] out_spacing -> {out_spacing}.") + + check_input(None, None, None, output_size, out_spacing, None) + + autoencoder, unet, scale_factor = load_models(args, device, logger) + num_downsample_level = max( + 1, + ( + len(args.diffusion_unet_def["num_channels"]) + if isinstance(args.diffusion_unet_def["num_channels"], list) + else len(args.diffusion_unet_def["attention_levels"]) + ), + ) + divisor = 2 ** (num_downsample_level - 2) + logger.info(f"num_downsample_level -> {num_downsample_level}, divisor -> {divisor}.") + + top_region_index_tensor, bottom_region_index_tensor, spacing_tensor, modality_tensor = ( + prepare_tensors(args, device) + ) + data = run_inference( + args, + device, + autoencoder, + unet, + scale_factor, + top_region_index_tensor, + bottom_region_index_tensor, + spacing_tensor, + modality_tensor, + output_size, + divisor, + logger, + ) + + timestamp = datetime.now().strftime("%Y%m%d%H%M%S") + output_path = "{0}/{1}_seed{2}_size{3:d}x{4:d}x{5:d}_spacing{6:.2f}x{7:.2f}x{8:.2f}_{9}_rank{10}.nii.gz".format( + args.output_dir, + output_prefix, + random_seed, + output_size[0], + output_size[1], + output_size[2], + out_spacing[0], + out_spacing[1], + out_spacing[2], + timestamp, + local_rank, + ) + save_image(data, output_size, out_spacing, output_path, logger) + + if dist.is_initialized(): + dist.destroy_process_group() + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Diffusion Model Inference") + parser.add_argument( + "--env_config", + type=str, + default="./configs/environment_maisi_diff_model_train.json", + help="Path to environment configuration file", + ) + parser.add_argument( + "--model_config", + type=str, + default="./configs/config_maisi_diff_model_train.json", + help="Path to model training/inference configuration", + ) + parser.add_argument( + "--model_def", + type=str, + default="./configs/config_maisi.json", + help="Path to model definition file", + ) + parser.add_argument( + "--num_gpus", + type=int, + default=1, + help="Number of GPUs to use for distributed inference", + ) + + args = parser.parse_args() + diff_model_infer(args.env_config, args.model_config, args.model_def, args.num_gpus) diff --git a/itrialspace/src/itrialspace/synthesis/scripts/diff_model_setting.py b/itrialspace/src/itrialspace/synthesis/scripts/diff_model_setting.py new file mode 100644 index 0000000000000000000000000000000000000000..722207cf51e2ecf5b7f5729368d30a5cd883bac0 --- /dev/null +++ b/itrialspace/src/itrialspace/synthesis/scripts/diff_model_setting.py @@ -0,0 +1,94 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import argparse +import json +import logging + +import torch +import torch.distributed as dist +from monai.utils import RankFilter + + +def setup_logging(logger_name: str = "") -> logging.Logger: + """ + Setup the logging configuration. + + Args: + logger_name (str): logger name. + + Returns: + logging.Logger: Configured logger. + """ + logger = logging.getLogger(logger_name) + if dist.is_initialized(): + logger.addFilter(RankFilter()) + logging.basicConfig( + level=logging.INFO, + format="[%(asctime)s.%(msecs)03d][%(levelname)5s](%(name)s) - %(message)s", + datefmt="%Y-%m-%d %H:%M:%S", + ) + return logger + + +def load_config( + env_config_path: str, model_config_path: str, model_def_path: str +) -> argparse.Namespace: + """ + Load configuration from JSON files. + + Args: + env_config_path (str): Path to the environment configuration file. + model_config_path (str): Path to the model configuration file. + model_def_path (str): Path to the model definition file. + + Returns: + argparse.Namespace: Loaded configuration. + """ + args = argparse.Namespace() + + with open(env_config_path, "r") as f: + env_config = json.load(f) + for k, v in env_config.items(): + setattr(args, k, v) + + with open(model_config_path, "r") as f: + model_config = json.load(f) + for k, v in model_config.items(): + setattr(args, k, v) + + with open(model_def_path, "r") as f: + model_def = json.load(f) + for k, v in model_def.items(): + setattr(args, k, v) + + return args + + +def initialize_distributed(num_gpus: int) -> tuple: + """ + Initialize distributed training. + + Returns: + tuple: local_rank, world_size, and device. + """ + if torch.cuda.is_available() and num_gpus > 1: + dist.init_process_group(backend="nccl", init_method="env://") + local_rank = dist.get_rank() + world_size = dist.get_world_size() + else: + local_rank = 0 + world_size = 1 + device = torch.device("cuda", local_rank) + torch.cuda.set_device(device) + return local_rank, world_size, device diff --git a/itrialspace/src/itrialspace/synthesis/scripts/diff_model_train.py b/itrialspace/src/itrialspace/synthesis/scripts/diff_model_train.py new file mode 100644 index 0000000000000000000000000000000000000000..1376c2c65e320c9cd639043cec7069bba047c0bd --- /dev/null +++ b/itrialspace/src/itrialspace/synthesis/scripts/diff_model_train.py @@ -0,0 +1,536 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import argparse +import json +import logging +import os +from datetime import datetime +from pathlib import Path + +import monai +import torch +import torch.distributed as dist +from monai.data import DataLoader, partition_dataset +from monai.networks.schedulers import RFlowScheduler +from monai.networks.schedulers.ddpm import DDPMPredictionType +from monai.transforms import Compose +from monai.utils import first +from torch.amp import GradScaler, autocast +from torch.nn.parallel import DistributedDataParallel + +from .diff_model_setting import initialize_distributed, load_config, setup_logging +from .utils import define_instance + + +def load_filenames(data_list_path: str) -> list: + """ + Load filenames from the JSON data list. + + Args: + data_list_path (str): Path to the JSON data list file. + + Returns: + list: List of filenames. + """ + with open(data_list_path, "r") as file: + json_data = json.load(file) + filenames_train = json_data["training"] + return [_item["image"].replace(".nii.gz", "_emb.nii.gz") for _item in filenames_train] + + +def prepare_data( + train_files: list, + device: torch.device, + cache_rate: float, + num_workers: int = 2, + batch_size: int = 1, + include_body_region: bool = False, +) -> DataLoader: + """ + Prepare training data. + + Args: + train_files (list): List of training files. + device (torch.device): Device to use for training. + cache_rate (float): Cache rate for dataset. + num_workers (int): Number of workers for data loading. + batch_size (int): Mini-batch size. + include_body_region (bool): Whether to include body region in data + + Returns: + DataLoader: Data loader for training. + """ + + def _load_data_from_file(file_path, key): + with open(file_path) as f: + return torch.FloatTensor(json.load(f)[key]) + + train_transforms_list = [ + monai.transforms.LoadImaged(keys=["image"]), + monai.transforms.EnsureChannelFirstd(keys=["image"]), + monai.transforms.Lambdad(keys="spacing", func=lambda x: _load_data_from_file(x, "spacing")), + monai.transforms.Lambdad(keys="spacing", func=lambda x: x * 1e2), + ] + if include_body_region: + train_transforms_list += [ + monai.transforms.Lambdad( + keys="top_region_index", func=lambda x: _load_data_from_file(x, "top_region_index") + ), + monai.transforms.Lambdad( + keys="bottom_region_index", + func=lambda x: _load_data_from_file(x, "bottom_region_index"), + ), + monai.transforms.Lambdad(keys="top_region_index", func=lambda x: x * 1e2), + monai.transforms.Lambdad(keys="bottom_region_index", func=lambda x: x * 1e2), + ] + train_transforms = Compose(train_transforms_list) + + train_ds = monai.data.CacheDataset( + data=train_files, transform=train_transforms, cache_rate=cache_rate, num_workers=num_workers + ) + + return DataLoader(train_ds, num_workers=6, batch_size=batch_size, shuffle=True) + + +def load_unet( + args: argparse.Namespace, device: torch.device, logger: logging.Logger +) -> torch.nn.Module: + """ + Load the UNet model. + + Args: + args (argparse.Namespace): Configuration arguments. + device (torch.device): Device to load the model on. + logger (logging.Logger): Logger for logging information. + + Returns: + torch.nn.Module: Loaded UNet model. + """ + unet = define_instance(args, "diffusion_unet_def").to(device) + unet = torch.nn.SyncBatchNorm.convert_sync_batchnorm(unet) + + if dist.is_initialized(): + unet = DistributedDataParallel(unet, device_ids=[device], find_unused_parameters=True) + + if args.existing_ckpt_filepath is None: + logger.info("Training from scratch.") + else: + checkpoint_unet = torch.load( + f"{args.existing_ckpt_filepath}", map_location=device, weights_only=False + ) + if dist.is_initialized(): + unet.module.load_state_dict(checkpoint_unet["unet_state_dict"], strict=True) + else: + unet.load_state_dict(checkpoint_unet["unet_state_dict"], strict=True) + logger.info(f"Pretrained checkpoint {args.existing_ckpt_filepath} loaded.") + + return unet + + +def calculate_scale_factor( + train_loader: DataLoader, device: torch.device, logger: logging.Logger +) -> torch.Tensor: + """ + Calculate the scaling factor for the dataset. + + Args: + train_loader (DataLoader): Data loader for training. + device (torch.device): Device to use for calculation. + logger (logging.Logger): Logger for logging information. + + Returns: + torch.Tensor: Calculated scaling factor. + """ + check_data = first(train_loader) + z = check_data["image"].to(device) + scale_factor = 1 / torch.std(z) + logger.info(f"Scaling factor set to {scale_factor}.") + + if dist.is_initialized(): + dist.barrier() + dist.all_reduce(scale_factor, op=torch.distributed.ReduceOp.AVG) + logger.info(f"scale_factor -> {scale_factor}.") + return scale_factor + + +def create_optimizer(model: torch.nn.Module, lr: float) -> torch.optim.Optimizer: + """ + Create optimizer for training. + + Args: + model (torch.nn.Module): Model to optimize. + lr (float): Learning rate. + + Returns: + torch.optim.Optimizer: Created optimizer. + """ + return torch.optim.Adam(params=model.parameters(), lr=lr) + + +def create_lr_scheduler( + optimizer: torch.optim.Optimizer, total_steps: int +) -> torch.optim.lr_scheduler.PolynomialLR: + """ + Create learning rate scheduler. + + Args: + optimizer (torch.optim.Optimizer): Optimizer to schedule. + total_steps (int): Total number of training steps. + + Returns: + torch.optim.lr_scheduler.PolynomialLR: Created learning rate scheduler. + """ + return torch.optim.lr_scheduler.PolynomialLR(optimizer, total_iters=total_steps, power=2.0) + + +def train_one_epoch( + epoch: int, + unet: torch.nn.Module, + train_loader: DataLoader, + optimizer: torch.optim.Optimizer, + lr_scheduler: torch.optim.lr_scheduler.PolynomialLR, + loss_pt: torch.nn.L1Loss, + scaler: GradScaler, + scale_factor: torch.Tensor, + noise_scheduler: torch.nn.Module, + num_images_per_batch: int, + num_train_timesteps: int, + device: torch.device, + logger: logging.Logger, + local_rank: int, + amp: bool = True, +) -> torch.Tensor: + """ + Train the model for one epoch. + + Args: + epoch (int): Current epoch number. + unet (torch.nn.Module): UNet model. + train_loader (DataLoader): Data loader for training. + optimizer (torch.optim.Optimizer): Optimizer. + lr_scheduler (torch.optim.lr_scheduler.PolynomialLR): Learning rate scheduler. + loss_pt (torch.nn.L1Loss): Loss function. + scaler (GradScaler): Gradient scaler for mixed precision training. + scale_factor (torch.Tensor): Scaling factor. + noise_scheduler (torch.nn.Module): Noise scheduler. + num_images_per_batch (int): Number of images per batch. + num_train_timesteps (int): Number of training timesteps. + device (torch.device): Device to use for training. + logger (logging.Logger): Logger for logging information. + local_rank (int): Local rank for distributed training. + amp (bool): Use automatic mixed precision training. + + Returns: + torch.Tensor: Training loss for the epoch. + """ + include_body_region = unet.include_top_region_index_input + include_modality = unet.num_class_embeds is not None + + if local_rank == 0: + current_lr = optimizer.param_groups[0]["lr"] + logger.info(f"Epoch {epoch + 1}, lr {current_lr}.") + + _iter = 0 + loss_torch = torch.zeros(2, dtype=torch.float, device=device) + + unet.train() + for train_data in train_loader: + current_lr = optimizer.param_groups[0]["lr"] + + _iter += 1 + images = train_data["image"].to(device) + images = images * scale_factor + + if include_body_region: + top_region_index_tensor = train_data["top_region_index"].to(device) + bottom_region_index_tensor = train_data["bottom_region_index"].to(device) + # We trained with only CT in this version + if include_modality: + modality_tensor = torch.ones((len(images),), dtype=torch.long).to(device) + spacing_tensor = train_data["spacing"].to(device) + + optimizer.zero_grad(set_to_none=True) + + with autocast("cuda", enabled=amp): + noise = torch.randn_like(images) + + if isinstance(noise_scheduler, RFlowScheduler): + timesteps = noise_scheduler.sample_timesteps(images) + else: + timesteps = torch.randint( + 0, num_train_timesteps, (images.shape[0],), device=images.device + ).long() + + noisy_latent = noise_scheduler.add_noise( + original_samples=images, noise=noise, timesteps=timesteps + ) + + # Create a dictionary to store the inputs + unet_inputs = { + "x": noisy_latent, + "timesteps": timesteps, + "spacing_tensor": spacing_tensor, + } + # Add extra arguments if include_body_region is True + if include_body_region: + unet_inputs.update( + { + "top_region_index_tensor": top_region_index_tensor, + "bottom_region_index_tensor": bottom_region_index_tensor, + } + ) + if include_modality: + unet_inputs.update( + { + "class_labels": modality_tensor, + } + ) + model_output = unet(**unet_inputs) + + if noise_scheduler.prediction_type == DDPMPredictionType.EPSILON: + # predict noise + model_gt = noise + elif noise_scheduler.prediction_type == DDPMPredictionType.SAMPLE: + # predict sample + model_gt = images + elif noise_scheduler.prediction_type == DDPMPredictionType.V_PREDICTION: + # predict velocity + model_gt = images - noise + else: + raise ValueError( + "noise scheduler prediction type has to be chosen from ", + f"[{DDPMPredictionType.EPSILON},{DDPMPredictionType.SAMPLE},{DDPMPredictionType.V_PREDICTION}]", + ) + + loss = loss_pt(model_output.float(), model_gt.float()) + + if amp: + scaler.scale(loss).backward() + scaler.step(optimizer) + scaler.update() + else: + loss.backward() + optimizer.step() + + lr_scheduler.step() + + loss_torch[0] += loss.item() + loss_torch[1] += 1.0 + + if local_rank == 0: + logger.info( + "[{0}] epoch {1}, iter {2}/{3}, loss: {4:.4f}, lr: {5:.12f}.".format( + str(datetime.now())[:19], + epoch + 1, + _iter, + len(train_loader), + loss.item(), + current_lr, + ) + ) + + if dist.is_initialized(): + dist.all_reduce(loss_torch, op=torch.distributed.ReduceOp.SUM) + + return loss_torch + + +def save_checkpoint( + epoch: int, + unet: torch.nn.Module, + loss_torch_epoch: float, + num_train_timesteps: int, + scale_factor: torch.Tensor, + ckpt_folder: str, + args: argparse.Namespace, +) -> None: + """ + Save checkpoint. + + Args: + epoch (int): Current epoch number. + unet (torch.nn.Module): UNet model. + loss_torch_epoch (float): Training loss for the epoch. + num_train_timesteps (int): Number of training timesteps. + scale_factor (torch.Tensor): Scaling factor. + ckpt_folder (str): Checkpoint folder path. + args (argparse.Namespace): Configuration arguments. + """ + unet_state_dict = unet.module.state_dict() if dist.is_initialized() else unet.state_dict() + torch.save( + { + "epoch": epoch + 1, + "loss": loss_torch_epoch, + "num_train_timesteps": num_train_timesteps, + "scale_factor": scale_factor, + "unet_state_dict": unet_state_dict, + }, + f"{ckpt_folder}/{args.model_filename}", + ) + + +def diff_model_train( + env_config_path: str, + model_config_path: str, + model_def_path: str, + num_gpus: int, + amp: bool = True, +) -> None: + """ + Main function to train a diffusion model. + + Args: + env_config_path (str): Path to the environment configuration file. + model_config_path (str): Path to the model configuration file. + model_def_path (str): Path to the model definition file. + num_gpus (int): Number of GPUs to use for training. + amp (bool): Use automatic mixed precision training. + """ + args = load_config(env_config_path, model_config_path, model_def_path) + local_rank, world_size, device = initialize_distributed(num_gpus) + logger = setup_logging("training") + + logger.info(f"Using {device} of {world_size}") + + if local_rank == 0: + logger.info(f"[config] ckpt_folder -> {args.model_dir}.") + logger.info(f"[config] data_root -> {args.embedding_base_dir}.") + logger.info(f"[config] data_list -> {args.json_data_list}.") + logger.info(f"[config] lr -> {args.diffusion_unet_train['lr']}.") + logger.info(f"[config] num_epochs -> {args.diffusion_unet_train['n_epochs']}.") + logger.info( + f"[config] num_train_timesteps -> {args.noise_scheduler['num_train_timesteps']}." + ) + + Path(args.model_dir).mkdir(parents=True, exist_ok=True) + + unet = load_unet(args, device, logger) + noise_scheduler = define_instance(args, "noise_scheduler") + include_body_region = unet.include_top_region_index_input + + filenames_train = load_filenames(args.json_data_list) + if local_rank == 0: + logger.info(f"num_files_train: {len(filenames_train)}") + + train_files = [] + for _i in range(len(filenames_train)): + str_img = os.path.join(args.embedding_base_dir, filenames_train[_i]) + if not os.path.exists(str_img): + continue + + str_info = os.path.join(args.embedding_base_dir, filenames_train[_i]) + ".json" + train_files_i = {"image": str_img, "spacing": str_info} + if include_body_region: + train_files_i["top_region_index"] = str_info + train_files_i["bottom_region_index"] = str_info + train_files.append(train_files_i) + if dist.is_initialized(): + train_files = partition_dataset( + data=train_files, + shuffle=True, + num_partitions=dist.get_world_size(), + even_divisible=True, + )[local_rank] + + train_loader = prepare_data( + train_files, + device, + args.diffusion_unet_train["cache_rate"], + batch_size=args.diffusion_unet_train["batch_size"], + include_body_region=include_body_region, + ) + + scale_factor = calculate_scale_factor(train_loader, device, logger) + optimizer = create_optimizer(unet, args.diffusion_unet_train["lr"]) + + total_steps = ( + args.diffusion_unet_train["n_epochs"] * len(train_loader.dataset) + ) / args.diffusion_unet_train["batch_size"] + lr_scheduler = create_lr_scheduler(optimizer, total_steps) + loss_pt = torch.nn.L1Loss() + scaler = GradScaler("cuda") + + torch.set_float32_matmul_precision("highest") + logger.info("torch.set_float32_matmul_precision -> highest.") + + for epoch in range(args.diffusion_unet_train["n_epochs"]): + loss_torch = train_one_epoch( + epoch, + unet, + train_loader, + optimizer, + lr_scheduler, + loss_pt, + scaler, + scale_factor, + noise_scheduler, + args.diffusion_unet_train["batch_size"], + args.noise_scheduler["num_train_timesteps"], + device, + logger, + local_rank, + amp=amp, + ) + + loss_torch = loss_torch.tolist() + if torch.cuda.device_count() == 1 or local_rank == 0: + loss_torch_epoch = loss_torch[0] / loss_torch[1] + logger.info(f"epoch {epoch + 1} average loss: {loss_torch_epoch:.4f}.") + + save_checkpoint( + epoch, + unet, + loss_torch_epoch, + args.noise_scheduler["num_train_timesteps"], + scale_factor, + args.model_dir, + args, + ) + + if dist.is_initialized(): + dist.destroy_process_group() + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Diffusion Model Training") + parser.add_argument( + "--env_config", + type=str, + default="./configs/environment_maisi_diff_model.json", + help="Path to environment configuration file", + ) + parser.add_argument( + "--model_config", + type=str, + default="./configs/config_maisi_diff_model.json", + help="Path to model training/inference configuration", + ) + parser.add_argument( + "--model_def", + type=str, + default="./configs/config_maisi.json", + help="Path to model definition file", + ) + parser.add_argument( + "--num_gpus", type=int, default=1, help="Number of GPUs to use for training" + ) + parser.add_argument( + "--no_amp", + dest="amp", + action="store_false", + help="Disable automatic mixed precision training", + ) + + args = parser.parse_args() + diff_model_train(args.env_config, args.model_config, args.model_def, args.num_gpus, args.amp) diff --git a/itrialspace/src/itrialspace/synthesis/scripts/find_masks.py b/itrialspace/src/itrialspace/synthesis/scripts/find_masks.py new file mode 100644 index 0000000000000000000000000000000000000000..42106f5f2a8794c556d116ea4c2407372095ecd4 --- /dev/null +++ b/itrialspace/src/itrialspace/synthesis/scripts/find_masks.py @@ -0,0 +1,170 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +import json +import os +from typing import Sequence + +from monai.apps.utils import extractall +from monai.utils import ensure_tuple_rep + + +def convert_body_region(body_region: str | Sequence[str]) -> Sequence[int]: + """ + Convert body region string to body region index. + Args: + body_region: list of input body region string. If single str, will be converted to list of str. + Return: + body_region_indices, list of input body region index. + """ + if type(body_region) is str: + body_region = [body_region] + + # body region mapping for maisi + region_mapping_maisi = { + "head": 0, + "chest": 1, + "thorax": 1, + "chest/thorax": 1, + "abdomen": 2, + "pelvis": 3, + "lower": 3, + "pelvis/lower": 3, + } + + # perform mapping + body_region_indices = [] + for region in body_region: + normalized_region = region.lower() # norm str to lower case + if normalized_region not in region_mapping_maisi: + raise ValueError(f"Invalid region: {normalized_region}") + body_region_indices.append(region_mapping_maisi[normalized_region]) + + return body_region_indices + + +def find_masks( + body_region: str | Sequence[str], + anatomy_list: int | Sequence[int], + spacing: Sequence[float] | float = 1.0, + output_size: Sequence[int] = [512, 512, 512], + check_spacing_and_output_size: bool = False, + database_filepath: str = "./configs/database.json", + mask_foldername: str = "./datasets/masks/", +): + """ + Find candidate masks that fullfills all the requirements. + They shoud contain all the body region in `body_region`, all the anatomies in `anatomy_list`. + If there is no tumor specified in `anatomy_list`, we also expect the candidate masks to be tumor free. + If check_spacing_and_output_size is True, the candidate masks need to have the expected `spacing` and `output_size`. + Args: + body_region: list of input body region string. If single str, will be converted to list of str. + The found candidate mask will include these body regions. + anatomy_list: list of input anatomy. The found candidate mask will include these anatomies. + spacing: list of three floats, voxel spacing. If providing a single number, will use it for all the three dimensions. + output_size: list of three int, expected candidate mask spatial size. + check_spacing_and_output_size: whether we expect candidate mask to have spatial size of `output_size` and voxel size of `spacing`. + database_filepath: path for the json file that stores the information of all the candidate masks. + mask_foldername: directory that saves all the candidate masks. + Return: + candidate_masks, list of dict, each dict contains information of one candidate mask that fullfills all the requirements. + """ + # check and preprocess input + body_region = convert_body_region(body_region) + + if isinstance(anatomy_list, int): + anatomy_list = [anatomy_list] + + spacing = ensure_tuple_rep(spacing, 3) + + if not os.path.exists(mask_foldername): + zip_file_path = mask_foldername + ".zip" + + if not os.path.isfile(zip_file_path): + raise ValueError( + f"Please download {zip_file_path} following the instruction in ./datasets/README.md." + ) + + print(f"Extracting {zip_file_path} to {os.path.dirname(zip_file_path)}") + extractall( + filepath=zip_file_path, output_dir=os.path.dirname(zip_file_path), file_type="zip" + ) + print(f"Unzipped {zip_file_path} to {mask_foldername}.") + + if not os.path.isfile(database_filepath): + raise ValueError( + f"Please download {database_filepath} following the instruction in ./datasets/README.md." + ) + with open(database_filepath, "r") as f: + db = json.load(f) + + # select candidate_masks + candidate_masks = [] + for _item in db: + if not set(anatomy_list).issubset(_item["label_list"]): + continue + + # whether to keep this mask, default to be True. + keep_mask = True + + # extract region indice (top_index and bottom_index) for candidate mask + include_body_region = "top_region_index" in _item.keys() + if include_body_region: + top_index = [ + index for index, element in enumerate(_item["top_region_index"]) if element != 0 + ] + top_index = top_index[0] + bottom_index = [ + index for index, element in enumerate(_item["bottom_region_index"]) if element != 0 + ] + bottom_index = bottom_index[0] + + # if candiate mask does not contain all the body_region, skip it + for _idx in body_region: + if _idx > bottom_index or _idx < top_index: + keep_mask = False + + for tumor_label in [23, 24, 26, 27, 128]: + # we skip those mask with tumors if users do not provide tumor label in anatomy_list + if tumor_label not in anatomy_list and tumor_label in _item["label_list"]: + keep_mask = False + + if check_spacing_and_output_size: + # if the output_size and spacing are different with user's input, skip it + for axis in range(3): + if ( + _item["dim"][axis] != output_size[axis] + or _item["spacing"][axis] != spacing[axis] + ): + keep_mask = False + + if keep_mask: + # if decide to keep this mask, we pack the information of this mask and add to final output. + candidate = { + "pseudo_label": os.path.join(mask_foldername, _item["pseudo_label_filename"]), + "spacing": _item["spacing"], + "dim": _item["dim"], + } + if include_body_region: + candidate["top_region_index"] = _item["top_region_index"] + candidate["bottom_region_index"] = _item["bottom_region_index"] + + # Conditionally add the label to the candidate dictionary + if "label_filename" in _item: + candidate["label"] = os.path.join(mask_foldername, _item["label_filename"]) + + candidate_masks.append(candidate) + + if len(candidate_masks) == 0 and not check_spacing_and_output_size: + raise ValueError("Cannot find body region with given anatomy list.") + + return candidate_masks diff --git a/itrialspace/src/itrialspace/synthesis/scripts/infer_controlnet.py b/itrialspace/src/itrialspace/synthesis/scripts/infer_controlnet.py new file mode 100644 index 0000000000000000000000000000000000000000..606a4d3036812599ace3a5b003638abe9d2d8a5a --- /dev/null +++ b/itrialspace/src/itrialspace/synthesis/scripts/infer_controlnet.py @@ -0,0 +1,237 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import argparse +import json +import logging +import os +import sys +from datetime import datetime + +import torch +import torch.distributed as dist +from monai.data import MetaTensor, decollate_batch +from monai.networks.utils import copy_model_state +from monai.transforms import SaveImage +from monai.utils import RankFilter + +from .sample import check_input, ldm_conditional_sample_one_image +from .utils import define_instance, prepare_maisi_controlnet_json_dataloader, setup_ddp + + +@torch.inference_mode() +def main(): + parser = argparse.ArgumentParser(description="maisi.controlnet.infer") + parser.add_argument( + "-e", + "--environment-file", + default="./configs/environment_maisi_controlnet_train.json", + help="environment json file that stores environment path", + ) + parser.add_argument( + "-c", + "--config-file", + default="./configs/config_maisi.json", + help="config json file that stores network hyper-parameters", + ) + parser.add_argument( + "-t", + "--training-config", + default="./configs/config_maisi_controlnet_train.json", + help="config json file that stores training hyper-parameters", + ) + parser.add_argument("-g", "--gpus", default=1, type=int, help="number of gpus per node") + + args = parser.parse_args() + + # Step 0: configuration + logger = logging.getLogger("maisi.controlnet.infer") + # whether to use distributed data parallel + use_ddp = args.gpus > 1 + if use_ddp: + rank = int(os.environ["LOCAL_RANK"]) + world_size = int(os.environ["WORLD_SIZE"]) + device = setup_ddp(rank, world_size) + logger.addFilter(RankFilter()) + else: + rank = 0 + world_size = 1 + device = torch.device(f"cuda:{rank}") + + torch.cuda.set_device(device) + logger.info(f"Number of GPUs: {torch.cuda.device_count()}") + logger.info(f"World_size: {world_size}") + + with open(args.environment_file, "r") as env_file: + env_dict = json.load(env_file) + with open(args.config_file, "r") as config_file: + config_dict = json.load(config_file) + with open(args.training_config, "r") as training_config_file: + training_config_dict = json.load(training_config_file) + + for k, v in env_dict.items(): + setattr(args, k, v) + for k, v in config_dict.items(): + setattr(args, k, v) + for k, v in training_config_dict.items(): + setattr(args, k, v) + + # Step 1: set data loader + _, val_loader = prepare_maisi_controlnet_json_dataloader( + json_data_list=args.json_data_list, + data_base_dir=args.data_base_dir, + rank=rank, + world_size=world_size, + batch_size=args.controlnet_train["batch_size"], + cache_rate=args.controlnet_train["cache_rate"], + fold=args.controlnet_train["fold"], + ) + + # Step 2: define AE, diffusion model and controlnet + # define AE + autoencoder = define_instance(args, "autoencoder_def").to(device) + # load trained autoencoder model + if args.trained_autoencoder_path is not None: + if not os.path.exists(args.trained_autoencoder_path): + raise ValueError("Please download the autoencoder checkpoint.") + autoencoder_ckpt = torch.load(args.trained_autoencoder_path, weights_only=True) + autoencoder.load_state_dict(autoencoder_ckpt) + logger.info(f"Load trained diffusion model from {args.trained_autoencoder_path}.") + else: + logger.info("trained autoencoder model is not loaded.") + + # define diffusion Model + unet = define_instance(args, "diffusion_unet_def").to(device) + include_body_region = unet.include_top_region_index_input + include_modality = unet.num_class_embeds is not None + + # load trained diffusion model + if args.trained_diffusion_path is not None: + if not os.path.exists(args.trained_diffusion_path): + raise ValueError("Please download the trained diffusion unet checkpoint.") + diffusion_model_ckpt = torch.load( + args.trained_diffusion_path, map_location=device, weights_only=False + ) + unet.load_state_dict(diffusion_model_ckpt["unet_state_dict"]) + # load scale factor from diffusion model checkpoint + scale_factor = diffusion_model_ckpt["scale_factor"] + logger.info(f"Load trained diffusion model from {args.trained_diffusion_path}.") + logger.info(f"loaded scale_factor from diffusion model ckpt -> {scale_factor}.") + else: + logger.info("trained diffusion model is not loaded.") + scale_factor = 1.0 + logger.info(f"set scale_factor -> {scale_factor}.") + + # define ControlNet + controlnet = define_instance(args, "controlnet_def").to(device) + # copy weights from the DM to the controlnet + copy_model_state(controlnet, unet.state_dict()) + # load trained controlnet model if it is provided + if args.trained_controlnet_path is not None: + if not os.path.exists(args.trained_controlnet_path): + raise ValueError("Please download the trained ControlNet checkpoint.") + controlnet.load_state_dict( + torch.load(args.trained_controlnet_path, map_location=device, weights_only=False)[ + "controlnet_state_dict" + ] + ) + logger.info(f"load trained controlnet model from {args.trained_controlnet_path}") + else: + logger.info("trained controlnet is not loaded.") + + noise_scheduler = define_instance(args, "noise_scheduler") + + # Step 3: inference + autoencoder.eval() + controlnet.eval() + unet.eval() + + for batch in val_loader: + + # get label mask + labels = batch["label"].to(device) + # get corresponding conditions + if include_body_region: + top_region_index_tensor = batch["top_region_index"].to(device) + bottom_region_index_tensor = batch["bottom_region_index"].to(device) + else: + top_region_index_tensor = None + bottom_region_index_tensor = None + spacing_tensor = batch["spacing"].to(device) + modality_tensor = args.controlnet_infer["modality"] * torch.ones( + (len(labels),), dtype=torch.long + ).to(device) + out_spacing = tuple((batch["spacing"].squeeze().numpy() / 100).tolist()) + # get target dimension + dim = batch["dim"] + output_size = (dim[0].item(), dim[1].item(), dim[2].item()) + latent_shape = ( + args.latent_channels, + output_size[0] // 4, + output_size[1] // 4, + output_size[2] // 4, + ) + # check if output_size and out_spacing are valid. + check_input(None, None, None, output_size, out_spacing, None) + # generate a single synthetic image using a latent diffusion model with controlnet. + synthetic_images, _ = ldm_conditional_sample_one_image( + autoencoder=autoencoder, + diffusion_unet=unet, + controlnet=controlnet, + noise_scheduler=noise_scheduler, + scale_factor=scale_factor, + device=device, + combine_label_or=labels, + top_region_index_tensor=top_region_index_tensor, + bottom_region_index_tensor=bottom_region_index_tensor, + spacing_tensor=spacing_tensor, + modality_tensor=modality_tensor, + latent_shape=latent_shape, + output_size=output_size, + noise_factor=1.0, + num_inference_steps=args.controlnet_infer["num_inference_steps"], + autoencoder_sliding_window_infer_size=args.controlnet_infer[ + "autoencoder_sliding_window_infer_size" + ], + autoencoder_sliding_window_infer_overlap=args.controlnet_infer[ + "autoencoder_sliding_window_infer_overlap" + ], + ) + # save image/label pairs + labels = decollate_batch(batch)[0]["label"] + real_object_name = labels.meta.get("filename_or_obj", "default_name.nii.gz") + labels.meta["filename_or_obj"] = real_object_name + output_postfix = datetime.now().strftime("%Y%m%d_%H%M%S_%f") + synthetic_images = MetaTensor(synthetic_images.squeeze(0), meta=labels.meta) + img_saver = SaveImage( + output_dir=args.output_dir, + output_postfix="image", + separate_folder=False, + ) + img_saver(synthetic_images) + label_saver = SaveImage( + output_dir=args.output_dir, + output_postfix="label", + separate_folder=False, + ) + label_saver(labels) + if use_ddp: + dist.destroy_process_group() + + +if __name__ == "__main__": + logging.basicConfig( + stream=sys.stdout, + level=logging.INFO, + format="[%(asctime)s.%(msecs)03d][%(levelname)5s](%(name)s) - %(message)s", + datefmt="%Y-%m-%d %H:%M:%S", + ) + main() diff --git a/itrialspace/src/itrialspace/synthesis/scripts/infer_testV2_controlnet.py b/itrialspace/src/itrialspace/synthesis/scripts/infer_testV2_controlnet.py new file mode 100644 index 0000000000000000000000000000000000000000..1ca27fb9d5e6a94c171d37e611aefab49fd0bdfb --- /dev/null +++ b/itrialspace/src/itrialspace/synthesis/scripts/infer_testV2_controlnet.py @@ -0,0 +1,241 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import argparse +import json +import logging +import os +import sys +from datetime import datetime + +import torch +import torch.distributed as dist +from monai.data import MetaTensor, decollate_batch +from monai.networks.utils import copy_model_state +from monai.transforms import SaveImage +from monai.utils import RankFilter + +from .sample import check_input, ldm_conditional_sample_one_image +from .utils import ( + define_instance, + prepare_maisi_controlnet_json_dataloader, + prepare_maisi_controlnet_test_dataloader, + setup_ddp, +) + + +@torch.inference_mode() +def main(): + parser = argparse.ArgumentParser(description="maisi.controlnet.infer") + parser.add_argument( + "-e", + "--environment-file", + default="./configs/environment_maisi_controlnet_train.json", + help="environment json file that stores environment path", + ) + parser.add_argument( + "-c", + "--config-file", + default="./configs/config_maisi.json", + help="config json file that stores network hyper-parameters", + ) + parser.add_argument( + "-t", + "--training-config", + default="./configs/config_maisi_controlnet_train.json", + help="config json file that stores training hyper-parameters", + ) + parser.add_argument("-g", "--gpus", default=1, type=int, help="number of gpus per node") + + args = parser.parse_args() + + # Step 0: configuration + logger = logging.getLogger("maisi.controlnet.infer") + # whether to use distributed data parallel + use_ddp = args.gpus > 1 + if use_ddp: + rank = int(os.environ["LOCAL_RANK"]) + world_size = int(os.environ["WORLD_SIZE"]) + device = setup_ddp(rank, world_size) + logger.addFilter(RankFilter()) + else: + rank = 0 + world_size = 1 + device = torch.device(f"cuda:{rank}") + + torch.cuda.set_device(device) + logger.info(f"Number of GPUs: {torch.cuda.device_count()}") + logger.info(f"World_size: {world_size}") + + with open(args.environment_file, "r") as env_file: + env_dict = json.load(env_file) + with open(args.config_file, "r") as config_file: + config_dict = json.load(config_file) + with open(args.training_config, "r") as training_config_file: + training_config_dict = json.load(training_config_file) + + for k, v in env_dict.items(): + setattr(args, k, v) + for k, v in config_dict.items(): + setattr(args, k, v) + for k, v in training_config_dict.items(): + setattr(args, k, v) + + # Step 1: set data loader + val_loader = prepare_maisi_controlnet_test_dataloader( + json_data_list=args.json_data_list, + data_base_dir=args.data_base_dir, + batch_size=args.controlnet_train["batch_size"], + cache_rate=args.controlnet_train["cache_rate"], + rank=rank, + world_size=world_size, + ) + + # Step 2: define AE, diffusion model and controlnet + # define AE + autoencoder = define_instance(args, "autoencoder_def").to(device) + # load trained autoencoder model + if args.trained_autoencoder_path is not None: + if not os.path.exists(args.trained_autoencoder_path): + raise ValueError("Please download the autoencoder checkpoint.") + autoencoder_ckpt = torch.load(args.trained_autoencoder_path, weights_only=True) + autoencoder.load_state_dict(autoencoder_ckpt) + logger.info(f"Load trained diffusion model from {args.trained_autoencoder_path}.") + else: + logger.info("trained autoencoder model is not loaded.") + + # define diffusion Model + unet = define_instance(args, "diffusion_unet_def").to(device) + include_body_region = unet.include_top_region_index_input + include_modality = unet.num_class_embeds is not None + + # load trained diffusion model + if args.trained_diffusion_path is not None: + if not os.path.exists(args.trained_diffusion_path): + raise ValueError("Please download the trained diffusion unet checkpoint.") + diffusion_model_ckpt = torch.load( + args.trained_diffusion_path, map_location=device, weights_only=False + ) + unet.load_state_dict(diffusion_model_ckpt["unet_state_dict"]) + # load scale factor from diffusion model checkpoint + scale_factor = diffusion_model_ckpt["scale_factor"] + logger.info(f"Load trained diffusion model from {args.trained_diffusion_path}.") + logger.info(f"loaded scale_factor from diffusion model ckpt -> {scale_factor}.") + else: + logger.info("trained diffusion model is not loaded.") + scale_factor = 1.0 + logger.info(f"set scale_factor -> {scale_factor}.") + + # define ControlNet + controlnet = define_instance(args, "controlnet_def").to(device) + # copy weights from the DM to the controlnet + copy_model_state(controlnet, unet.state_dict()) + # load trained controlnet model if it is provided + if args.trained_controlnet_path is not None: + if not os.path.exists(args.trained_controlnet_path): + raise ValueError("Please download the trained ControlNet checkpoint.") + controlnet.load_state_dict( + torch.load(args.trained_controlnet_path, map_location=device, weights_only=False)[ + "controlnet_state_dict" + ] + ) + logger.info(f"load trained controlnet model from {args.trained_controlnet_path}") + else: + logger.info("trained controlnet is not loaded.") + + noise_scheduler = define_instance(args, "noise_scheduler") + + # Step 3: inference + autoencoder.eval() + controlnet.eval() + unet.eval() + + for batch in val_loader: + + # get label mask + labels = batch["label"].to(device) + # get corresponding conditions + if include_body_region: + top_region_index_tensor = batch["top_region_index"].to(device) + bottom_region_index_tensor = batch["bottom_region_index"].to(device) + else: + top_region_index_tensor = None + bottom_region_index_tensor = None + spacing_tensor = batch["spacing"].to(device) + modality_tensor = args.controlnet_infer["modality"] * torch.ones( + (len(labels),), dtype=torch.long + ).to(device) + out_spacing = tuple((batch["spacing"].squeeze().numpy() / 100).tolist()) + # get target dimension + dim = batch["dim"] + output_size = (dim[0].item(), dim[1].item(), dim[2].item()) + latent_shape = ( + args.latent_channels, + output_size[0] // 4, + output_size[1] // 4, + output_size[2] // 4, + ) + # check if output_size and out_spacing are valid. + check_input(None, None, None, output_size, out_spacing, None) + # generate a single synthetic image using a latent diffusion model with controlnet. + synthetic_images, _ = ldm_conditional_sample_one_image( + autoencoder=autoencoder, + diffusion_unet=unet, + controlnet=controlnet, + noise_scheduler=noise_scheduler, + scale_factor=scale_factor, + device=device, + combine_label_or=labels, + top_region_index_tensor=top_region_index_tensor, + bottom_region_index_tensor=bottom_region_index_tensor, + spacing_tensor=spacing_tensor, + modality_tensor=modality_tensor, + latent_shape=latent_shape, + output_size=output_size, + noise_factor=1.0, + num_inference_steps=args.controlnet_infer["num_inference_steps"], + autoencoder_sliding_window_infer_size=args.controlnet_infer[ + "autoencoder_sliding_window_infer_size" + ], + autoencoder_sliding_window_infer_overlap=args.controlnet_infer[ + "autoencoder_sliding_window_infer_overlap" + ], + ) + # save image/label pairs + labels = decollate_batch(batch)[0]["label"] + real_object_name = labels.meta.get("filename_or_obj", "default_name.nii.gz") + labels.meta["filename_or_obj"] = real_object_name + output_postfix = datetime.now().strftime("%Y%m%d_%H%M%S_%f") + synthetic_images = MetaTensor(synthetic_images.squeeze(0), meta=labels.meta) + img_saver = SaveImage( + output_dir=args.output_dir, + output_postfix="image", + separate_folder=False, + ) + img_saver(synthetic_images) + label_saver = SaveImage( + output_dir=args.output_dir, + output_postfix="label", + separate_folder=False, + ) + label_saver(labels) + if use_ddp: + dist.destroy_process_group() + + +if __name__ == "__main__": + logging.basicConfig( + stream=sys.stdout, + level=logging.INFO, + format="[%(asctime)s.%(msecs)03d][%(levelname)5s](%(name)s) - %(message)s", + datefmt="%Y-%m-%d %H:%M:%S", + ) + main() diff --git a/itrialspace/src/itrialspace/synthesis/scripts/infer_test_controlnet.py b/itrialspace/src/itrialspace/synthesis/scripts/infer_test_controlnet.py new file mode 100644 index 0000000000000000000000000000000000000000..0c173ca878401bb5fc93d95d4b78f8ae5803654d --- /dev/null +++ b/itrialspace/src/itrialspace/synthesis/scripts/infer_test_controlnet.py @@ -0,0 +1,241 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import argparse +import json +import logging +import os +import sys +from datetime import datetime + +import torch +import torch.distributed as dist +from monai.data import MetaTensor, decollate_batch +from monai.networks.utils import copy_model_state +from monai.transforms import SaveImage +from monai.utils import RankFilter + +from .sample import check_input, ldm_conditional_sample_one_image +from .utils import ( + define_instance, + prepare_maisi_controlnet_infer_dataloader, + prepare_maisi_controlnet_json_dataloader, + setup_ddp, +) + + +@torch.inference_mode() +def main(): + parser = argparse.ArgumentParser(description="maisi.controlnet.infer") + parser.add_argument( + "-e", + "--environment-file", + default="./configs/environment_maisi_controlnet_train.json", + help="environment json file that stores environment path", + ) + parser.add_argument( + "-c", + "--config-file", + default="./configs/config_maisi.json", + help="config json file that stores network hyper-parameters", + ) + parser.add_argument( + "-t", + "--training-config", + default="./configs/config_maisi_controlnet_train.json", + help="config json file that stores training hyper-parameters", + ) + parser.add_argument("-g", "--gpus", default=1, type=int, help="number of gpus per node") + + args = parser.parse_args() + + # Step 0: configuration + logger = logging.getLogger("maisi.controlnet.infer") + # whether to use distributed data parallel + use_ddp = args.gpus > 1 + if use_ddp: + rank = int(os.environ["LOCAL_RANK"]) + world_size = int(os.environ["WORLD_SIZE"]) + device = setup_ddp(rank, world_size) + logger.addFilter(RankFilter()) + else: + rank = 0 + world_size = 1 + device = torch.device(f"cuda:{rank}") + + torch.cuda.set_device(device) + logger.info(f"Number of GPUs: {torch.cuda.device_count()}") + logger.info(f"World_size: {world_size}") + + with open(args.environment_file, "r") as env_file: + env_dict = json.load(env_file) + with open(args.config_file, "r") as config_file: + config_dict = json.load(config_file) + with open(args.training_config, "r") as training_config_file: + training_config_dict = json.load(training_config_file) + + for k, v in env_dict.items(): + setattr(args, k, v) + for k, v in config_dict.items(): + setattr(args, k, v) + for k, v in training_config_dict.items(): + setattr(args, k, v) + + # Step 1: set data loader + val_loader = prepare_maisi_controlnet_infer_dataloader( + json_data_list=args.json_data_list, + data_base_dir=args.data_base_dir, + batch_size=args.controlnet_train["batch_size"], + cache_rate=args.controlnet_train["cache_rate"], + rank=rank, + world_size=world_size, + ) + + # Step 2: define AE, diffusion model and controlnet + # define AE + autoencoder = define_instance(args, "autoencoder_def").to(device) + # load trained autoencoder model + if args.trained_autoencoder_path is not None: + if not os.path.exists(args.trained_autoencoder_path): + raise ValueError("Please download the autoencoder checkpoint.") + autoencoder_ckpt = torch.load(args.trained_autoencoder_path, weights_only=True) + autoencoder.load_state_dict(autoencoder_ckpt) + logger.info(f"Load trained diffusion model from {args.trained_autoencoder_path}.") + else: + logger.info("trained autoencoder model is not loaded.") + + # define diffusion Model + unet = define_instance(args, "diffusion_unet_def").to(device) + include_body_region = unet.include_top_region_index_input + include_modality = unet.num_class_embeds is not None + + # load trained diffusion model + if args.trained_diffusion_path is not None: + if not os.path.exists(args.trained_diffusion_path): + raise ValueError("Please download the trained diffusion unet checkpoint.") + diffusion_model_ckpt = torch.load( + args.trained_diffusion_path, map_location=device, weights_only=False + ) + unet.load_state_dict(diffusion_model_ckpt["unet_state_dict"]) + # load scale factor from diffusion model checkpoint + scale_factor = diffusion_model_ckpt["scale_factor"] + logger.info(f"Load trained diffusion model from {args.trained_diffusion_path}.") + logger.info(f"loaded scale_factor from diffusion model ckpt -> {scale_factor}.") + else: + logger.info("trained diffusion model is not loaded.") + scale_factor = 1.0 + logger.info(f"set scale_factor -> {scale_factor}.") + + # define ControlNet + controlnet = define_instance(args, "controlnet_def").to(device) + # copy weights from the DM to the controlnet + copy_model_state(controlnet, unet.state_dict()) + # load trained controlnet model if it is provided + if args.trained_controlnet_path is not None: + if not os.path.exists(args.trained_controlnet_path): + raise ValueError("Please download the trained ControlNet checkpoint.") + controlnet.load_state_dict( + torch.load(args.trained_controlnet_path, map_location=device, weights_only=False)[ + "controlnet_state_dict" + ] + ) + logger.info(f"load trained controlnet model from {args.trained_controlnet_path}") + else: + logger.info("trained controlnet is not loaded.") + + noise_scheduler = define_instance(args, "noise_scheduler") + + # Step 3: inference + autoencoder.eval() + controlnet.eval() + unet.eval() + + for batch in val_loader: + + # get label mask + labels = batch["label"].to(device) + # get corresponding conditions + if include_body_region: + top_region_index_tensor = batch["top_region_index"].to(device) + bottom_region_index_tensor = batch["bottom_region_index"].to(device) + else: + top_region_index_tensor = None + bottom_region_index_tensor = None + spacing_tensor = batch["spacing"].to(device) + modality_tensor = args.controlnet_infer["modality"] * torch.ones( + (len(labels),), dtype=torch.long + ).to(device) + out_spacing = tuple((batch["spacing"].squeeze().numpy() / 100).tolist()) + # get target dimension + dim = batch["dim"] + output_size = (dim[0].item(), dim[1].item(), dim[2].item()) + latent_shape = ( + args.latent_channels, + output_size[0] // 4, + output_size[1] // 4, + output_size[2] // 4, + ) + # check if output_size and out_spacing are valid. + check_input(None, None, None, output_size, out_spacing, None) + # generate a single synthetic image using a latent diffusion model with controlnet. + synthetic_images, _ = ldm_conditional_sample_one_image( + autoencoder=autoencoder, + diffusion_unet=unet, + controlnet=controlnet, + noise_scheduler=noise_scheduler, + scale_factor=scale_factor, + device=device, + combine_label_or=labels, + top_region_index_tensor=top_region_index_tensor, + bottom_region_index_tensor=bottom_region_index_tensor, + spacing_tensor=spacing_tensor, + modality_tensor=modality_tensor, + latent_shape=latent_shape, + output_size=output_size, + noise_factor=1.0, + num_inference_steps=args.controlnet_infer["num_inference_steps"], + autoencoder_sliding_window_infer_size=args.controlnet_infer[ + "autoencoder_sliding_window_infer_size" + ], + autoencoder_sliding_window_infer_overlap=args.controlnet_infer[ + "autoencoder_sliding_window_infer_overlap" + ], + ) + # save image/label pairs + labels = decollate_batch(batch)[0]["label"] + real_object_name = labels.meta.get("filename_or_obj", "default_name.nii.gz") + labels.meta["filename_or_obj"] = real_object_name + output_postfix = datetime.now().strftime("%Y%m%d_%H%M%S_%f") + synthetic_images = MetaTensor(synthetic_images.squeeze(0), meta=labels.meta) + img_saver = SaveImage( + output_dir=args.output_dir, + output_postfix="image", + separate_folder=False, + ) + img_saver(synthetic_images) + label_saver = SaveImage( + output_dir=args.output_dir, + output_postfix="label", + separate_folder=False, + ) + label_saver(labels) + if use_ddp: + dist.destroy_process_group() + + +if __name__ == "__main__": + logging.basicConfig( + stream=sys.stdout, + level=logging.INFO, + format="[%(asctime)s.%(msecs)03d][%(levelname)5s](%(name)s) - %(message)s", + datefmt="%Y-%m-%d %H:%M:%S", + ) + main() diff --git a/itrialspace/src/itrialspace/synthesis/scripts/inference.py b/itrialspace/src/itrialspace/synthesis/scripts/inference.py new file mode 100644 index 0000000000000000000000000000000000000000..0e3474c061048a96897af36cdfeb67e9bee777a4 --- /dev/null +++ b/itrialspace/src/itrialspace/synthesis/scripts/inference.py @@ -0,0 +1,311 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +#     http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# # MAISI Inference Script +import argparse +import json +import logging +import os +import sys +import tempfile + +import monai +import torch +from monai.apps import download_url +from monai.config import print_config +from monai.transforms import LoadImage, Orientation +from monai.utils import set_determinism +from scripts.sample import LDMSampler, check_input +from scripts.utils import define_instance +from scripts.utils_plot import find_label_center_loc, get_xyz_plot, show_image + + +def main(): + parser = argparse.ArgumentParser(description="maisi.controlnet.training") + parser.add_argument( + "-e", + "--environment-file", + default="./configs/environment.json", + help="environment json file that stores environment path", + ) + parser.add_argument( + "-c", + "--config-file", + default="./configs/config_maisi.json", + help="config json file that stores network hyper-parameters", + ) + parser.add_argument( + "-i", + "--inference-file", + default="./configs/config_infer.json", + help="config json file that stores inference hyper-parameters", + ) + parser.add_argument( + "-x", + "--extra-config-file", + default=None, + help="config json file that stores inference extra parameters", + ) + parser.add_argument( + "-s", + "--random-seed", + default=None, + help="random seed, can be None or int", + ) + parser.add_argument( + "--version", + default="maisi3d-rflow", + type=str, + help="maisi_version, choose from ['maisi3d-ddpm', 'maisi3d-rflow']", + ) + args = parser.parse_args() + # Step 0: configuration + logger = logging.getLogger("maisi.inference") + + maisi_version = args.version + + # ## Set deterministic training for reproducibility + if args.random_seed is not None: + set_determinism(seed=args.random_seed) + + # ## Setup data directory + # You can specify a directory with the `MONAI_DATA_DIRECTORY` environment variable. + # This allows you to save results and reuse downloads. + # If not specified a temporary directory will be used. + + directory = os.environ.get("MONAI_DATA_DIRECTORY") + if directory is not None: + os.makedirs(directory, exist_ok=True) + root_dir = tempfile.mkdtemp() if directory is None else directory + print(root_dir) + + # TODO: remove the `files` after the files are uploaded to the NGC + files = [ + { + "path": "models/autoencoder_epoch273.pt", + "url": "https://developer.download.nvidia.com/assets/Clara/monai/tutorials" + "/model_zoo/model_maisi_autoencoder_epoch273_alternative.pt", + }, + { + "path": "models/mask_generation_autoencoder.pt", + "url": "https://developer.download.nvidia.com/assets/Clara/monai" + "/tutorials/mask_generation_autoencoder.pt", + }, + { + "path": "models/mask_generation_diffusion_unet.pt", + "url": "https://developer.download.nvidia.com/assets/Clara/monai" + "/tutorials/model_zoo/model_maisi_mask_generation_diffusion_unet_v2.pt", + }, + { + "path": "configs/all_anatomy_size_condtions.json", + "url": "https://developer.download.nvidia.com/assets/Clara/monai/tutorials/all_anatomy_size_condtions.json", + }, + { + "path": "datasets/all_masks_flexible_size_and_spacing_4000.zip", + "url": "https://developer.download.nvidia.com/assets/Clara/monai" + "/tutorials/all_masks_flexible_size_and_spacing_4000.zip", + }, + ] + + if maisi_version == "maisi3d-ddpm": + files += [ + { + "path": "models/diff_unet_3d_ddpm.pt", + "url": "https://developer.download.nvidia.com/assets/Clara/monai/tutorials/model_zoo" + "/model_maisi_input_unet3d_data-all_steps1000size512ddpm_random_current_inputx_v1_alternative.pt", + }, + { + "path": "models/controlnet_3d_ddpm.pt", + "url": "https://developer.download.nvidia.com/assets/Clara/monai/tutorials/model_zoo" + "/model_maisi_controlnet-20datasets-e20wl100fold0bc_noi_dia_fsize_current_alternative.pt", + }, + { + "path": "configs/candidate_masks_flexible_size_and_spacing_3000.json", + "url": "https://developer.download.nvidia.com/assets/Clara/monai" + "/tutorials/candidate_masks_flexible_size_and_spacing_3000.json", + }, + ] + elif maisi_version == "maisi3d-rflow": + files += [ + { + "path": "models/diff_unet_3d_rflow.pt", + "url": "https://developer.download.nvidia.com/assets/Clara/monai/tutorials/" + "diff_unet_ckpt_rflow_epoch19350.pt", + }, + { + "path": "models/controlnet_3d_rflow.pt", + "url": "https://developer.download.nvidia.com/assets/Clara/monai/tutorials/" + "controlnet_rflow_epoch60.pt", + }, + { + "path": "configs/candidate_masks_flexible_size_and_spacing_4000.json", + "url": "https://developer.download.nvidia.com/assets/Clara/monai" + "/tutorials/candidate_masks_flexible_size_and_spacing_4000.json", + }, + ] + else: + raise ValueError( + f"maisi_version has to be chosen from ['maisi3d-ddpm', 'maisi3d-rflow'], yet got {maisi_version}." + ) + + for file in files: + file["path"] = ( + file["path"] + if "datasets/" not in file["path"] + else os.path.join(root_dir, file["path"]) + ) + download_url(url=file["url"], filepath=file["path"]) + + # ## Read in environment setting, including data directory, model directory, and output directory + # The information for data directory, model directory, and output directory are saved in ./configs/environment.json + env_dict = json.load(open(args.environment_file, "r")) + for k, v in env_dict.items(): + # Update the path to the downloaded dataset in MONAI_DATA_DIRECTORY + val = v if "datasets/" not in v else os.path.join(root_dir, v) + setattr(args, k, val) + print(f"{k}: {val}") + print("Global config variables have been loaded.") + + # ## Read in configuration setting, including network definition, body region and anatomy to generate, etc. + # + # The information for the inference input, like body region and anatomy to generate, is stored in "./configs/config_infer.json". + # Please refer to README.md for the details. + config_dict = json.load(open(args.config_file, "r")) + for k, v in config_dict.items(): + setattr(args, k, v) + + # check the format of inference inputs + config_infer_dict = json.load(open(args.inference_file, "r")) + # override num_split if asked + if "autoencoder_tp_num_splits" in config_infer_dict: + args.autoencoder_def["num_splits"] = config_infer_dict["autoencoder_tp_num_splits"] + args.mask_generation_autoencoder_def["num_splits"] = config_infer_dict[ + "autoencoder_tp_num_splits" + ] + for k, v in config_infer_dict.items(): + setattr(args, k, v) + print(f"{k}: {v}") + + # + # ## Read in optional extra configuration setting - typically acceleration options (TRT) + # + # + if args.extra_config_file is not None: + extra_config_dict = json.load(open(args.extra_config_file, "r")) + for k, v in extra_config_dict.items(): + setattr(args, k, v) + print(f"{k}: {v}") + + check_input( + args.body_region, + args.anatomy_list, + args.label_dict_json, + args.output_size, + args.spacing, + args.controllable_anatomy_size, + ) + latent_shape = [ + args.latent_channels, + args.output_size[0] // 4, + args.output_size[1] // 4, + args.output_size[2] // 4, + ] + print("Network definition and inference inputs have been loaded.") + + # ## Initialize networks and noise scheduler, then load the trained model weights. + # The networks and noise scheduler are defined in `config_file`. We will read them in and load the model weights. + noise_scheduler = define_instance(args, "noise_scheduler") + mask_generation_noise_scheduler = define_instance(args, "mask_generation_noise_scheduler") + + device = torch.device("cuda") + + autoencoder = define_instance(args, "autoencoder").to(device) + checkpoint_autoencoder = torch.load(args.trained_autoencoder_path, weights_only=True) + autoencoder.load_state_dict(checkpoint_autoencoder) + + diffusion_unet = define_instance(args, "diffusion_unet").to(device) + checkpoint_diffusion_unet = torch.load(args.trained_diffusion_path, weights_only=False) + diffusion_unet.load_state_dict(checkpoint_diffusion_unet["unet_state_dict"], strict=True) + scale_factor = checkpoint_diffusion_unet["scale_factor"].to(device) + + controlnet = define_instance(args, "controlnet").to(device) + checkpoint_controlnet = torch.load(args.trained_controlnet_path, weights_only=False) + monai.networks.utils.copy_model_state(controlnet, diffusion_unet.state_dict()) + controlnet.load_state_dict(checkpoint_controlnet["controlnet_state_dict"], strict=True) + + mask_generation_autoencoder = define_instance(args, "mask_generation_autoencoder").to(device) + checkpoint_mask_generation_autoencoder = torch.load( + args.trained_mask_generation_autoencoder_path, weights_only=True + ) + mask_generation_autoencoder.load_state_dict(checkpoint_mask_generation_autoencoder) + + mask_generation_diffusion_unet = define_instance(args, "mask_generation_diffusion").to(device) + checkpoint_mask_generation_diffusion_unet = torch.load( + args.trained_mask_generation_diffusion_path, weights_only=False + ) + mask_generation_diffusion_unet.load_state_dict( + checkpoint_mask_generation_diffusion_unet["unet_state_dict"] + ) + mask_generation_scale_factor = checkpoint_mask_generation_diffusion_unet["scale_factor"] + + print("All the trained model weights have been loaded.") + + # ## Define the LDM Sampler, which contains functions that will perform the inference. + ldm_sampler = LDMSampler( + args.body_region, + args.anatomy_list, + args.all_mask_files_json, + args.all_anatomy_size_conditions_json, + args.all_mask_files_base_dir, + args.label_dict_json, + args.label_dict_remap_json, + autoencoder, + diffusion_unet, + controlnet, + noise_scheduler, + scale_factor, + mask_generation_autoencoder, + mask_generation_diffusion_unet, + mask_generation_scale_factor, + mask_generation_noise_scheduler, + device, + latent_shape, + args.mask_generation_latent_shape, + args.output_size, + args.output_dir, + args.controllable_anatomy_size, + image_output_ext=args.image_output_ext, + label_output_ext=args.label_output_ext, + spacing=args.spacing, + modality=args.modality, + num_inference_steps=args.num_inference_steps, + mask_generation_num_inference_steps=args.mask_generation_num_inference_steps, + random_seed=args.random_seed, + autoencoder_sliding_window_infer_size=args.autoencoder_sliding_window_infer_size, + autoencoder_sliding_window_infer_overlap=args.autoencoder_sliding_window_infer_overlap, + ) + + print(f"The generated image/mask pairs will be saved in {args.output_dir}.") + output_filenames = ldm_sampler.sample_multiple_images(args.num_output_samples) + print("MAISI image/mask generation finished") + + +if __name__ == "__main__": + logging.basicConfig( + stream=sys.stdout, + level=logging.INFO, + format="[%(asctime)s.%(msecs)03d][%(levelname)5s](%(name)s) - %(message)s", + datefmt="%Y-%m-%d %H:%M:%S", + ) + torch.cuda.reset_peak_memory_stats() + main() + peak_memory_gb = torch.cuda.max_memory_allocated() / (1024**3) # Convert to GB + print(f"Peak GPU memory usage: {peak_memory_gb:.2f} GB") diff --git a/itrialspace/src/itrialspace/synthesis/scripts/quality_check.py b/itrialspace/src/itrialspace/synthesis/scripts/quality_check.py new file mode 100644 index 0000000000000000000000000000000000000000..7e5b83ab3a6b46954992fdb62be977cd792d2ee2 --- /dev/null +++ b/itrialspace/src/itrialspace/synthesis/scripts/quality_check.py @@ -0,0 +1,153 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import numpy as np + + +def get_masked_data(label_data, image_data, labels): + """ + Extracts and returns the image data corresponding to specified labels within a 3D volume. + + This function efficiently masks the `image_data` array based on the provided `labels` in the `label_data` array. + The function handles cases with both a large and small number of labels, optimizing performance accordingly. + + Args: + label_data (np.ndarray): A NumPy array containing label data, representing different anatomical + regions or classes in a 3D medical image. + image_data (np.ndarray): A NumPy array containing the image data from which the relevant regions + will be extracted. + labels (list of int): A list of integers representing the label values to be used for masking. + + Returns: + np.ndarray: A NumPy array containing the elements of `image_data` that correspond to the specified + labels in `label_data`. If no labels are provided, an empty array is returned. + + Raises: + ValueError: If `image_data` and `label_data` do not have the same shape. + + Example: + label_int_dict = {"liver": [1], "kidney": [5, 14]} + masked_data = get_masked_data(label_data, image_data, label_int_dict["kidney"]) + """ + + # Check if the shapes of image_data and label_data match + if image_data.shape != label_data.shape: + raise ValueError( + f"Shape mismatch: image_data has shape {image_data.shape}, " + f"but label_data has shape {label_data.shape}. They must be the same." + ) + + if not labels: + return np.array([]) # Return an empty array if no labels are provided + + labels = list(set(labels)) # remove duplicate items + + # Optimize performance based on the number of labels + num_label_acceleration_thresh = 3 + if len(labels) >= num_label_acceleration_thresh: + # if many labels, np.isin is faster + mask = np.isin(label_data, labels) + else: + # Use logical OR to combine masks if the number of labels is small + mask = np.zeros_like(label_data, dtype=bool) + for label in labels: + mask = np.logical_or(mask, label_data == label) + + # Retrieve the masked data + masked_data = image_data[mask.astype(bool)] + + return masked_data + + +def is_outlier(statistics, image_data, label_data, label_int_dict): + """ + Perform a quality check on the generated image by comparing its statistics with precomputed thresholds. + + Args: + statistics (dict): Dictionary containing precomputed statistics including mean +/- 3sigma ranges. + image_data (np.ndarray): The image data to be checked, typically a 3D NumPy array. + label_data (np.ndarray): The label data corresponding to the image, used for masking regions of interest. + label_int_dict (dict): Dictionary mapping label names to their corresponding integer lists. + e.g., label_int_dict = {"liver": [1], "kidney": [5, 14]} + + Returns: + dict: A dictionary with labels as keys, each containing the quality check result, + including whether it's an outlier, the median value, and the thresholds used. + If no data is found for a label, the median value will be `None` and `is_outlier` will be `False`. + + Example: + # Example input data + statistics = { + "liver": { + "sigma_6_low": -21.596463547885904, + "sigma_6_high": 156.27881534763367 + }, + "kidney": { + "sigma_6_low": -15.0, + "sigma_6_high": 120.0 + } + } + label_int_dict = { + "liver": [1], + "kidney": [5, 14] + } + image_data = np.random.rand(100, 100, 100) # Replace with actual image data + label_data = np.zeros((100, 100, 100)) # Replace with actual label data + label_data[40:60, 40:60, 40:60] = 1 # Example region for liver + label_data[70:90, 70:90, 70:90] = 5 # Example region for kidney + result = is_outlier(statistics, image_data, label_data, label_int_dict) + """ + outlier_results = {} + + for label_name, stats in statistics.items(): + # Get the thresholds from the statistics + low_thresh = min( + stats["sigma_6_low"], stats["percentile_0_5"] + ) # or "sigma_12_low" depending on your needs + high_thresh = max( + stats["sigma_6_high"], stats["percentile_99_5"] + ) # or "sigma_12_high" depending on your needs + + if label_name == "bone": + high_thresh = 1000.0 + + # Retrieve the corresponding label integers + labels = label_int_dict.get(label_name, []) + masked_data = get_masked_data(label_data, image_data, labels) + masked_data = masked_data[~np.isnan(masked_data)] + + if len(masked_data) == 0 or masked_data.size == 0: + outlier_results[label_name] = { + "is_outlier": False, + "median_value": None, + "low_thresh": low_thresh, + "high_thresh": high_thresh, + } + continue + + # Compute the median of the masked region + median_value = np.nanmedian(masked_data) + + if np.isnan(median_value): + median_value = None + is_outlier = False + else: + # Determine if the median value is an outlier + is_outlier = median_value < low_thresh or median_value > high_thresh + + outlier_results[label_name] = { + "is_outlier": is_outlier, + "median_value": median_value, + "low_thresh": low_thresh, + "high_thresh": high_thresh, + } + + return outlier_results diff --git a/itrialspace/src/itrialspace/synthesis/scripts/rectified_flow.py b/itrialspace/src/itrialspace/synthesis/scripts/rectified_flow.py new file mode 100644 index 0000000000000000000000000000000000000000..cf402ae222a39c8b943dd76b79387fad212bd9fa --- /dev/null +++ b/itrialspace/src/itrialspace/synthesis/scripts/rectified_flow.py @@ -0,0 +1,337 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# ========================================================================= +# Adapted from https://github.com/hpcaitech/Open-Sora/blob/main/opensora/schedulers/rf/rectified_flow.py +# which has the following license: +# https://github.com/hpcaitech/Open-Sora/blob/main/LICENSE +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ========================================================================= + +from __future__ import annotations + +from typing import Union + +import numpy as np +import torch +from monai.utils import StrEnum +from torch.distributions import LogisticNormal + +from .ddpm import DDPMPredictionType +from .scheduler import Scheduler + + +class RFlowPredictionType(StrEnum): + """ + Set of valid prediction type names for the RFlow scheduler's `prediction_type` argument. + + v_prediction: velocity prediction, see section 2.4 https://imagen.research.google/video/paper.pdf + """ + + V_PREDICTION = DDPMPredictionType.V_PREDICTION + + +def timestep_transform( + t, + input_img_size_numel, + base_img_size_numel=32 * 32 * 32, + scale=1.0, + num_train_timesteps=1000, + spatial_dim=3, +): + """ + Applies a transformation to the timestep based on image resolution scaling. + + Args: + t (torch.Tensor): The original timestep(s). + input_img_size_numel (torch.Tensor): The input image's size (H * W * D). + base_img_size_numel (int): reference H*W*D size, usually smaller than input_img_size_numel. + scale (float): Scaling factor for the transformation. + num_train_timesteps (int): Total number of training timesteps. + spatial_dim (int): Number of spatial dimensions in the image. + + Returns: + torch.Tensor: Transformed timestep(s). + """ + t = t / num_train_timesteps + ratio_space = (input_img_size_numel / base_img_size_numel) ** (1.0 / spatial_dim) + + ratio = ratio_space * scale + new_t = ratio * t / (1 + (ratio - 1) * t) + + new_t = new_t * num_train_timesteps + return new_t + + +class RFlowScheduler(Scheduler): + """ + A rectified flow scheduler for guiding the diffusion process in a generative model. + + Supports uniform and logit-normal sampling methods, timestep transformation for + different resolutions, and noise addition during diffusion. + + Args: + num_train_timesteps (int): Total number of training timesteps. + use_discrete_timesteps (bool): Whether to use discrete timesteps. + sample_method (str): Training time step sampling method ('uniform' or 'logit-normal'). + loc (float): Location parameter for logit-normal distribution, used only if sample_method='logit-normal'. + scale (float): Scale parameter for logit-normal distribution, used only if sample_method='logit-normal'. + use_timestep_transform (bool): Whether to apply timestep transformation. + If true, there will be more inference timesteps at early(noisy) stages for larger image volumes. + transform_scale (float): Scaling factor for timestep transformation, used only if use_timestep_transform=True. + steps_offset (int): Offset added to computed timesteps, used only if use_timestep_transform=True. + base_img_size_numel (int): Reference image volume size for scaling, used only if use_timestep_transform=True. + spatial_dim (int): 2 or 3, incidcating 2D or 3D images, used only if use_timestep_transform=True. + + Example: + + .. code-block:: python + + # define a scheduler + noise_scheduler = RFlowScheduler( + num_train_timesteps = 1000, + use_discrete_timesteps = True, + sample_method = 'logit-normal', + use_timestep_transform = True, + base_img_size_numel = 32 * 32 * 32, + spatial_dim = 3 + ) + + # during training + inputs = torch.ones(2,4,64,64,32) + noise = torch.randn_like(inputs) + timesteps = noise_scheduler.sample_timesteps(inputs) + noisy_inputs = noise_scheduler.add_noise(original_samples=inputs, noise=noise, timesteps=timesteps) + predicted_velocity = diffusion_unet( + x=noisy_inputs, + timesteps=timesteps + ) + loss = loss_l1(predicted_velocity, (inputs - noise)) + + # during inference + noisy_inputs = torch.randn(2,4,64,64,32) + input_img_size_numel = torch.prod(torch.tensor(noisy_inputs.shape[-3:]) + noise_scheduler.set_timesteps( + num_inference_steps=30, input_img_size_numel=input_img_size_numel) + ) + all_next_timesteps = torch.cat( + (noise_scheduler.timesteps[1:], torch.tensor([0], dtype=noise_scheduler.timesteps.dtype)) + ) + for t, next_t in tqdm( + zip(noise_scheduler.timesteps, all_next_timesteps), + total=min(len(noise_scheduler.timesteps), len(all_next_timesteps)), + ): + predicted_velocity = diffusion_unet( + x=noisy_inputs, + timesteps=timesteps + ) + noisy_inputs, _ = noise_scheduler.step(predicted_velocity, t, noisy_inputs, next_t) + final_output = noisy_inputs + """ + + def __init__( + self, + num_train_timesteps: int = 1000, + use_discrete_timesteps: bool = True, + sample_method: str = "uniform", + loc: float = 0.0, + scale: float = 1.0, + use_timestep_transform: bool = False, + transform_scale: float = 1.0, + steps_offset: int = 0, + base_img_size_numel: int = 32 * 32 * 32, + spatial_dim: int = 3, + ): + # rectified flow only accepts velocity prediction + self.prediction_type = RFlowPredictionType.V_PREDICTION + + self.num_train_timesteps = num_train_timesteps + self.use_discrete_timesteps = use_discrete_timesteps + self.base_img_size_numel = base_img_size_numel + self.spatial_dim = spatial_dim + + # sample method + if sample_method not in ["uniform", "logit-normal"]: + raise ValueError( + f"sample_method = {sample_method}, which has to be chosen from ['uniform', 'logit-normal']." + ) + self.sample_method = sample_method + if sample_method == "logit-normal": + self.distribution = LogisticNormal(torch.tensor([loc]), torch.tensor([scale])) + self.sample_t = lambda x: self.distribution.sample((x.shape[0],))[:, 0].to(x.device) + + # timestep transform + self.use_timestep_transform = use_timestep_transform + self.transform_scale = transform_scale + self.steps_offset = steps_offset + + def add_noise( + self, original_samples: torch.Tensor, noise: torch.Tensor, timesteps: torch.Tensor + ) -> torch.Tensor: + """ + Add noise to the original samples. + + Args: + original_samples: original samples + noise: noise to add to samples + timesteps: timesteps tensor with shape of (N,), indicating the timestep to be computed for each sample. + + Returns: + noisy_samples: sample with added noise + """ + timepoints: torch.Tensor = timesteps.float() / self.num_train_timesteps + timepoints = 1 - timepoints # [1,1/1000] + + # expand timepoint to noise shape + if noise.ndim == 5: + timepoints = timepoints[..., None, None, None, None].expand(-1, *noise.shape[1:]) + elif noise.ndim == 4: + timepoints = timepoints[..., None, None, None].expand(-1, *noise.shape[1:]) + else: + raise ValueError( + f"noise tensor has to be 4D or 5D tensor, yet got shape of {noise.shape}" + ) + + noisy_samples: torch.Tensor = timepoints * original_samples + (1 - timepoints) * noise + + return noisy_samples + + def set_timesteps( + self, + num_inference_steps: int, + device: str | torch.device | None = None, + input_img_size_numel: int | None = None, + ) -> None: + """ + Sets the discrete timesteps used for the diffusion chain. Supporting function to be run before inference. + + Args: + num_inference_steps: number of diffusion steps used when generating samples with a pre-trained model. + device: target device to put the data. + input_img_size_numel: int, H*W*D of the image, used with self.use_timestep_transform is True. + """ + if num_inference_steps > self.num_train_timesteps or num_inference_steps < 1: + raise ValueError( + f"`num_inference_steps`: {num_inference_steps} should be at least 1, " + "and cannot be larger than `self.num_train_timesteps`:" + f" {self.num_train_timesteps} as the unet model trained with this scheduler can only handle" + f" maximal {self.num_train_timesteps} timesteps." + ) + + self.num_inference_steps = num_inference_steps + # prepare timesteps + timesteps = [ + (1.0 - i / self.num_inference_steps) * self.num_train_timesteps + for i in range(self.num_inference_steps) + ] + if self.use_discrete_timesteps: + timesteps = [int(round(t)) for t in timesteps] + if self.use_timestep_transform: + timesteps = [ + timestep_transform( + t, + input_img_size_numel=input_img_size_numel, + base_img_size_numel=self.base_img_size_numel, + num_train_timesteps=self.num_train_timesteps, + spatial_dim=self.spatial_dim, + ) + for t in timesteps + ] + timesteps_np = np.array(timesteps).astype(np.float16) + if self.use_discrete_timesteps: + timesteps_np = timesteps_np.astype(np.int64) + self.timesteps = torch.from_numpy(timesteps_np).to(device) + self.timesteps += self.steps_offset + + def sample_timesteps(self, x_start): + """ + Randomly samples training timesteps using the chosen sampling method. + + Args: + x_start (torch.Tensor): The input tensor for sampling. + + Returns: + torch.Tensor: Sampled timesteps. + """ + if self.sample_method == "uniform": + t = torch.rand((x_start.shape[0],), device=x_start.device) * self.num_train_timesteps + elif self.sample_method == "logit-normal": + t = self.sample_t(x_start) * self.num_train_timesteps + + if self.use_discrete_timesteps: + t = t.long() + + if self.use_timestep_transform: + input_img_size_numel = torch.prod(torch.tensor(x_start.shape[2:])) + t = timestep_transform( + t, + input_img_size_numel=input_img_size_numel, + base_img_size_numel=self.base_img_size_numel, + num_train_timesteps=self.num_train_timesteps, + spatial_dim=len(x_start.shape) - 2, + ) + + return t + + def step( + self, + model_output: torch.Tensor, + timestep: int, + sample: torch.Tensor, + next_timestep: Union[int, None] = None, + ) -> tuple[torch.Tensor, torch.Tensor]: + """ + Predicts the next sample in the diffusion process. + + Args: + model_output (torch.Tensor): Output from the trained diffusion model. + timestep (int): Current timestep in the diffusion chain. + sample (torch.Tensor): Current sample in the process. + next_timestep (Union[int, None]): Optional next timestep. + + Returns: + tuple[torch.Tensor, torch.Tensor]: Predicted sample at the next step and additional info. + """ + # Ensure num_inference_steps exists and is a valid integer + if not hasattr(self, "num_inference_steps") or not isinstance( + self.num_inference_steps, int + ): + raise AttributeError( + "num_inference_steps is missing or not an integer in the class." + "Please run self.set_timesteps(num_inference_steps,device,input_img_size_numel) to set it." + ) + + v_pred = model_output + + if next_timestep is not None: + next_timestep = int(next_timestep) + dt: float = ( + float(timestep - next_timestep) / self.num_train_timesteps + ) # Now next_timestep is guaranteed to be int + else: + dt = ( + 1.0 / float(self.num_inference_steps) if self.num_inference_steps > 0 else 0.0 + ) # Avoid division by zero + + pred_post_sample = sample + v_pred * dt + pred_original_sample = sample + v_pred * timestep / self.num_train_timesteps + + return pred_post_sample, pred_original_sample diff --git a/itrialspace/src/itrialspace/synthesis/scripts/sample.py b/itrialspace/src/itrialspace/synthesis/scripts/sample.py new file mode 100644 index 0000000000000000000000000000000000000000..2a96cdf57de004c1c51ec69544c0a7d30d389479 --- /dev/null +++ b/itrialspace/src/itrialspace/synthesis/scripts/sample.py @@ -0,0 +1,1228 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import gc +import json +import logging +import math +import os +import random +import time +import warnings +from datetime import datetime + +import monai +import torch +from monai.data import MetaTensor +from monai.inferers.inferer import DiffusionInferer, SlidingWindowInferer +from monai.networks.schedulers import DDPMScheduler, RFlowScheduler +from monai.transforms import Compose, SaveImage +from monai.utils import set_determinism +from tqdm import tqdm + +from .augmentation import augmentation +from .find_masks import find_masks +from .quality_check import is_outlier +from .utils import ( + binarize_labels, + dynamic_infer, + general_mask_generation_post_process, + get_body_region_index_from_mask, + remap_labels, +) + + +class ReconModel(torch.nn.Module): + """ + A PyTorch module for reconstructing images from latent representations. + + Attributes: + autoencoder: The autoencoder model used for decoding. + scale_factor: Scaling factor applied to the input before decoding. + """ + + def __init__(self, autoencoder, scale_factor): + super().__init__() + self.autoencoder = autoencoder + self.scale_factor = scale_factor + + def forward(self, z): + """ + Decode the input latent representation to an image. + + Args: + z (torch.Tensor): The input latent representation. + + Returns: + torch.Tensor: The reconstructed image. + """ + recon_pt_nda = self.autoencoder.decode_stage_2_outputs(z / self.scale_factor) + return recon_pt_nda + + +def initialize_noise_latents(latent_shape, device): + """ + Initialize random noise latents for image generation with float16. + + Args: + latent_shape (tuple): The shape of the latent space. + device (torch.device): The device to create the tensor on. + + Returns: + torch.Tensor: Initialized noise latents. + """ + return ( + torch.randn( + [ + 1, + ] + + list(latent_shape) + ) + .half() + .to(device) + ) + + +def ldm_conditional_sample_one_mask( + autoencoder, + diffusion_unet, + noise_scheduler, + scale_factor, + anatomy_size, + device, + latent_shape, + label_dict_remap_json, + num_inference_steps=1000, + autoencoder_sliding_window_infer_size=[96, 96, 96], + autoencoder_sliding_window_infer_overlap=0.6667, +): + """ + Generate a single synthetic mask using a latent diffusion model. + + Args: + autoencoder (nn.Module): The autoencoder model. + diffusion_unet (nn.Module): The diffusion U-Net model. + noise_scheduler: The noise scheduler for the diffusion process. + scale_factor (float): Scaling factor for the latent space. + anatomy_size (torch.Tensor): Tensor specifying the desired anatomy sizes. + device (torch.device): The device to run the computation on. + latent_shape (tuple): The shape of the latent space. + label_dict_remap_json (str): Path to the JSON file for label remapping. + num_inference_steps (int): Number of inference steps for the diffusion process. + autoencoder_sliding_window_infer_size (list, optional): Size of the sliding window for inference. Defaults to [96, 96, 96]. + autoencoder_sliding_window_infer_overlap (float, optional): Overlap ratio for sliding window inference. Defaults to 0.6667. + + Returns: + torch.Tensor: The generated synthetic mask. + """ + recon_model = ReconModel(autoencoder=autoencoder, scale_factor=scale_factor).to(device) + + with torch.no_grad(), torch.amp.autocast("cuda"): + # Generate random noise + latents = initialize_noise_latents(latent_shape, device) + anatomy_size = torch.FloatTensor(anatomy_size).unsqueeze(0).unsqueeze(0).half().to(device) + # synthesize latents + if ( + isinstance(noise_scheduler, DDPMScheduler) + and num_inference_steps < noise_scheduler.num_train_timesteps + ): + warnings.warn( + "**************************************************************\n" + "* WARNING: Mask noise_scheduler is a DDPMScheduler.\n" + "* We expect num_inference_steps = noise_scheduler.num_train_timesteps" + f" = {noise_scheduler.num_train_timesteps}.\n" + f"* Yet got num_inference_steps = {num_inference_steps}.\n" + "* The generated image quality is not guaranteed.\n" + "**************************************************************" + ) + + noise_scheduler.set_timesteps(num_inference_steps=num_inference_steps) + # mask generator is DDPM + inferer_ddpm = DiffusionInferer(noise_scheduler) + latents = inferer_ddpm.sample( + input_noise=latents, + diffusion_model=diffusion_unet, + scheduler=noise_scheduler, + verbose=True, + conditioning=anatomy_size.to(device), + ) + + inferer = SlidingWindowInferer( + roi_size=autoencoder_sliding_window_infer_size, + sw_batch_size=1, + progress=True, + mode="gaussian", + overlap=autoencoder_sliding_window_infer_overlap, + sw_device=device, + device=torch.device("cpu"), + ) + synthetic_mask = dynamic_infer(inferer, recon_model, latents) + synthetic_mask = torch.softmax(synthetic_mask, dim=1) + synthetic_mask = torch.argmax(synthetic_mask, dim=1, keepdim=True) + # mapping raw index to 132 labels + synthetic_mask = remap_labels(synthetic_mask, label_dict_remap_json) + + ###### post process ##### + data = synthetic_mask.squeeze().cpu().detach().numpy() + + labels = [23, 24, 26, 27, 128] + target_tumor_label = None + for index, size in enumerate(anatomy_size[0, 0, 5:10]): + if size.item() != -1.0: + target_tumor_label = labels[index] + + logging.info(f"target_tumor_label for postprocess:{target_tumor_label}") + data = general_mask_generation_post_process( + data, target_tumor_label=target_tumor_label, device=device + ) + synthetic_mask = torch.from_numpy(data).unsqueeze(0).unsqueeze(0).to(device) + + return synthetic_mask + + +def ldm_conditional_sample_one_image( + autoencoder, + diffusion_unet, + controlnet, + noise_scheduler, + scale_factor, + device, + combine_label_or, + spacing_tensor, + latent_shape, + output_size, + noise_factor, + top_region_index_tensor=None, + bottom_region_index_tensor=None, + modality_tensor=None, + num_inference_steps=1000, + autoencoder_sliding_window_infer_size=[96, 96, 96], + autoencoder_sliding_window_infer_overlap=0.6667, +): + """ + Generate a single synthetic image using a latent diffusion model with controlnet. + + Args: + autoencoder (nn.Module): The autoencoder model. + diffusion_unet (nn.Module): The diffusion U-Net model. + controlnet (nn.Module): The controlnet model. + noise_scheduler: The noise scheduler for the diffusion process. + scale_factor (float): Scaling factor for the latent space. + device (torch.device): The device to run the computation on. + combine_label_or (torch.Tensor): The combined label tensor. + spacing_tensor (torch.Tensor): Tensor specifying the spacing. + latent_shape (tuple): The shape of the latent space. + output_size (tuple): The desired output size of the image. + noise_factor (float): Factor to scale the initial noise. + top_region_index_tensor (torch.Tensor): Tensor specifying the top region index. Defaults to None. + bottom_region_index_tensor (torch.Tensor): Tensor specifying the bottom region index. Defaults to None. + modality_tensor (torch.Tensor): Int Tensor specifying the modality. + num_inference_steps (int): Number of inference steps for the diffusion process. + autoencoder_sliding_window_infer_size (list, optional): Size of the sliding window for inference. Defaults to [96, 96, 96]. + autoencoder_sliding_window_infer_overlap (float, optional): Overlap ratio for sliding window inference. Defaults to 0.6667. + + Returns: + tuple: A tuple containing the synthetic image and its corresponding label. + """ + # CT image intensity range + a_min = -1000 + a_max = 1000 + # autoencoder output intensity range + b_min = 0.0 + b_max = 1 + + include_body_region = diffusion_unet.include_top_region_index_input + include_modality = diffusion_unet.num_class_embeds is not None + + recon_model = ReconModel(autoencoder=autoencoder, scale_factor=scale_factor).to(device) + + with torch.no_grad(), torch.amp.autocast("cuda"): + logging.info("---- Start generating latent features... ----") + start_time = time.time() + # generate segmentation mask + combine_label = combine_label_or.to(device) + if ( + output_size[0] != combine_label.shape[2] + or output_size[1] != combine_label.shape[3] + or output_size[2] != combine_label.shape[4] + ): + logging.info( + "output_size is not a desired value. Need to interpolate the mask to match with output_size. The result image will be very low quality." + ) + combine_label = torch.nn.functional.interpolate( + combine_label, size=output_size, mode="nearest" + ) + + controlnet_cond_vis = binarize_labels(combine_label.as_tensor().long()).half() + + # Generate random noise + latents = initialize_noise_latents(latent_shape, device) * noise_factor + + # synthesize latents + if isinstance(noise_scheduler, RFlowScheduler): + noise_scheduler.set_timesteps( + num_inference_steps=num_inference_steps, + input_img_size_numel=torch.prod(torch.tensor(latents.shape[2:])), + ) + else: + noise_scheduler.set_timesteps(num_inference_steps=num_inference_steps) + + if ( + isinstance(noise_scheduler, DDPMScheduler) + and num_inference_steps < noise_scheduler.num_train_timesteps + ): + warnings.warn( + "**************************************************************\n" + "* WARNING: Image noise_scheduler is a DDPMScheduler.\n" + "* We expect num_inference_steps = noise_scheduler.num_train_timesteps" + f" = {noise_scheduler.num_train_timesteps}.\n" + f"* Yet got num_inference_steps = {num_inference_steps}.\n" + "* The generated image quality is not guaranteed.\n" + "**************************************************************" + ) + + all_timesteps = noise_scheduler.timesteps + all_next_timesteps = torch.cat( + (all_timesteps[1:], torch.tensor([0], dtype=all_timesteps.dtype)) + ) + progress_bar = tqdm( + zip(all_timesteps, all_next_timesteps), + total=min(len(all_timesteps), len(all_next_timesteps)), + ) + for t, next_t in progress_bar: + # get controlnet output + # Create a dictionary to store the inputs + controlnet_inputs = { + "x": latents, + "timesteps": torch.Tensor((t,)).to(device), + "controlnet_cond": controlnet_cond_vis, + } + if include_modality: + controlnet_inputs.update( + { + "class_labels": modality_tensor, + } + ) + down_block_res_samples, mid_block_res_sample = controlnet(**controlnet_inputs) + + # get diffusion network output + # Create a dictionary to store the inputs + unet_inputs = { + "x": latents, + "timesteps": torch.Tensor((t,)).to(device), + "spacing_tensor": spacing_tensor, + "down_block_additional_residuals": down_block_res_samples, + "mid_block_additional_residual": mid_block_res_sample, + } + # Add extra arguments if include_body_region is True + if include_body_region: + unet_inputs.update( + { + "top_region_index_tensor": top_region_index_tensor, + "bottom_region_index_tensor": bottom_region_index_tensor, + } + ) + if include_modality: + unet_inputs.update( + { + "class_labels": modality_tensor, + } + ) + model_output = diffusion_unet(**unet_inputs) + + if not isinstance(noise_scheduler, RFlowScheduler): + latents, _ = noise_scheduler.step(model_output, t, latents) # type: ignore + else: + latents, _ = noise_scheduler.step(model_output, t, latents, next_t) # type: ignore + end_time = time.time() + logging.info( + f"---- DM/ControlNet Latent features generation time: {end_time - start_time} seconds ----" + ) + del ( + unet_inputs, + controlnet_inputs, + model_output, + controlnet_cond_vis, + down_block_res_samples, + mid_block_res_sample, + ) + gc.collect() + torch.cuda.empty_cache() + + # decode latents to synthesized images + logging.info("---- Start decoding latent features into images... ----") + start_time = time.time() + + inferer = SlidingWindowInferer( + roi_size=autoencoder_sliding_window_infer_size, + sw_batch_size=1, + progress=True, + mode="gaussian", + overlap=autoencoder_sliding_window_infer_overlap, + sw_device=device, + device=torch.device("cpu"), + ) + synthetic_images = dynamic_infer(inferer, recon_model, latents) + synthetic_images = torch.clip(synthetic_images, b_min, b_max).cpu() + end_time = time.time() + logging.info(f"---- Image VAE decoding time: {end_time - start_time} seconds ----") + + ## post processing: + # project output to [0, 1] + synthetic_images = (synthetic_images - b_min) / (b_max - b_min) + # project output to [-1000, 1000] + synthetic_images = synthetic_images * (a_max - a_min) + a_min + # regularize background intensities + synthetic_images = crop_img_body_mask(synthetic_images, combine_label) + torch.cuda.empty_cache() + + return synthetic_images, combine_label + + +def filter_mask_with_organs(combine_label, anatomy_list): + """ + Filter a mask to only include specified organs. + + Args: + combine_label (torch.Tensor): The input mask. + anatomy_list (list): List of organ labels to keep. + + Returns: + torch.Tensor: The filtered mask. + """ + # final output mask file has shape of output_size, contains labels in anatomy_list + # it is already interpolated to target size + combine_label = combine_label.long() + # filter out the organs that are not in anatomy_list + for i in range(len(anatomy_list)): + organ = anatomy_list[i] + # replace it with a negative value so it will get mixed + combine_label[combine_label == organ] = -(i + 1) + # zero-out voxels with value not in anatomy_list + combine_label[combine_label > 0] = 0 + # output positive values + combine_label = -combine_label + return combine_label + + +def crop_img_body_mask(synthetic_images, combine_label): + """ + Crop the synthetic image using a body mask. + + Args: + synthetic_images (torch.Tensor): The synthetic images. + combine_label (torch.Tensor): The body mask. + + Returns: + torch.Tensor: The cropped synthetic images. + """ + synthetic_images[combine_label == 0] = -1000 + return synthetic_images + + +def check_input( + body_region, + anatomy_list, + label_dict_json, + output_size, + spacing, + controllable_anatomy_size=[("pancreas", 0.5)], +): + """ + Validate input parameters for image generation. + + Args: + body_region (list): List of body regions. + anatomy_list (list): List of anatomical structures. + label_dict_json (str): Path to the label dictionary JSON file. + output_size (tuple): Desired output size of the image. + spacing (tuple): Desired voxel spacing. + controllable_anatomy_size (list): List of tuples specifying controllable anatomy sizes. + + Raises: + ValueError: If any input parameter is invalid. + """ + # check output_size and spacing format + if output_size[0] != output_size[1]: + raise ValueError( + f"The first two components of output_size need to be equal, yet got {output_size}." + ) + if (output_size[0] not in [256, 384, 512]) or ( + output_size[2] not in [128, 256, 384, 512, 640, 768] + ): + raise ValueError( + f"The output_size[0] have to be chosen from [256, 384, 512], and output_size[2] have to be chosen from [128, 256, 384, 512, 640, 768], yet got {output_size}." + ) + + if spacing[0] != spacing[1]: + raise ValueError( + f"The first two components of spacing need to be equal, yet got {spacing}." + ) + if spacing[0] < 0.5 or spacing[0] > 3.0 or spacing[2] < 0.5 or spacing[2] > 5.0: + raise ValueError( + f"spacing[0] have to be between 0.5 and 3.0 mm, spacing[2] have to be between 0.5 and 5.0 mm, yet got {spacing}." + ) + + if output_size[0] * spacing[0] < 256: + FOV = [output_size[axis] * spacing[axis] for axis in range(3)] + raise ValueError( + f"`'spacing'({spacing}mm) and 'output_size'({output_size}) together decide the output field of view (FOV). The FOV will be {FOV}mm. We recommend the FOV in x and y axis to be at least 256mm for head, and at least 384mm for other body regions like abdomen. There is no such restriction for z-axis." + ) + + if controllable_anatomy_size == None: + logging.info("`controllable_anatomy_size` is not provided.") + return + + # check controllable_anatomy_size format + if len(controllable_anatomy_size) > 10: + raise ValueError( + f"The length of list controllable_anatomy_size has to be less than 10. Yet got length equal to {len(controllable_anatomy_size)}." + ) + available_controllable_organ = [ + "liver", + "gallbladder", + "stomach", + "pancreas", + "colon", + ] + available_controllable_tumor = [ + "hepatic tumor", + "bone lesion", + "lung tumor", + "colon cancer primaries", + "pancreatic tumor", + ] + available_controllable_anatomy = available_controllable_organ + available_controllable_tumor + controllable_tumor = [] + controllable_organ = [] + for controllable_anatomy_size_pair in controllable_anatomy_size: + if controllable_anatomy_size_pair[0] not in available_controllable_anatomy: + raise ValueError( + f"The controllable_anatomy have to be chosen from {available_controllable_anatomy}, yet got {controllable_anatomy_size_pair[0]}." + ) + if controllable_anatomy_size_pair[0] in available_controllable_tumor: + controllable_tumor += [controllable_anatomy_size_pair[0]] + if controllable_anatomy_size_pair[0] in available_controllable_organ: + controllable_organ += [controllable_anatomy_size_pair[0]] + if controllable_anatomy_size_pair[1] == -1: + continue + if controllable_anatomy_size_pair[1] < 0 or controllable_anatomy_size_pair[1] > 1.0: + raise ValueError( + f"The controllable size scale have to be between 0 and 1,0, or equal to -1, yet got {controllable_anatomy_size_pair[1]}." + ) + if len(controllable_tumor + controllable_organ) != len( + list(set(controllable_tumor + controllable_organ)) + ): + raise ValueError( + f"Please do not repeat controllable_anatomy. Got {controllable_tumor + controllable_organ}." + ) + if len(controllable_tumor) > 1: + raise ValueError(f"Only one controllable tumor is supported. Yet got {controllable_tumor}.") + + if len(controllable_anatomy_size) > 0: + logging.info( + f"`controllable_anatomy_size` is not empty.\nWe will ignore `body_region` and `anatomy_list` and synthesize based on `controllable_anatomy_size`: ({controllable_anatomy_size})." + ) + else: + logging.info( + f"`controllable_anatomy_size` is empty.\nWe will synthesize based on `body_region`: ({body_region}) and `anatomy_list`: ({anatomy_list})." + ) + # check body_region format + available_body_region = [ + "head", + "chest", + "thorax", + "abdomen", + "pelvis", + "lower", + ] + for region in body_region: + if region not in available_body_region: + raise ValueError( + f"The components in body_region have to be chosen from {available_body_region}, yet got {region}." + ) + + # check anatomy_list format + with open(label_dict_json) as f: + label_dict = json.load(f) + for anatomy in anatomy_list: + if anatomy not in label_dict.keys(): + raise ValueError( + f"The components in anatomy_list have to be chosen from {label_dict.keys()}, yet got {anatomy}." + ) + logging.info( + f"The generate results will have voxel size to be {spacing}mm, volume size to be {output_size}." + ) + + return + + +class LDMSampler: + """ + A sampler class for generating synthetic medical images and masks using latent diffusion models. + + Attributes: + Various attributes related to model configuration, input parameters, and generation settings. + """ + + def __init__( + self, + body_region, + anatomy_list, + all_mask_files_json, + all_anatomy_size_condtions_json, + all_mask_files_base_dir, + label_dict_json, + label_dict_remap_json, + autoencoder, + diffusion_unet, + controlnet, + noise_scheduler, + scale_factor, + mask_generation_autoencoder, + mask_generation_diffusion_unet, + mask_generation_scale_factor, + mask_generation_noise_scheduler, + device, + latent_shape, + mask_generation_latent_shape, + output_size, + output_dir, + controllable_anatomy_size, + image_output_ext=".nii.gz", + label_output_ext=".nii.gz", + real_img_median_statistics="./configs/image_median_statistics.json", + spacing=[1, 1, 1], + modality=1, + num_inference_steps=None, + mask_generation_num_inference_steps=None, + random_seed=None, + autoencoder_sliding_window_infer_size=[96, 96, 96], + autoencoder_sliding_window_infer_overlap=0.6667, + ) -> None: + """ + Initialize the LDMSampler with various parameters and models. + + Args: + Various parameters related to model configuration, input settings, and output specifications. + """ + self.random_seed = random_seed + if random_seed is not None: + set_determinism(seed=random_seed) + + with open(label_dict_json, "r") as f: + label_dict = json.load(f) + self.all_anatomy_size_condtions_json = all_anatomy_size_condtions_json + + # intialize variables + self.body_region = body_region + self.anatomy_list = [label_dict[organ] for organ in anatomy_list] + self.all_mask_files_json = all_mask_files_json + self.data_root = all_mask_files_base_dir + self.label_dict_remap_json = label_dict_remap_json + self.autoencoder = autoencoder + self.diffusion_unet = diffusion_unet + self.controlnet = controlnet + self.noise_scheduler = noise_scheduler + self.scale_factor = scale_factor + self.mask_generation_autoencoder = mask_generation_autoencoder + self.mask_generation_diffusion_unet = mask_generation_diffusion_unet + self.mask_generation_scale_factor = mask_generation_scale_factor + self.mask_generation_noise_scheduler = mask_generation_noise_scheduler + self.device = device + self.latent_shape = latent_shape + self.mask_generation_latent_shape = mask_generation_latent_shape + self.output_size = output_size + self.output_dir = output_dir + self.noise_factor = 1.0 + self.controllable_anatomy_size = controllable_anatomy_size + if len(self.controllable_anatomy_size): + logging.info("controllable_anatomy_size is given, mask generation is triggered!") + # overwrite the anatomy_list by given organs in self.controllable_anatomy_size + self.anatomy_list = [ + label_dict[organ_and_size[0]] for organ_and_size in self.controllable_anatomy_size + ] + self.image_output_ext = image_output_ext + self.label_output_ext = label_output_ext + # Set the default value for number of inference steps to 1000 + self.num_inference_steps = num_inference_steps if num_inference_steps is not None else 1000 + self.mask_generation_num_inference_steps = ( + mask_generation_num_inference_steps + if mask_generation_num_inference_steps is not None + else 1000 + ) + + if any(size % 16 != 0 for size in autoencoder_sliding_window_infer_size): + raise ValueError( + f"autoencoder_sliding_window_infer_size must be divisible by 16.\n Got {autoencoder_sliding_window_infer_size}" + ) + if not (0 <= autoencoder_sliding_window_infer_overlap <= 1): + raise ValueError( + f"Value of autoencoder_sliding_window_infer_overlap must be between 0 and 1.\n Got {autoencoder_sliding_window_infer_overlap}" + ) + self.autoencoder_sliding_window_infer_size = autoencoder_sliding_window_infer_size + self.autoencoder_sliding_window_infer_overlap = autoencoder_sliding_window_infer_overlap + + # quality check args + self.max_try_time = 2 # if not pass quality check, will try self.max_try_time times + with open(real_img_median_statistics, "r") as json_file: + self.median_statistics = json.load(json_file) + self.label_int_dict = { + "liver": [1], + "spleen": [3], + "pancreas": [4], + "kidney": [5, 14], + "lung": [28, 29, 30, 31, 31], + "brain": [22], + "hepatic tumor": [26], + "bone lesion": [128], + "lung tumor": [23], + "colon cancer primaries": [27], + "pancreatic tumor": [24], + "bone": list(range(33, 57)) + list(range(63, 98)) + [120, 122, 127], + } + + # networks + self.autoencoder.eval() + self.diffusion_unet.eval() + self.controlnet.eval() + self.mask_generation_autoencoder.eval() + self.mask_generation_diffusion_unet.eval() + + self.spacing = spacing + self.modality_tensor = modality * torch.ones((1,), dtype=torch.long).to(device) + self.include_body_region = self.diffusion_unet.include_top_region_index_input + self.include_modality = self.diffusion_unet.num_class_embeds is not None + + val_transforms_list = [ + monai.transforms.LoadImaged(keys=["pseudo_label"]), + monai.transforms.EnsureChannelFirstd(keys=["pseudo_label"]), + monai.transforms.Orientationd(keys=["pseudo_label"], axcodes="RAS"), + monai.transforms.EnsureTyped(keys=["pseudo_label"], dtype=torch.uint8), + monai.transforms.Lambdad(keys="spacing", func=lambda x: torch.FloatTensor(x)), + monai.transforms.Lambdad(keys="spacing", func=lambda x: x * 1e2), + ] + if self.include_body_region: + val_transforms_list += [ + monai.transforms.Lambdad( + keys="top_region_index", func=lambda x: torch.FloatTensor(x) + ), + monai.transforms.Lambdad( + keys="bottom_region_index", func=lambda x: torch.FloatTensor(x) + ), + monai.transforms.Lambdad(keys="top_region_index", func=lambda x: x * 1e2), + monai.transforms.Lambdad(keys="bottom_region_index", func=lambda x: x * 1e2), + ] + + self.val_transforms = Compose(val_transforms_list) + logging.info("LDM sampler initialized.") + + def sample_multiple_images(self, num_img): + """ + Generate multiple synthetic images and masks. + + Args: + num_img (int): Number of images to generate. + """ + modality_tensor = self.modality_tensor + output_filenames = [] + if len(self.controllable_anatomy_size) > 0: + # we will use mask generation instead of finding candidate masks + # create a dummy selected_mask_files for placeholder + selected_mask_files = list(range(num_img)) + # prerpare organ size conditions + anatomy_size_condtion = self.prepare_anatomy_size_condtion( + self.controllable_anatomy_size + ) + else: + need_resample = False + # find candidate mask and save to candidate_mask_files + candidate_mask_files = find_masks( + self.body_region, + self.anatomy_list, + self.spacing, + self.output_size, + True, + self.all_mask_files_json, + self.data_root, + ) + if len(candidate_mask_files) < num_img: + # if we cannot find enough masks based on the exact match of anatomy list, spacing, and output size, + # then we will try to find the closest mask in terms of spacing, and output size. + logging.info("Resample mask file to get desired output size and spacing") + candidate_mask_files = self.find_closest_masks(num_img) + need_resample = True + + selected_mask_files = self.select_mask(candidate_mask_files, num_img) + logging.info(f"Images will be generated based on {selected_mask_files}.") + if len(selected_mask_files) < num_img: + raise ValueError( + ( + f"len(selected_mask_files) ({len(selected_mask_files)}) < num_img ({num_img}). " + "This should not happen. Please revisit function select_mask(self, candidate_mask_files, num_img)." + ) + ) + + num_generated_img = 0 + for index_s in range(len(selected_mask_files)): + item = selected_mask_files[index_s] + if num_generated_img >= num_img: + break + logging.info("---- Start preparing masks... ----") + start_time = time.time() + if len(self.controllable_anatomy_size) > 0: + # generate a synthetic mask + ( + combine_label_or, + top_region_index_tensor, + bottom_region_index_tensor, + spacing_tensor, + ) = self.prepare_one_mask_and_meta_info(anatomy_size_condtion) + else: + # read in mask file + mask_file = item["mask_file"] + if_aug = item["if_aug"] + ( + combine_label_or, + top_region_index_tensor, + bottom_region_index_tensor, + spacing_tensor, + ) = self.read_mask_information(mask_file) + if need_resample: + combine_label_or = self.ensure_output_size_and_spacing(combine_label_or) + # mask augmentation + if if_aug: + combine_label_or = augmentation( + combine_label_or, self.output_size, self.random_seed + ) + end_time = time.time() + logging.info(f"---- Mask preparation time: {end_time - start_time} seconds ----") + torch.cuda.empty_cache() + # generate image/label pairs + to_generate = True + try_time = 0 + # start generation + synthetic_images, synthetic_labels = self.sample_one_pair( + combine_label_or, + top_region_index_tensor, + bottom_region_index_tensor, + spacing_tensor, + modality_tensor, + ) + # synthetic image quality check + pass_quality_check = self.quality_check( + synthetic_images.cpu().detach().numpy(), combine_label_or.cpu().detach().numpy() + ) + print(num_img - num_generated_img, (len(selected_mask_files) - index_s)) + if pass_quality_check or (num_img - num_generated_img) >= ( + len(selected_mask_files) - index_s + ): + if not pass_quality_check: + logging.info( + "Generated image/label pair did not pass quality check, but will still save them. " + "Please consider changing spacing and output_size to facilitate a more realistic setting." + ) + num_generated_img = num_generated_img + 1 + # save image/label pairs + output_postfix = datetime.now().strftime("%Y%m%d_%H%M%S_%f") + synthetic_labels.meta["filename_or_obj"] = "sample.nii.gz" + synthetic_images = MetaTensor(synthetic_images, meta=synthetic_labels.meta) + img_saver = SaveImage( + output_dir=self.output_dir, + output_postfix=output_postfix + "_image", + output_ext=self.image_output_ext, + separate_folder=False, + ) + img_saver(synthetic_images[0]) + synthetic_images_filename = os.path.join( + self.output_dir, "sample_" + output_postfix + "_image" + self.image_output_ext + ) + # filter out the organs that are not in anatomy_list + synthetic_labels = filter_mask_with_organs(synthetic_labels, self.anatomy_list) + label_saver = SaveImage( + output_dir=self.output_dir, + output_postfix=output_postfix + "_label", + output_ext=self.label_output_ext, + separate_folder=False, + ) + label_saver(synthetic_labels[0]) + synthetic_labels_filename = os.path.join( + self.output_dir, "sample_" + output_postfix + "_label" + self.label_output_ext + ) + output_filenames.append([synthetic_images_filename, synthetic_labels_filename]) + to_generate = False + else: + logging.info( + "Generated image/label pair did not pass quality check, will re-generate another pair." + ) + return output_filenames + + def select_mask(self, candidate_mask_files, num_img): + """ + Select mask files for image generation. + + Args: + candidate_mask_files (list): List of candidate mask files. + num_img (int): Number of images to generate. + + Returns: + list: Selected mask files with augmentation flags. + """ + selected_mask_files = [] + random.shuffle(candidate_mask_files) + + for n in range(len(candidate_mask_files)): + mask_file = candidate_mask_files[n % len(candidate_mask_files)] + selected_mask_files.append({"mask_file": mask_file, "if_aug": True}) + return selected_mask_files + + def sample_one_pair( + self, + combine_label_or_aug, + top_region_index_tensor, + bottom_region_index_tensor, + spacing_tensor, + modality_tensor, + ): + """ + Generate a single pair of synthetic image and mask. + + Args: + combine_label_or_aug (torch.Tensor): Combined label tensor or augmented label. + top_region_index_tensor (torch.Tensor): Tensor specifying the top region index. + bottom_region_index_tensor (torch.Tensor): Tensor specifying the bottom region index. + spacing_tensor (torch.Tensor): Tensor specifying the spacing. + modality_tensor (torch.Tensor): Int Tensor specifying the modality. + + Returns: + tuple: A tuple containing the synthetic image and its corresponding label. + """ + # generate image/label pairs + synthetic_images, synthetic_labels = ldm_conditional_sample_one_image( + autoencoder=self.autoencoder, + diffusion_unet=self.diffusion_unet, + controlnet=self.controlnet, + noise_scheduler=self.noise_scheduler, + scale_factor=self.scale_factor, + device=self.device, + combine_label_or=combine_label_or_aug, + top_region_index_tensor=top_region_index_tensor, + bottom_region_index_tensor=bottom_region_index_tensor, + spacing_tensor=spacing_tensor, + modality_tensor=modality_tensor, + latent_shape=self.latent_shape, + output_size=self.output_size, + noise_factor=self.noise_factor, + num_inference_steps=self.num_inference_steps, + autoencoder_sliding_window_infer_size=self.autoencoder_sliding_window_infer_size, + autoencoder_sliding_window_infer_overlap=self.autoencoder_sliding_window_infer_overlap, + ) + return synthetic_images, synthetic_labels + + def prepare_anatomy_size_condtion( + self, + controllable_anatomy_size, + ): + """ + Prepare anatomy size conditions for mask generation. + + Args: + controllable_anatomy_size (list): List of tuples specifying controllable anatomy sizes. + + Returns: + list: Prepared anatomy size conditions. + """ + anatomy_size_idx = { + "gallbladder": 0, + "liver": 1, + "stomach": 2, + "pancreas": 3, + "colon": 4, + "lung tumor": 5, + "pancreatic tumor": 6, + "hepatic tumor": 7, + "colon cancer primaries": 8, + "bone lesion": 9, + } + provide_anatomy_size = [None for _ in range(10)] + logging.info(f"controllable_anatomy_size: {controllable_anatomy_size}") + for element in controllable_anatomy_size: + anatomy_name, anatomy_size = element + provide_anatomy_size[anatomy_size_idx[anatomy_name]] = anatomy_size + + with open(self.all_anatomy_size_condtions_json, "r") as f: + all_anatomy_size_condtions = json.load(f) + + # loop through the database and find closest combinations + candidate_list = [] + for anatomy_size in all_anatomy_size_condtions: + size = anatomy_size["organ_size"] + diff = 0 + for db_size, provide_size in zip(size, provide_anatomy_size): + if provide_size is None: + continue + diff += abs(provide_size - db_size) + candidate_list.append((size, diff)) + candidate_condition = sorted(candidate_list, key=lambda x: x[1])[0][0] + + # overwrite the anatomy size provided by users + for element in controllable_anatomy_size: + anatomy_name, anatomy_size = element + candidate_condition[anatomy_size_idx[anatomy_name]] = anatomy_size + + return candidate_condition + + def prepare_one_mask_and_meta_info(self, anatomy_size_condtion): + """ + Prepare a single mask and its associated meta information. + + Args: + anatomy_size_condtion (list): Anatomy size conditions. + + Returns: + tuple: A tuple containing the prepared mask and associated tensors. + """ + combine_label_or = self.sample_one_mask(anatomy_size=anatomy_size_condtion) + # TODO: current mask generation model only can generate 256^3 volumes with 1.5 mm spacing. + affine = torch.zeros((4, 4)) + affine[0, 0] = 1.5 + affine[1, 1] = 1.5 + affine[2, 2] = 1.5 + affine[3, 3] = 1.0 # dummy + combine_label_or = MetaTensor(combine_label_or, affine=affine) + combine_label_or = self.ensure_output_size_and_spacing(combine_label_or) + + top_region_index, bottom_region_index = get_body_region_index_from_mask(combine_label_or) + + spacing_tensor = torch.FloatTensor(self.spacing).unsqueeze(0).half().to(self.device) * 1e2 + top_region_index_tensor = ( + torch.FloatTensor(top_region_index).unsqueeze(0).half().to(self.device) * 1e2 + ) + bottom_region_index_tensor = ( + torch.FloatTensor(bottom_region_index).unsqueeze(0).half().to(self.device) * 1e2 + ) + + return combine_label_or, top_region_index_tensor, bottom_region_index_tensor, spacing_tensor + + def sample_one_mask(self, anatomy_size): + """ + Generate a single synthetic mask. + + Args: + anatomy_size (list): Anatomy size specifications. + + Returns: + torch.Tensor: The generated synthetic mask. + """ + # generate one synthetic mask + synthetic_mask = ldm_conditional_sample_one_mask( + self.mask_generation_autoencoder, + self.mask_generation_diffusion_unet, + self.mask_generation_noise_scheduler, + self.mask_generation_scale_factor, + anatomy_size, + self.device, + self.mask_generation_latent_shape, + label_dict_remap_json=self.label_dict_remap_json, + num_inference_steps=self.mask_generation_num_inference_steps, + autoencoder_sliding_window_infer_size=self.autoencoder_sliding_window_infer_size, + autoencoder_sliding_window_infer_overlap=self.autoencoder_sliding_window_infer_overlap, + ) + return synthetic_mask + + def ensure_output_size_and_spacing(self, labels, check_contains_target_labels=True): + """ + Ensure the output mask has the correct size and spacing. + + Args: + labels (torch.Tensor): Input label tensor. + check_contains_target_labels (bool): Whether to check if the resampled mask contains target labels. + + Returns: + torch.Tensor: Resampled label tensor. + + Raises: + ValueError: If the resampled mask doesn't contain required class labels. + """ + current_spacing = [labels.affine[0, 0], labels.affine[1, 1], labels.affine[2, 2]] + current_shape = list(labels.squeeze().shape) + + need_resample = False + # check spacing + for i, j in zip(current_spacing, self.spacing): + if i != j: + need_resample = True + # check output size + for i, j in zip(current_shape, self.output_size): + if i != j: + need_resample = True + # resample to target size and spacing + if need_resample: + logging.info("Resampling mask to target shape and spacing") + logging.info(f"Resize Spacing: {current_spacing} -> {self.spacing}") + logging.info(f"Output size: {current_shape} -> {self.output_size}") + spacing = monai.transforms.Spacing(pixdim=tuple(self.spacing), mode="nearest") + pad_crop = monai.transforms.ResizeWithPadOrCrop(spatial_size=tuple(self.output_size)) + labels = pad_crop(spacing(labels.squeeze(0))).unsqueeze(0).to(labels.dtype) + + contained_labels = torch.unique(labels) + if check_contains_target_labels: + # check if the resampled mask still contains those target labels + for anatomy_label in self.anatomy_list: + if anatomy_label not in contained_labels: + raise ValueError( + f"Resampled mask does not contain required class labels {anatomy_label}. Please tune spacing and output size." + ) + return labels + + def read_mask_information(self, mask_file): + """ + Read mask information from a file. + + Args: + mask_file (str): Path to the mask file. + + Returns: + tuple: A tuple containing the mask tensor and associated information. + """ + val_data = self.val_transforms(mask_file) + + for key in ["pseudo_label", "spacing", "top_region_index", "bottom_region_index"]: + if isinstance(val_data[key], torch.Tensor): + val_data[key] = val_data[key].unsqueeze(0).to(self.device) + else: + val_data[key] = None + + return ( + val_data["pseudo_label"], + val_data["top_region_index"], + val_data["bottom_region_index"], + val_data["spacing"], + ) + + def find_closest_masks(self, num_img): + """ + Find the closest matching masks from the database. + + Args: + num_img (int): Number of images to generate. + + Returns: + list: List of closest matching mask candidates. + + Raises: + ValueError: If suitable candidates cannot be found. + """ + # first check the database based on anatomy list + candidates = find_masks( + self.body_region, + self.anatomy_list, + self.spacing, + self.output_size, + False, + self.all_mask_files_json, + self.data_root, + ) + + if len(candidates) < num_img: + raise ValueError(f"candidate masks are less than {num_img}).") + + # loop through the database and find closest combinations + new_candidates = [] + for c in candidates: + diff = 0 + include_c = True + for axis in range(3): + if abs(c["dim"][axis]) < self.output_size[axis] - 64: + # we cannot upsample the mask too much + include_c = False + break + # check diff in FOV, major metric + diff += abs( + ( + abs(c["dim"][axis] * c["spacing"][axis]) + - self.output_size[axis] * self.spacing[axis] + ) + / 10 + ) + # check diff in dim + diff += abs((abs(c["dim"][axis]) - self.output_size[axis]) / 100) + # check diff in spacing + diff += abs(abs(c["spacing"][axis]) - self.spacing[axis]) + if include_c: + new_candidates.append((c, diff)) + + # choose top-2*num_img candidates (at least 5) + num_candidates = max(self.max_try_time * num_img, 5) + new_candidates = sorted(new_candidates, key=lambda x: x[1]) + + final_candidates = [] + # check top-2*num_img candidates and update spacing after resampling + for c, _ in new_candidates: + c = self.resample_mask_check_organ_list(c) + if c is not None: + final_candidates.append(c) + if len(final_candidates) >= num_candidates: + break + if len(final_candidates) == 0: + raise ValueError("Cannot find body region with given organ list.") + return final_candidates + + def resample_mask_check_organ_list(self, mask): + """ + Resample mask and check if the resampled mask contains the required organ list. + + Args: + mask (dict): input mask. + + Returns: + dict: resampled mask. If None, means the resampled mask does not contain the required organ list + + Raises: + ValueError: If suitable candidates cannot be found. + """ + + image_loader = monai.transforms.LoadImage(image_only=True, ensure_channel_first=True) + label = image_loader(mask["pseudo_label"]) + try: + label = self.ensure_output_size_and_spacing(label.unsqueeze(0)) + except ValueError as e: + if "Resampled mask does not contain required class labels" in str(e): + return None + else: + raise e + # get region_index after resample + top_region_index, bottom_region_index = get_body_region_index_from_mask(label) + mask["top_region_index"] = top_region_index + mask["bottom_region_index"] = bottom_region_index + mask["spacing"] = self.spacing + mask["dim"] = self.output_size + return mask + + def quality_check(self, image_data, label_data): + """ + Perform a quality check on the generated image. + Args: + image_data (np.ndarray): The generated image. + label_data (np.ndarray): The corresponding whole body mask. + Returns: + bool: True if the image passes the quality check, False otherwise. + """ + outlier_results = is_outlier( + self.median_statistics, image_data, label_data, self.label_int_dict + ) + for label, result in outlier_results.items(): + if result.get("is_outlier", False): + logging.info( + f"Generated image quality check for label '{label}' failed: median value {result['median_value']} is outside the acceptable range ({result['low_thresh']} - {result['high_thresh']})." + ) + return False + return True diff --git a/itrialspace/src/itrialspace/synthesis/scripts/scheduler.py b/itrialspace/src/itrialspace/synthesis/scripts/scheduler.py new file mode 100644 index 0000000000000000000000000000000000000000..66dd2dc6703018449d626f4ded55b6944dd36179 --- /dev/null +++ b/itrialspace/src/itrialspace/synthesis/scripts/scheduler.py @@ -0,0 +1,223 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# ========================================================================= +# Adapted from https://github.com/huggingface/diffusers +# which has the following license: +# https://github.com/huggingface/diffusers/blob/main/LICENSE +# +# Copyright 2022 UC Berkeley Team and The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ========================================================================= + + +from __future__ import annotations + +import torch +import torch.nn as nn +from monai.utils import ComponentStore, unsqueeze_right + +NoiseSchedules = ComponentStore("NoiseSchedules", "Functions to generate noise schedules") + + +@NoiseSchedules.add_def("linear_beta", "Linear beta schedule") +def _linear_beta(num_train_timesteps: int, beta_start: float = 1e-4, beta_end: float = 2e-2): + """ + Linear beta noise schedule function. + + Args: + num_train_timesteps: number of timesteps + beta_start: start of beta range, default 1e-4 + beta_end: end of beta range, default 2e-2 + + Returns: + betas: beta schedule tensor + """ + return torch.linspace(beta_start, beta_end, num_train_timesteps, dtype=torch.float32) + + +@NoiseSchedules.add_def("scaled_linear_beta", "Scaled linear beta schedule") +def _scaled_linear_beta(num_train_timesteps: int, beta_start: float = 1e-4, beta_end: float = 2e-2): + """ + Scaled linear beta noise schedule function. + + Args: + num_train_timesteps: number of timesteps + beta_start: start of beta range, default 1e-4 + beta_end: end of beta range, default 2e-2 + + Returns: + betas: beta schedule tensor + """ + return ( + torch.linspace(beta_start**0.5, beta_end**0.5, num_train_timesteps, dtype=torch.float32) + ** 2 + ) + + +@NoiseSchedules.add_def("sigmoid_beta", "Sigmoid beta schedule") +def _sigmoid_beta( + num_train_timesteps: int, beta_start: float = 1e-4, beta_end: float = 2e-2, sig_range: float = 6 +): + """ + Sigmoid beta noise schedule function. + + Args: + num_train_timesteps: number of timesteps + beta_start: start of beta range, default 1e-4 + beta_end: end of beta range, default 2e-2 + sig_range: pos/neg range of sigmoid input, default 6 + + Returns: + betas: beta schedule tensor + """ + betas = torch.linspace(-sig_range, sig_range, num_train_timesteps) + return torch.sigmoid(betas) * (beta_end - beta_start) + beta_start + + +@NoiseSchedules.add_def("cosine", "Cosine schedule") +def _cosine_beta(num_train_timesteps: int, s: float = 8e-3): + """ + Cosine noise schedule, see https://arxiv.org/abs/2102.09672 + + Args: + num_train_timesteps: number of timesteps + s: smoothing factor, default 8e-3 (see referenced paper) + + Returns: + (betas, alphas, alpha_cumprod) values + """ + x = torch.linspace(0, num_train_timesteps, num_train_timesteps + 1) + alphas_cumprod = torch.cos(((x / num_train_timesteps) + s) / (1 + s) * torch.pi * 0.5) ** 2 + alphas_cumprod /= alphas_cumprod[0].item() + betas = 1.0 - (alphas_cumprod[1:] / alphas_cumprod[:-1]) + betas = torch.clip(betas, 0.0, 0.999) + alphas = 1.0 - betas + alphas_cumprod = torch.cumprod(alphas, dim=0) + return betas, alphas, alphas_cumprod + + +class Scheduler(nn.Module): + """ + Base class for other schedulers based on a noise schedule function. + + This class is meant as the base for other schedulers which implement their own way of sampling or stepping. Here + the class defines beta, alpha, and alpha_cumprod values from a noise schedule function named with `schedule`, + which is the name of a component in NoiseSchedules. These components must all be callables which return either + the beta schedule alone or a triple containing (betas, alphas, alphas_cumprod) values. New schedule functions + can be provided by using the NoiseSchedules.add_def, for example: + + .. code-block:: python + + from monai.networks.schedulers import NoiseSchedules, DDPMScheduler + + @NoiseSchedules.add_def("my_beta_schedule", "Some description of your function") + def _beta_function(num_train_timesteps, beta_start=1e-4, beta_end=2e-2): + return torch.linspace(beta_start, beta_end, num_train_timesteps, dtype=torch.float32) + + scheduler = DDPMScheduler(num_train_timesteps=1000, schedule="my_beta_schedule") + + All such functions should have an initial positional integer argument `num_train_timesteps` stating the number of + timesteps the schedule is for, otherwise any other arguments can be given which will be passed by keyword through + the constructor's `schedule_args` value. To see what noise functions are available, print the object NoiseSchedules + to get a listing of stored objects with their docstring descriptions. + + Note: in previous versions of the schedulers the argument `schedule_beta` was used to state the beta schedule + type, this now replaced with `schedule` and most names used with the previous argument now have "_beta" appended + to them, eg. 'schedule_beta="linear"' -> 'schedule="linear_beta"'. The `beta_start` and `beta_end` arguments are + still used for some schedules but these are provided as keyword arguments now. + + Args: + num_train_timesteps: number of diffusion steps used to train the model. + schedule: member of NoiseSchedules, + a named function returning the beta tensor or (betas, alphas, alphas_cumprod) triple + schedule_args: arguments to pass to the schedule function + """ + + def __init__( + self, num_train_timesteps: int = 1000, schedule: str = "linear_beta", **schedule_args + ) -> None: + super().__init__() + schedule_args["num_train_timesteps"] = num_train_timesteps + noise_sched = NoiseSchedules[schedule](**schedule_args) + + # set betas, alphas, alphas_cumprod based off return value from noise function + if isinstance(noise_sched, tuple): + self.betas, self.alphas, self.alphas_cumprod = noise_sched + else: + self.betas = noise_sched + self.alphas = 1.0 - self.betas + self.alphas_cumprod = torch.cumprod(self.alphas, dim=0) + + self.num_train_timesteps = num_train_timesteps + self.one = torch.tensor(1.0) + + # settable values + self.num_inference_steps: int | None = None + self.timesteps = torch.arange(num_train_timesteps - 1, -1, -1) + + def add_noise( + self, original_samples: torch.Tensor, noise: torch.Tensor, timesteps: torch.Tensor + ) -> torch.Tensor: + """ + Add noise to the original samples. + + Args: + original_samples: original samples + noise: noise to add to samples + timesteps: timesteps tensor indicating the timestep to be computed for each sample. + + Returns: + noisy_samples: sample with added noise + """ + # Make sure alphas_cumprod and timestep have same device and dtype as original_samples + self.alphas_cumprod = self.alphas_cumprod.to( + device=original_samples.device, dtype=original_samples.dtype + ) + timesteps = timesteps.to(original_samples.device) + + sqrt_alpha_cumprod: torch.Tensor = unsqueeze_right( + self.alphas_cumprod[timesteps] ** 0.5, original_samples.ndim + ) + sqrt_one_minus_alpha_prod: torch.Tensor = unsqueeze_right( + (1 - self.alphas_cumprod[timesteps]) ** 0.5, original_samples.ndim + ) + + noisy_samples = sqrt_alpha_cumprod * original_samples + sqrt_one_minus_alpha_prod * noise + return noisy_samples + + def get_velocity( + self, sample: torch.Tensor, noise: torch.Tensor, timesteps: torch.Tensor + ) -> torch.Tensor: + # Make sure alphas_cumprod and timestep have same device and dtype as sample + self.alphas_cumprod = self.alphas_cumprod.to(device=sample.device, dtype=sample.dtype) + timesteps = timesteps.to(sample.device) + + sqrt_alpha_prod: torch.Tensor = unsqueeze_right( + self.alphas_cumprod[timesteps] ** 0.5, sample.ndim + ) + sqrt_one_minus_alpha_prod: torch.Tensor = unsqueeze_right( + (1 - self.alphas_cumprod[timesteps]) ** 0.5, sample.ndim + ) + + velocity = sqrt_alpha_prod * noise - sqrt_one_minus_alpha_prod * sample + return velocity diff --git a/itrialspace/src/itrialspace/synthesis/scripts/schedulers/__init__.py b/itrialspace/src/itrialspace/synthesis/scripts/schedulers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/itrialspace/src/itrialspace/synthesis/scripts/schedulers/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/scripts/schedulers/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..decce11c372a1eaabfd04fb01a3961a8349688a8 Binary files /dev/null and b/itrialspace/src/itrialspace/synthesis/scripts/schedulers/__pycache__/__init__.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/synthesis/scripts/schedulers/__pycache__/ddim.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/scripts/schedulers/__pycache__/ddim.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..38e286b25a1009c4949d7eff73ebcd9b6348385e Binary files /dev/null and b/itrialspace/src/itrialspace/synthesis/scripts/schedulers/__pycache__/ddim.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/synthesis/scripts/schedulers/__pycache__/ddpm.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/scripts/schedulers/__pycache__/ddpm.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..351c0b6243e04465eeb1594df89e3767e7e0ddf0 Binary files /dev/null and b/itrialspace/src/itrialspace/synthesis/scripts/schedulers/__pycache__/ddpm.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/synthesis/scripts/schedulers/__pycache__/pndm.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/scripts/schedulers/__pycache__/pndm.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0a899993bb1c796e0ab99407ea44cd9928deb078 Binary files /dev/null and b/itrialspace/src/itrialspace/synthesis/scripts/schedulers/__pycache__/pndm.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/synthesis/scripts/schedulers/__pycache__/rectified_flow.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/scripts/schedulers/__pycache__/rectified_flow.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e5bd3ba39d6b807b03c89e59af52dd2cbcfe23af Binary files /dev/null and b/itrialspace/src/itrialspace/synthesis/scripts/schedulers/__pycache__/rectified_flow.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/synthesis/scripts/schedulers/__pycache__/scheduler.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/scripts/schedulers/__pycache__/scheduler.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8d9ee70f75fdb355eac781b4964e7b075fc82f08 Binary files /dev/null and b/itrialspace/src/itrialspace/synthesis/scripts/schedulers/__pycache__/scheduler.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/synthesis/scripts/schedulers/ddim.py b/itrialspace/src/itrialspace/synthesis/scripts/schedulers/ddim.py new file mode 100644 index 0000000000000000000000000000000000000000..28297fee334dfe9efbdfa936825de76b8e4ac7cf --- /dev/null +++ b/itrialspace/src/itrialspace/synthesis/scripts/schedulers/ddim.py @@ -0,0 +1,320 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# ========================================================================= +# Adapted from https://github.com/huggingface/diffusers +# which has the following license: +# https://github.com/huggingface/diffusers/blob/main/LICENSE +# +# Copyright 2022 UC Berkeley Team and The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ========================================================================= + +from __future__ import annotations + +import numpy as np +import torch + +from .ddpm import DDPMPredictionType +from .scheduler import Scheduler + +DDIMPredictionType = DDPMPredictionType + + +class DDIMScheduler(Scheduler): + """ + Denoising diffusion implicit models is a scheduler that extends the denoising procedure introduced in denoising + diffusion probabilistic models (DDPMs) with non-Markovian guidance. Based on: Song et al. "Denoising Diffusion + Implicit Models" https://arxiv.org/abs/2010.02502 + + Args: + num_train_timesteps: number of diffusion steps used to train the model. + schedule: member of NoiseSchedules, name of noise schedule function in component store + clip_sample: option to clip predicted sample between -1 and 1 for numerical stability. + set_alpha_to_one: each diffusion step uses the value of alphas product at that step and at the previous one. + For the final step there is no previous alpha. When this option is `True` the previous alpha product is + fixed to `1`, otherwise it uses the value of alpha at step 0. + steps_offset: an offset added to the inference steps. You can use a combination of `steps_offset=1` and + `set_alpha_to_one=False`, to make the last step use step 0 for the previous alpha product, as done in + stable diffusion. + prediction_type: member of DDPMPredictionType + clip_sample_min: minimum clipping value when clip_sample equals True + clip_sample_max: maximum clipping value when clip_sample equals True + schedule_args: arguments to pass to the schedule function + + """ + + def __init__( + self, + num_train_timesteps: int = 1000, + schedule: str = "linear_beta", + clip_sample: bool = True, + set_alpha_to_one: bool = True, + steps_offset: int = 0, + prediction_type: str = DDIMPredictionType.EPSILON, + clip_sample_min: float = -1.0, + clip_sample_max: float = 1.0, + **schedule_args, + ) -> None: + super().__init__(num_train_timesteps, schedule, **schedule_args) + + if prediction_type not in DDIMPredictionType.__members__.values(): + raise ValueError("Argument `prediction_type` must be a member of DDIMPredictionType") + + self.prediction_type = prediction_type + + # At every step in ddim, we are looking into the previous alphas_cumprod + # For the final step, there is no previous alphas_cumprod because we are already at 0 + # `set_alpha_to_one` decides whether we set this parameter simply to one or + # whether we use the final alpha of the "non-previous" one. + self.final_alpha_cumprod = torch.tensor(1.0) if set_alpha_to_one else self.alphas_cumprod[0] + + # standard deviation of the initial noise distribution + self.init_noise_sigma = 1.0 + + self.timesteps = torch.from_numpy( + np.arange(0, self.num_train_timesteps)[::-1].astype(np.int64) + ) + + self.clip_sample = clip_sample + self.clip_sample_values = [clip_sample_min, clip_sample_max] + self.steps_offset = steps_offset + + # default the number of inference timesteps to the number of train steps + self.num_inference_steps: int + self.set_timesteps(self.num_train_timesteps) + + def set_timesteps( + self, num_inference_steps: int, device: str | torch.device | None = None + ) -> None: + """ + Sets the discrete timesteps used for the diffusion chain. Supporting function to be run before inference. + + Args: + num_inference_steps: number of diffusion steps used when generating samples with a pre-trained model. + device: target device to put the data. + """ + if num_inference_steps > self.num_train_timesteps: + raise ValueError( + f"`num_inference_steps`: {num_inference_steps} cannot be larger than `self.num_train_timesteps`:" + f" {self.num_train_timesteps} as the unet model trained with this scheduler can only handle" + f" maximal {self.num_train_timesteps} timesteps." + ) + + self.num_inference_steps = num_inference_steps + step_ratio = self.num_train_timesteps // self.num_inference_steps + if self.steps_offset >= step_ratio: + raise ValueError( + f"`steps_offset`: {self.steps_offset} cannot be greater than or equal to " + f"`num_train_timesteps // num_inference_steps : {step_ratio}` as this will cause timesteps to exceed" + f" the max train timestep." + ) + + # creates integer timesteps by multiplying by ratio + # casting to int to avoid issues when num_inference_step is power of 3 + timesteps = ( + (np.arange(0, num_inference_steps) * step_ratio).round()[::-1].copy().astype(np.int64) + ) + self.timesteps = torch.from_numpy(timesteps).to(device) + self.timesteps += self.steps_offset + + def _get_variance(self, timestep: int, prev_timestep: int) -> torch.Tensor: + alpha_prod_t = self.alphas_cumprod[timestep] + alpha_prod_t_prev = ( + self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod + ) + beta_prod_t = 1 - alpha_prod_t + beta_prod_t_prev = 1 - alpha_prod_t_prev + + variance: torch.Tensor = (beta_prod_t_prev / beta_prod_t) * ( + 1 - alpha_prod_t / alpha_prod_t_prev + ) + + return variance + + def step( + self, + model_output: torch.Tensor, + timestep: int, + sample: torch.Tensor, + eta: float = 0.0, + generator: torch.Generator | None = None, + ) -> tuple[torch.Tensor, torch.Tensor]: + """ + Predict the sample at the previous timestep by reversing the SDE. Core function to propagate the diffusion + process from the learned model outputs (most often the predicted noise). + + Args: + model_output: direct output from learned diffusion model. + timestep: current discrete timestep in the diffusion chain. + sample: current instance of sample being created by diffusion process. + eta: weight of noise for added noise in diffusion step. + generator: random number generator. + + Returns: + pred_prev_sample: Predicted previous sample + pred_original_sample: Predicted original sample + """ + # See formulas (12) and (16) of DDIM paper https://arxiv.org/pdf/2010.02502.pdf + # Ideally, read DDIM paper in-detail understanding + + # Notation ( -> + # - model_output -> e_theta(x_t, t) + # - pred_original_sample -> f_theta(x_t, t) or x_0 + # - std_dev_t -> sigma_t + # - eta -> η + # - pred_sample_direction -> "direction pointing to x_t" + # - pred_prev_sample -> "x_t-1" + + # 1. get previous step value (=t-1) + prev_timestep = timestep - self.num_train_timesteps // self.num_inference_steps + + # 2. compute alphas, betas + alpha_prod_t = self.alphas_cumprod[timestep] + alpha_prod_t_prev = ( + self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod + ) + + beta_prod_t = 1 - alpha_prod_t + + # predefinitions satisfy pylint/mypy, these values won't be ultimately used + pred_original_sample = sample + pred_epsilon = model_output + + # 3. compute predicted original sample from predicted noise also called + # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf + if self.prediction_type == DDIMPredictionType.EPSILON: + pred_original_sample = (sample - (beta_prod_t**0.5) * model_output) / ( + alpha_prod_t**0.5 + ) + pred_epsilon = model_output + elif self.prediction_type == DDIMPredictionType.SAMPLE: + pred_original_sample = model_output + pred_epsilon = (sample - (alpha_prod_t**0.5) * pred_original_sample) / ( + beta_prod_t**0.5 + ) + elif self.prediction_type == DDIMPredictionType.V_PREDICTION: + pred_original_sample = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output + pred_epsilon = (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample + + # 4. Clip "predicted x_0" + if self.clip_sample: + pred_original_sample = torch.clamp( + pred_original_sample, self.clip_sample_values[0], self.clip_sample_values[1] + ) + + # 5. compute variance: "sigma_t(η)" -> see formula (16) + # σ_t = sqrt((1 − α_t−1)/(1 − α_t)) * sqrt(1 − α_t/α_t−1) + variance = self._get_variance(timestep, prev_timestep) + std_dev_t = eta * variance**0.5 + + # 6. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf + pred_sample_direction = (1 - alpha_prod_t_prev - std_dev_t**2) ** 0.5 * pred_epsilon + + # 7. compute x_t-1 without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf + pred_prev_sample = alpha_prod_t_prev**0.5 * pred_original_sample + pred_sample_direction + + if eta > 0: + # randn_like does not support generator https://github.com/pytorch/pytorch/issues/27072 + device: torch.device = torch.device( + model_output.device if torch.is_tensor(model_output) else "cpu" + ) + noise = torch.randn( + model_output.shape, dtype=model_output.dtype, generator=generator, device=device + ) + variance = self._get_variance(timestep, prev_timestep) ** 0.5 * eta * noise + + pred_prev_sample = pred_prev_sample + variance + + return pred_prev_sample, pred_original_sample + + def reversed_step( + self, model_output: torch.Tensor, timestep: int, sample: torch.Tensor + ) -> tuple[torch.Tensor, torch.Tensor]: + """ + Predict the sample at the next timestep by reversing the SDE. Core function to propagate the diffusion + process from the learned model outputs (most often the predicted noise). + + Args: + model_output: direct output from learned diffusion model. + timestep: current discrete timestep in the diffusion chain. + sample: current instance of sample being created by diffusion process. + + Returns: + pred_prev_sample: Predicted previous sample + pred_original_sample: Predicted original sample + """ + # See Appendix F at https://arxiv.org/pdf/2105.05233.pdf, or Equation (6) in https://arxiv.org/pdf/2203.04306.pdf + + # Notation ( -> + # - model_output -> e_theta(x_t, t) + # - pred_original_sample -> f_theta(x_t, t) or x_0 + # - std_dev_t -> sigma_t + # - eta -> η + # - pred_sample_direction -> "direction pointing to x_t" + # - pred_post_sample -> "x_t+1" + + # 1. get previous step value (=t+1) + prev_timestep = timestep + self.num_train_timesteps // self.num_inference_steps + + # 2. compute alphas, betas at timestep t+1 + alpha_prod_t = self.alphas_cumprod[timestep] + alpha_prod_t_prev = ( + self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod + ) + + beta_prod_t = 1 - alpha_prod_t + + # predefinitions satisfy pylint/mypy, these values won't be ultimately used + pred_original_sample = sample + pred_epsilon = model_output + + # 3. compute predicted original sample from predicted noise also called + # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf + + if self.prediction_type == DDIMPredictionType.EPSILON: + pred_original_sample = ( + sample - beta_prod_t ** (0.5) * model_output + ) / alpha_prod_t ** (0.5) + pred_epsilon = model_output + elif self.prediction_type == DDIMPredictionType.SAMPLE: + pred_original_sample = model_output + pred_epsilon = ( + sample - alpha_prod_t ** (0.5) * pred_original_sample + ) / beta_prod_t ** (0.5) + elif self.prediction_type == DDIMPredictionType.V_PREDICTION: + pred_original_sample = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output + pred_epsilon = (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample + + # 4. Clip "predicted x_0" + if self.clip_sample: + pred_original_sample = torch.clamp( + pred_original_sample, self.clip_sample_values[0], self.clip_sample_values[1] + ) + + # 5. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf + pred_sample_direction = (1 - alpha_prod_t_prev) ** (0.5) * pred_epsilon + + # 6. compute x_t+1 without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf + pred_post_sample = alpha_prod_t_prev ** (0.5) * pred_original_sample + pred_sample_direction + + return pred_post_sample, pred_original_sample diff --git a/itrialspace/src/itrialspace/synthesis/scripts/schedulers/ddpm.py b/itrialspace/src/itrialspace/synthesis/scripts/schedulers/ddpm.py new file mode 100644 index 0000000000000000000000000000000000000000..6b797cc931133a6b2c77c745e8dd2d484c898405 --- /dev/null +++ b/itrialspace/src/itrialspace/synthesis/scripts/schedulers/ddpm.py @@ -0,0 +1,274 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# ========================================================================= +# Adapted from https://github.com/huggingface/diffusers +# which has the following license: +# https://github.com/huggingface/diffusers/blob/main/LICENSE +# +# Copyright 2022 UC Berkeley Team and The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ========================================================================= + +from __future__ import annotations + +import numpy as np +import torch +from monai.utils import StrEnum + +from .scheduler import Scheduler + + +class DDPMVarianceType(StrEnum): + """ + Valid names for DDPM Scheduler's `variance_type` argument. Options to clip the variance used when adding noise + to the denoised sample. + """ + + FIXED_SMALL = "fixed_small" + FIXED_LARGE = "fixed_large" + LEARNED = "learned" + LEARNED_RANGE = "learned_range" + + +class DDPMPredictionType(StrEnum): + """ + Set of valid prediction type names for the DDPM scheduler's `prediction_type` argument. + + epsilon: predicting the noise of the diffusion process + sample: directly predicting the noisy sample + v_prediction: velocity prediction, see section 2.4 https://imagen.research.google/video/paper.pdf + """ + + EPSILON = "epsilon" + SAMPLE = "sample" + V_PREDICTION = "v_prediction" + + +class DDPMScheduler(Scheduler): + """ + Denoising diffusion probabilistic models (DDPMs) explores the connections between denoising score matching and + Langevin dynamics sampling. Based on: Ho et al., "Denoising Diffusion Probabilistic Models" + https://arxiv.org/abs/2006.11239 + + Args: + num_train_timesteps: number of diffusion steps used to train the model. + schedule: member of NoiseSchedules, name of noise schedule function in component store + variance_type: member of DDPMVarianceType + clip_sample: option to clip predicted sample between -1 and 1 for numerical stability. + prediction_type: member of DDPMPredictionType + clip_sample_min: minimum clipping value when clip_sample equals True + clip_sample_max: maximum clipping value when clip_sample equals True + schedule_args: arguments to pass to the schedule function + """ + + def __init__( + self, + num_train_timesteps: int = 1000, + schedule: str = "linear_beta", + variance_type: str = DDPMVarianceType.FIXED_SMALL, + clip_sample: bool = True, + prediction_type: str = DDPMPredictionType.EPSILON, + clip_sample_min: float = -1.0, + clip_sample_max: float = 1.0, + **schedule_args, + ) -> None: + super().__init__(num_train_timesteps, schedule, **schedule_args) + + if variance_type not in DDPMVarianceType.__members__.values(): + raise ValueError("Argument `variance_type` must be a member of `DDPMVarianceType`") + + if prediction_type not in DDPMPredictionType.__members__.values(): + raise ValueError("Argument `prediction_type` must be a member of `DDPMPredictionType`") + + self.clip_sample = clip_sample + self.clip_sample_values = [clip_sample_min, clip_sample_max] + self.variance_type = variance_type + self.prediction_type = prediction_type + + def set_timesteps( + self, num_inference_steps: int, device: str | torch.device | None = None + ) -> None: + """ + Sets the discrete timesteps used for the diffusion chain. Supporting function to be run before inference. + + Args: + num_inference_steps: number of diffusion steps used when generating samples with a pre-trained model. + device: target device to put the data. + """ + if num_inference_steps > self.num_train_timesteps: + raise ValueError( + f"`num_inference_steps`: {num_inference_steps} cannot be larger than `self.num_train_timesteps`:" + f" {self.num_train_timesteps} as the unet model trained with this scheduler can only handle" + f" maximal {self.num_train_timesteps} timesteps." + ) + + self.num_inference_steps = num_inference_steps + step_ratio = self.num_train_timesteps // self.num_inference_steps + # creates integer timesteps by multiplying by ratio + # casting to int to avoid issues when num_inference_step is power of 3 + timesteps = (np.arange(0, num_inference_steps) * step_ratio).round()[::-1].astype(np.int64) + self.timesteps = torch.from_numpy(timesteps).to(device) + + def _get_mean(self, timestep: int, x_0: torch.Tensor, x_t: torch.Tensor) -> torch.Tensor: + """ + Compute the mean of the posterior at timestep t. + + Args: + timestep: current timestep. + x0: the noise-free input. + x_t: the input noised to timestep t. + + Returns: + Returns the mean + """ + # these attributes are used for calculating the posterior, q(x_{t-1}|x_t,x_0), + # (see formula (5-7) from https://arxiv.org/pdf/2006.11239.pdf) + alpha_t = self.alphas[timestep] + alpha_prod_t = self.alphas_cumprod[timestep] + alpha_prod_t_prev = self.alphas_cumprod[timestep - 1] if timestep > 0 else self.one + + x_0_coefficient = alpha_prod_t_prev.sqrt() * self.betas[timestep] / (1 - alpha_prod_t) + x_t_coefficient = alpha_t.sqrt() * (1 - alpha_prod_t_prev) / (1 - alpha_prod_t) + + mean: torch.Tensor = x_0_coefficient * x_0 + x_t_coefficient * x_t + + return mean + + def _get_variance( + self, timestep: int, predicted_variance: torch.Tensor | None = None + ) -> torch.Tensor: + """ + Compute the variance of the posterior at timestep t. + + Args: + timestep: current timestep. + predicted_variance: variance predicted by the model. + + Returns: + Returns the variance + """ + alpha_prod_t = self.alphas_cumprod[timestep] + alpha_prod_t_prev = self.alphas_cumprod[timestep - 1] if timestep > 0 else self.one + + # For t > 0, compute predicted variance βt (see formula (6) and (7) from https://arxiv.org/pdf/2006.11239.pdf) + # and sample from it to get previous sample + # x_{t-1} ~ N(pred_prev_sample, variance) == add variance to pred_sample + variance: torch.Tensor = (1 - alpha_prod_t_prev) / (1 - alpha_prod_t) * self.betas[timestep] + # hacks - were probably added for training stability + if self.variance_type == DDPMVarianceType.FIXED_SMALL: + variance = torch.clamp(variance, min=1e-20) + elif self.variance_type == DDPMVarianceType.FIXED_LARGE: + variance = self.betas[timestep] + elif self.variance_type == DDPMVarianceType.LEARNED and predicted_variance is not None: + return predicted_variance + elif ( + self.variance_type == DDPMVarianceType.LEARNED_RANGE and predicted_variance is not None + ): + min_log = variance + max_log = self.betas[timestep] + frac = (predicted_variance + 1) / 2 + variance = frac * max_log + (1 - frac) * min_log + + return variance + + def step( + self, + model_output: torch.Tensor, + timestep: int, + sample: torch.Tensor, + generator: torch.Generator | None = None, + ) -> tuple[torch.Tensor, torch.Tensor]: + """ + Predict the sample at the previous timestep by reversing the SDE. Core function to propagate the diffusion + process from the learned model outputs (most often the predicted noise). + + Args: + model_output: direct output from learned diffusion model. + timestep: current discrete timestep in the diffusion chain. + sample: current instance of sample being created by diffusion process. + generator: random number generator. + + Returns: + pred_prev_sample: Predicted previous sample + """ + if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type in [ + "learned", + "learned_range", + ]: + model_output, predicted_variance = torch.split(model_output, sample.shape[1], dim=1) + else: + predicted_variance = None + + # 1. compute alphas, betas + alpha_prod_t = self.alphas_cumprod[timestep] + alpha_prod_t_prev = self.alphas_cumprod[timestep - 1] if timestep > 0 else self.one + beta_prod_t = 1 - alpha_prod_t + beta_prod_t_prev = 1 - alpha_prod_t_prev + + # 2. compute predicted original sample from predicted noise also called + # "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf + if self.prediction_type == DDPMPredictionType.EPSILON: + pred_original_sample = ( + sample - beta_prod_t ** (0.5) * model_output + ) / alpha_prod_t ** (0.5) + elif self.prediction_type == DDPMPredictionType.SAMPLE: + pred_original_sample = model_output + elif self.prediction_type == DDPMPredictionType.V_PREDICTION: + pred_original_sample = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output + + # 3. Clip "predicted x_0" + if self.clip_sample: + pred_original_sample = torch.clamp( + pred_original_sample, self.clip_sample_values[0], self.clip_sample_values[1] + ) + + # 4. Compute coefficients for pred_original_sample x_0 and current sample x_t + # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf + pred_original_sample_coeff = ( + alpha_prod_t_prev ** (0.5) * self.betas[timestep] + ) / beta_prod_t + current_sample_coeff = self.alphas[timestep] ** (0.5) * beta_prod_t_prev / beta_prod_t + + # 5. Compute predicted previous sample µ_t + # See formula (7) from https://arxiv.org/pdf/2006.11239.pdf + pred_prev_sample = ( + pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample + ) + + # 6. Add noise + variance: torch.Tensor = torch.tensor(0) + if timestep > 0: + noise = torch.randn( + model_output.size(), + dtype=model_output.dtype, + layout=model_output.layout, + generator=generator, + device=model_output.device, + ) + variance = ( + self._get_variance(timestep, predicted_variance=predicted_variance) ** 0.5 + ) * noise + + pred_prev_sample = pred_prev_sample + variance + + return pred_prev_sample, pred_original_sample diff --git a/itrialspace/src/itrialspace/synthesis/scripts/schedulers/pndm.py b/itrialspace/src/itrialspace/synthesis/scripts/schedulers/pndm.py new file mode 100644 index 0000000000000000000000000000000000000000..6901aac7f189d3e58151fae6694e5ac583bfae96 --- /dev/null +++ b/itrialspace/src/itrialspace/synthesis/scripts/schedulers/pndm.py @@ -0,0 +1,332 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# ========================================================================= +# Adapted from https://github.com/huggingface/diffusers +# which has the following license: +# https://github.com/huggingface/diffusers/blob/main/LICENSE +# +# Copyright 2022 UC Berkeley Team and The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ========================================================================= + +from __future__ import annotations + +from typing import Any + +import numpy as np +import torch +from monai.utils import StrEnum + +from .scheduler import Scheduler + + +class PNDMPredictionType(StrEnum): + """ + Set of valid prediction type names for the PNDM scheduler's `prediction_type` argument. + + epsilon: predicting the noise of the diffusion process + v_prediction: velocity prediction, see section 2.4 https://imagen.research.google/video/paper.pdf + """ + + EPSILON = "epsilon" + V_PREDICTION = "v_prediction" + + +class PNDMScheduler(Scheduler): + """ + Pseudo numerical methods for diffusion models (PNDM) proposes using more advanced ODE integration techniques, + namely Runge-Kutta method and a linear multi-step method. Based on: Liu et al., + "Pseudo Numerical Methods for Diffusion Models on Manifolds" https://arxiv.org/abs/2202.09778 + + Args: + num_train_timesteps: number of diffusion steps used to train the model. + schedule: member of NoiseSchedules, name of noise schedule function in component store + skip_prk_steps: + allows the scheduler to skip the Runge-Kutta steps that are defined in the original paper as being required + before plms step. + set_alpha_to_one: + each diffusion step uses the value of alphas product at that step and at the previous one. For the final + step there is no previous alpha. When this option is `True` the previous alpha product is fixed to `1`, + otherwise it uses the value of alpha at step 0. + prediction_type: member of DDPMPredictionType + steps_offset: + an offset added to the inference steps. You can use a combination of `offset=1` and + `set_alpha_to_one=False`, to make the last step use step 0 for the previous alpha product, as done in + stable diffusion. + schedule_args: arguments to pass to the schedule function + """ + + def __init__( + self, + num_train_timesteps: int = 1000, + schedule: str = "linear_beta", + skip_prk_steps: bool = False, + set_alpha_to_one: bool = False, + prediction_type: str = PNDMPredictionType.EPSILON, + steps_offset: int = 0, + **schedule_args, + ) -> None: + super().__init__(num_train_timesteps, schedule, **schedule_args) + + if prediction_type not in PNDMPredictionType.__members__.values(): + raise ValueError("Argument `prediction_type` must be a member of PNDMPredictionType") + + self.prediction_type = prediction_type + + self.final_alpha_cumprod = torch.tensor(1.0) if set_alpha_to_one else self.alphas_cumprod[0] + + # standard deviation of the initial noise distribution + self.init_noise_sigma = 1.0 + + # For now we only support F-PNDM, i.e. the runge-kutta method + # For more information on the algorithm please take a look at the paper: https://arxiv.org/pdf/2202.09778.pdf + # mainly at formula (9), (12), (13) and the Algorithm 2. + self.pndm_order = 4 + + self.skip_prk_steps = skip_prk_steps + self.steps_offset = steps_offset + + # running values + self.cur_model_output = torch.Tensor() + self.counter = 0 + self.cur_sample = torch.Tensor() + self.ets: list = [] + + # default the number of inference timesteps to the number of train steps + self.set_timesteps(num_train_timesteps) + + def set_timesteps( + self, num_inference_steps: int, device: str | torch.device | None = None + ) -> None: + """ + Sets the discrete timesteps used for the diffusion chain. Supporting function to be run before inference. + + Args: + num_inference_steps: number of diffusion steps used when generating samples with a pre-trained model. + device: target device to put the data. + """ + if num_inference_steps > self.num_train_timesteps: + raise ValueError( + f"`num_inference_steps`: {num_inference_steps} cannot be larger than `self.num_train_timesteps`:" + f" {self.num_train_timesteps} as the unet model trained with this scheduler can only handle" + f" maximal {self.num_train_timesteps} timesteps." + ) + + self.num_inference_steps = num_inference_steps + step_ratio = self.num_train_timesteps // self.num_inference_steps + # creates integer timesteps by multiplying by ratio + # casting to int to avoid issues when num_inference_step is power of 3 + self._timesteps = (np.arange(0, num_inference_steps) * step_ratio).round().astype(np.int64) + self._timesteps += self.steps_offset + + if self.skip_prk_steps: + # for some models like stable diffusion the prk steps can/should be skipped to + # produce better results. When using PNDM with `self.skip_prk_steps` the implementation + # is based on crowsonkb's PLMS sampler implementation: https://github.com/CompVis/latent-diffusion/pull/51 + self.prk_timesteps = np.array([]) + self.plms_timesteps = self._timesteps[::-1] + + else: + prk_timesteps = np.array(self._timesteps[-self.pndm_order :]).repeat(2) + np.tile( + np.array([0, self.num_train_timesteps // num_inference_steps // 2]), self.pndm_order + ) + self.prk_timesteps = (prk_timesteps[:-1].repeat(2)[1:-1])[::-1].copy() + self.plms_timesteps = self._timesteps[:-3][ + ::-1 + ].copy() # we copy to avoid having negative strides which are not supported by torch.from_numpy + + timesteps = np.concatenate([self.prk_timesteps, self.plms_timesteps]).astype(np.int64) + self.timesteps = torch.from_numpy(timesteps).to(device) + # update num_inference_steps - necessary if we use prk steps + self.num_inference_steps = len(self.timesteps) + + self.ets = [] + self.counter = 0 + + def step( + self, model_output: torch.Tensor, timestep: int, sample: torch.Tensor + ) -> tuple[torch.Tensor, Any]: + """ + Predict the sample at the previous timestep by reversing the SDE. Core function to propagate the diffusion + process from the learned model outputs (most often the predicted noise). + This function calls `step_prk()` or `step_plms()` depending on the internal variable `counter`. + + Args: + model_output: direct output from learned diffusion model. + timestep: current discrete timestep in the diffusion chain. + sample: current instance of sample being created by diffusion process. + Returns: + pred_prev_sample: Predicted previous sample + """ + # return a tuple for consistency with samplers that return (previous pred, original sample pred) + + if self.counter < len(self.prk_timesteps) and not self.skip_prk_steps: + return self.step_prk(model_output=model_output, timestep=timestep, sample=sample), None + else: + return self.step_plms(model_output=model_output, timestep=timestep, sample=sample), None + + def step_prk( + self, model_output: torch.Tensor, timestep: int, sample: torch.Tensor + ) -> torch.Tensor: + """ + Step function propagating the sample with the Runge-Kutta method. RK takes 4 forward passes to approximate the + solution to the differential equation. + + Args: + model_output: direct output from learned diffusion model. + timestep: current discrete timestep in the diffusion chain. + sample: current instance of sample being created by diffusion process. + + Returns: + pred_prev_sample: Predicted previous sample + """ + if self.num_inference_steps is None: + raise ValueError( + "Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler" + ) + + diff_to_prev = ( + 0 if self.counter % 2 else self.num_train_timesteps // self.num_inference_steps // 2 + ) + prev_timestep = timestep - diff_to_prev + timestep = self.prk_timesteps[self.counter // 4 * 4] + + if self.counter % 4 == 0: + self.cur_model_output = 1 / 6 * model_output + self.ets.append(model_output) + self.cur_sample = sample + elif (self.counter - 1) % 4 == 0: + self.cur_model_output += 1 / 3 * model_output + elif (self.counter - 2) % 4 == 0: + self.cur_model_output += 1 / 3 * model_output + elif (self.counter - 3) % 4 == 0: + model_output = self.cur_model_output + 1 / 6 * model_output + self.cur_model_output = torch.Tensor() + + # cur_sample should not be an empty torch.Tensor() + cur_sample = self.cur_sample if self.cur_sample.numel() != 0 else sample + + prev_sample: torch.Tensor = self._get_prev_sample( + cur_sample, timestep, prev_timestep, model_output + ) + self.counter += 1 + + return prev_sample + + def step_plms(self, model_output: torch.Tensor, timestep: int, sample: torch.Tensor) -> Any: + """ + Step function propagating the sample with the linear multi-step method. This has one forward pass with multiple + times to approximate the solution. + + Args: + model_output: direct output from learned diffusion model. + timestep: current discrete timestep in the diffusion chain. + sample: current instance of sample being created by diffusion process. + + Returns: + pred_prev_sample: Predicted previous sample + """ + if self.num_inference_steps is None: + raise ValueError( + "Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler" + ) + + if not self.skip_prk_steps and len(self.ets) < 3: + raise ValueError( + f"{self.__class__} can only be run AFTER scheduler has been run " + "in 'prk' mode for at least 12 iterations " + ) + + prev_timestep = timestep - self.num_train_timesteps // self.num_inference_steps + + if self.counter != 1: + self.ets = self.ets[-3:] + self.ets.append(model_output) + else: + prev_timestep = timestep + timestep = timestep + self.num_train_timesteps // self.num_inference_steps + + if len(self.ets) == 1 and self.counter == 0: + model_output = model_output + self.cur_sample = sample + elif len(self.ets) == 1 and self.counter == 1: + model_output = (model_output + self.ets[-1]) / 2 + sample = self.cur_sample + self.cur_sample = torch.Tensor() + elif len(self.ets) == 2: + model_output = (3 * self.ets[-1] - self.ets[-2]) / 2 + elif len(self.ets) == 3: + model_output = (23 * self.ets[-1] - 16 * self.ets[-2] + 5 * self.ets[-3]) / 12 + else: + model_output = (1 / 24) * ( + 55 * self.ets[-1] - 59 * self.ets[-2] + 37 * self.ets[-3] - 9 * self.ets[-4] + ) + + prev_sample = self._get_prev_sample(sample, timestep, prev_timestep, model_output) + self.counter += 1 + + return prev_sample + + def _get_prev_sample( + self, sample: torch.Tensor, timestep: int, prev_timestep: int, model_output: torch.Tensor + ): + # See formula (9) of PNDM paper https://arxiv.org/pdf/2202.09778.pdf + # this function computes x_(t−δ) using the formula of (9) + # Note that x_t needs to be added to both sides of the equation + + # Notation ( -> + # alpha_prod_t -> α_t + # alpha_prod_t_prev -> α_(t−δ) + # beta_prod_t -> (1 - α_t) + # beta_prod_t_prev -> (1 - α_(t−δ)) + # sample -> x_t + # model_output -> e_θ(x_t, t) + # prev_sample -> x_(t−δ) + alpha_prod_t = self.alphas_cumprod[timestep] + alpha_prod_t_prev = ( + self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod + ) + beta_prod_t = 1 - alpha_prod_t + beta_prod_t_prev = 1 - alpha_prod_t_prev + + if self.prediction_type == PNDMPredictionType.V_PREDICTION: + model_output = (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample + + # corresponds to (α_(t−δ) - α_t) divided by + # denominator of x_t in formula (9) and plus 1 + # Note: (α_(t−δ) - α_t) / (sqrt(α_t) * (sqrt(α_(t−δ)) + sqr(α_t))) = + # sqrt(α_(t−δ)) / sqrt(α_t)) + sample_coeff = (alpha_prod_t_prev / alpha_prod_t) ** (0.5) + + # corresponds to denominator of e_θ(x_t, t) in formula (9) + model_output_denom_coeff = alpha_prod_t * beta_prod_t_prev ** (0.5) + ( + alpha_prod_t * beta_prod_t * alpha_prod_t_prev + ) ** (0.5) + + # full formula (9) + prev_sample = ( + sample_coeff * sample + - (alpha_prod_t_prev - alpha_prod_t) * model_output / model_output_denom_coeff + ) + + return prev_sample diff --git a/itrialspace/src/itrialspace/synthesis/scripts/schedulers/rectified_flow.py b/itrialspace/src/itrialspace/synthesis/scripts/schedulers/rectified_flow.py new file mode 100644 index 0000000000000000000000000000000000000000..cf402ae222a39c8b943dd76b79387fad212bd9fa --- /dev/null +++ b/itrialspace/src/itrialspace/synthesis/scripts/schedulers/rectified_flow.py @@ -0,0 +1,337 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# ========================================================================= +# Adapted from https://github.com/hpcaitech/Open-Sora/blob/main/opensora/schedulers/rf/rectified_flow.py +# which has the following license: +# https://github.com/hpcaitech/Open-Sora/blob/main/LICENSE +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ========================================================================= + +from __future__ import annotations + +from typing import Union + +import numpy as np +import torch +from monai.utils import StrEnum +from torch.distributions import LogisticNormal + +from .ddpm import DDPMPredictionType +from .scheduler import Scheduler + + +class RFlowPredictionType(StrEnum): + """ + Set of valid prediction type names for the RFlow scheduler's `prediction_type` argument. + + v_prediction: velocity prediction, see section 2.4 https://imagen.research.google/video/paper.pdf + """ + + V_PREDICTION = DDPMPredictionType.V_PREDICTION + + +def timestep_transform( + t, + input_img_size_numel, + base_img_size_numel=32 * 32 * 32, + scale=1.0, + num_train_timesteps=1000, + spatial_dim=3, +): + """ + Applies a transformation to the timestep based on image resolution scaling. + + Args: + t (torch.Tensor): The original timestep(s). + input_img_size_numel (torch.Tensor): The input image's size (H * W * D). + base_img_size_numel (int): reference H*W*D size, usually smaller than input_img_size_numel. + scale (float): Scaling factor for the transformation. + num_train_timesteps (int): Total number of training timesteps. + spatial_dim (int): Number of spatial dimensions in the image. + + Returns: + torch.Tensor: Transformed timestep(s). + """ + t = t / num_train_timesteps + ratio_space = (input_img_size_numel / base_img_size_numel) ** (1.0 / spatial_dim) + + ratio = ratio_space * scale + new_t = ratio * t / (1 + (ratio - 1) * t) + + new_t = new_t * num_train_timesteps + return new_t + + +class RFlowScheduler(Scheduler): + """ + A rectified flow scheduler for guiding the diffusion process in a generative model. + + Supports uniform and logit-normal sampling methods, timestep transformation for + different resolutions, and noise addition during diffusion. + + Args: + num_train_timesteps (int): Total number of training timesteps. + use_discrete_timesteps (bool): Whether to use discrete timesteps. + sample_method (str): Training time step sampling method ('uniform' or 'logit-normal'). + loc (float): Location parameter for logit-normal distribution, used only if sample_method='logit-normal'. + scale (float): Scale parameter for logit-normal distribution, used only if sample_method='logit-normal'. + use_timestep_transform (bool): Whether to apply timestep transformation. + If true, there will be more inference timesteps at early(noisy) stages for larger image volumes. + transform_scale (float): Scaling factor for timestep transformation, used only if use_timestep_transform=True. + steps_offset (int): Offset added to computed timesteps, used only if use_timestep_transform=True. + base_img_size_numel (int): Reference image volume size for scaling, used only if use_timestep_transform=True. + spatial_dim (int): 2 or 3, incidcating 2D or 3D images, used only if use_timestep_transform=True. + + Example: + + .. code-block:: python + + # define a scheduler + noise_scheduler = RFlowScheduler( + num_train_timesteps = 1000, + use_discrete_timesteps = True, + sample_method = 'logit-normal', + use_timestep_transform = True, + base_img_size_numel = 32 * 32 * 32, + spatial_dim = 3 + ) + + # during training + inputs = torch.ones(2,4,64,64,32) + noise = torch.randn_like(inputs) + timesteps = noise_scheduler.sample_timesteps(inputs) + noisy_inputs = noise_scheduler.add_noise(original_samples=inputs, noise=noise, timesteps=timesteps) + predicted_velocity = diffusion_unet( + x=noisy_inputs, + timesteps=timesteps + ) + loss = loss_l1(predicted_velocity, (inputs - noise)) + + # during inference + noisy_inputs = torch.randn(2,4,64,64,32) + input_img_size_numel = torch.prod(torch.tensor(noisy_inputs.shape[-3:]) + noise_scheduler.set_timesteps( + num_inference_steps=30, input_img_size_numel=input_img_size_numel) + ) + all_next_timesteps = torch.cat( + (noise_scheduler.timesteps[1:], torch.tensor([0], dtype=noise_scheduler.timesteps.dtype)) + ) + for t, next_t in tqdm( + zip(noise_scheduler.timesteps, all_next_timesteps), + total=min(len(noise_scheduler.timesteps), len(all_next_timesteps)), + ): + predicted_velocity = diffusion_unet( + x=noisy_inputs, + timesteps=timesteps + ) + noisy_inputs, _ = noise_scheduler.step(predicted_velocity, t, noisy_inputs, next_t) + final_output = noisy_inputs + """ + + def __init__( + self, + num_train_timesteps: int = 1000, + use_discrete_timesteps: bool = True, + sample_method: str = "uniform", + loc: float = 0.0, + scale: float = 1.0, + use_timestep_transform: bool = False, + transform_scale: float = 1.0, + steps_offset: int = 0, + base_img_size_numel: int = 32 * 32 * 32, + spatial_dim: int = 3, + ): + # rectified flow only accepts velocity prediction + self.prediction_type = RFlowPredictionType.V_PREDICTION + + self.num_train_timesteps = num_train_timesteps + self.use_discrete_timesteps = use_discrete_timesteps + self.base_img_size_numel = base_img_size_numel + self.spatial_dim = spatial_dim + + # sample method + if sample_method not in ["uniform", "logit-normal"]: + raise ValueError( + f"sample_method = {sample_method}, which has to be chosen from ['uniform', 'logit-normal']." + ) + self.sample_method = sample_method + if sample_method == "logit-normal": + self.distribution = LogisticNormal(torch.tensor([loc]), torch.tensor([scale])) + self.sample_t = lambda x: self.distribution.sample((x.shape[0],))[:, 0].to(x.device) + + # timestep transform + self.use_timestep_transform = use_timestep_transform + self.transform_scale = transform_scale + self.steps_offset = steps_offset + + def add_noise( + self, original_samples: torch.Tensor, noise: torch.Tensor, timesteps: torch.Tensor + ) -> torch.Tensor: + """ + Add noise to the original samples. + + Args: + original_samples: original samples + noise: noise to add to samples + timesteps: timesteps tensor with shape of (N,), indicating the timestep to be computed for each sample. + + Returns: + noisy_samples: sample with added noise + """ + timepoints: torch.Tensor = timesteps.float() / self.num_train_timesteps + timepoints = 1 - timepoints # [1,1/1000] + + # expand timepoint to noise shape + if noise.ndim == 5: + timepoints = timepoints[..., None, None, None, None].expand(-1, *noise.shape[1:]) + elif noise.ndim == 4: + timepoints = timepoints[..., None, None, None].expand(-1, *noise.shape[1:]) + else: + raise ValueError( + f"noise tensor has to be 4D or 5D tensor, yet got shape of {noise.shape}" + ) + + noisy_samples: torch.Tensor = timepoints * original_samples + (1 - timepoints) * noise + + return noisy_samples + + def set_timesteps( + self, + num_inference_steps: int, + device: str | torch.device | None = None, + input_img_size_numel: int | None = None, + ) -> None: + """ + Sets the discrete timesteps used for the diffusion chain. Supporting function to be run before inference. + + Args: + num_inference_steps: number of diffusion steps used when generating samples with a pre-trained model. + device: target device to put the data. + input_img_size_numel: int, H*W*D of the image, used with self.use_timestep_transform is True. + """ + if num_inference_steps > self.num_train_timesteps or num_inference_steps < 1: + raise ValueError( + f"`num_inference_steps`: {num_inference_steps} should be at least 1, " + "and cannot be larger than `self.num_train_timesteps`:" + f" {self.num_train_timesteps} as the unet model trained with this scheduler can only handle" + f" maximal {self.num_train_timesteps} timesteps." + ) + + self.num_inference_steps = num_inference_steps + # prepare timesteps + timesteps = [ + (1.0 - i / self.num_inference_steps) * self.num_train_timesteps + for i in range(self.num_inference_steps) + ] + if self.use_discrete_timesteps: + timesteps = [int(round(t)) for t in timesteps] + if self.use_timestep_transform: + timesteps = [ + timestep_transform( + t, + input_img_size_numel=input_img_size_numel, + base_img_size_numel=self.base_img_size_numel, + num_train_timesteps=self.num_train_timesteps, + spatial_dim=self.spatial_dim, + ) + for t in timesteps + ] + timesteps_np = np.array(timesteps).astype(np.float16) + if self.use_discrete_timesteps: + timesteps_np = timesteps_np.astype(np.int64) + self.timesteps = torch.from_numpy(timesteps_np).to(device) + self.timesteps += self.steps_offset + + def sample_timesteps(self, x_start): + """ + Randomly samples training timesteps using the chosen sampling method. + + Args: + x_start (torch.Tensor): The input tensor for sampling. + + Returns: + torch.Tensor: Sampled timesteps. + """ + if self.sample_method == "uniform": + t = torch.rand((x_start.shape[0],), device=x_start.device) * self.num_train_timesteps + elif self.sample_method == "logit-normal": + t = self.sample_t(x_start) * self.num_train_timesteps + + if self.use_discrete_timesteps: + t = t.long() + + if self.use_timestep_transform: + input_img_size_numel = torch.prod(torch.tensor(x_start.shape[2:])) + t = timestep_transform( + t, + input_img_size_numel=input_img_size_numel, + base_img_size_numel=self.base_img_size_numel, + num_train_timesteps=self.num_train_timesteps, + spatial_dim=len(x_start.shape) - 2, + ) + + return t + + def step( + self, + model_output: torch.Tensor, + timestep: int, + sample: torch.Tensor, + next_timestep: Union[int, None] = None, + ) -> tuple[torch.Tensor, torch.Tensor]: + """ + Predicts the next sample in the diffusion process. + + Args: + model_output (torch.Tensor): Output from the trained diffusion model. + timestep (int): Current timestep in the diffusion chain. + sample (torch.Tensor): Current sample in the process. + next_timestep (Union[int, None]): Optional next timestep. + + Returns: + tuple[torch.Tensor, torch.Tensor]: Predicted sample at the next step and additional info. + """ + # Ensure num_inference_steps exists and is a valid integer + if not hasattr(self, "num_inference_steps") or not isinstance( + self.num_inference_steps, int + ): + raise AttributeError( + "num_inference_steps is missing or not an integer in the class." + "Please run self.set_timesteps(num_inference_steps,device,input_img_size_numel) to set it." + ) + + v_pred = model_output + + if next_timestep is not None: + next_timestep = int(next_timestep) + dt: float = ( + float(timestep - next_timestep) / self.num_train_timesteps + ) # Now next_timestep is guaranteed to be int + else: + dt = ( + 1.0 / float(self.num_inference_steps) if self.num_inference_steps > 0 else 0.0 + ) # Avoid division by zero + + pred_post_sample = sample + v_pred * dt + pred_original_sample = sample + v_pred * timestep / self.num_train_timesteps + + return pred_post_sample, pred_original_sample diff --git a/itrialspace/src/itrialspace/synthesis/scripts/schedulers/scheduler.py b/itrialspace/src/itrialspace/synthesis/scripts/schedulers/scheduler.py new file mode 100644 index 0000000000000000000000000000000000000000..66dd2dc6703018449d626f4ded55b6944dd36179 --- /dev/null +++ b/itrialspace/src/itrialspace/synthesis/scripts/schedulers/scheduler.py @@ -0,0 +1,223 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# ========================================================================= +# Adapted from https://github.com/huggingface/diffusers +# which has the following license: +# https://github.com/huggingface/diffusers/blob/main/LICENSE +# +# Copyright 2022 UC Berkeley Team and The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ========================================================================= + + +from __future__ import annotations + +import torch +import torch.nn as nn +from monai.utils import ComponentStore, unsqueeze_right + +NoiseSchedules = ComponentStore("NoiseSchedules", "Functions to generate noise schedules") + + +@NoiseSchedules.add_def("linear_beta", "Linear beta schedule") +def _linear_beta(num_train_timesteps: int, beta_start: float = 1e-4, beta_end: float = 2e-2): + """ + Linear beta noise schedule function. + + Args: + num_train_timesteps: number of timesteps + beta_start: start of beta range, default 1e-4 + beta_end: end of beta range, default 2e-2 + + Returns: + betas: beta schedule tensor + """ + return torch.linspace(beta_start, beta_end, num_train_timesteps, dtype=torch.float32) + + +@NoiseSchedules.add_def("scaled_linear_beta", "Scaled linear beta schedule") +def _scaled_linear_beta(num_train_timesteps: int, beta_start: float = 1e-4, beta_end: float = 2e-2): + """ + Scaled linear beta noise schedule function. + + Args: + num_train_timesteps: number of timesteps + beta_start: start of beta range, default 1e-4 + beta_end: end of beta range, default 2e-2 + + Returns: + betas: beta schedule tensor + """ + return ( + torch.linspace(beta_start**0.5, beta_end**0.5, num_train_timesteps, dtype=torch.float32) + ** 2 + ) + + +@NoiseSchedules.add_def("sigmoid_beta", "Sigmoid beta schedule") +def _sigmoid_beta( + num_train_timesteps: int, beta_start: float = 1e-4, beta_end: float = 2e-2, sig_range: float = 6 +): + """ + Sigmoid beta noise schedule function. + + Args: + num_train_timesteps: number of timesteps + beta_start: start of beta range, default 1e-4 + beta_end: end of beta range, default 2e-2 + sig_range: pos/neg range of sigmoid input, default 6 + + Returns: + betas: beta schedule tensor + """ + betas = torch.linspace(-sig_range, sig_range, num_train_timesteps) + return torch.sigmoid(betas) * (beta_end - beta_start) + beta_start + + +@NoiseSchedules.add_def("cosine", "Cosine schedule") +def _cosine_beta(num_train_timesteps: int, s: float = 8e-3): + """ + Cosine noise schedule, see https://arxiv.org/abs/2102.09672 + + Args: + num_train_timesteps: number of timesteps + s: smoothing factor, default 8e-3 (see referenced paper) + + Returns: + (betas, alphas, alpha_cumprod) values + """ + x = torch.linspace(0, num_train_timesteps, num_train_timesteps + 1) + alphas_cumprod = torch.cos(((x / num_train_timesteps) + s) / (1 + s) * torch.pi * 0.5) ** 2 + alphas_cumprod /= alphas_cumprod[0].item() + betas = 1.0 - (alphas_cumprod[1:] / alphas_cumprod[:-1]) + betas = torch.clip(betas, 0.0, 0.999) + alphas = 1.0 - betas + alphas_cumprod = torch.cumprod(alphas, dim=0) + return betas, alphas, alphas_cumprod + + +class Scheduler(nn.Module): + """ + Base class for other schedulers based on a noise schedule function. + + This class is meant as the base for other schedulers which implement their own way of sampling or stepping. Here + the class defines beta, alpha, and alpha_cumprod values from a noise schedule function named with `schedule`, + which is the name of a component in NoiseSchedules. These components must all be callables which return either + the beta schedule alone or a triple containing (betas, alphas, alphas_cumprod) values. New schedule functions + can be provided by using the NoiseSchedules.add_def, for example: + + .. code-block:: python + + from monai.networks.schedulers import NoiseSchedules, DDPMScheduler + + @NoiseSchedules.add_def("my_beta_schedule", "Some description of your function") + def _beta_function(num_train_timesteps, beta_start=1e-4, beta_end=2e-2): + return torch.linspace(beta_start, beta_end, num_train_timesteps, dtype=torch.float32) + + scheduler = DDPMScheduler(num_train_timesteps=1000, schedule="my_beta_schedule") + + All such functions should have an initial positional integer argument `num_train_timesteps` stating the number of + timesteps the schedule is for, otherwise any other arguments can be given which will be passed by keyword through + the constructor's `schedule_args` value. To see what noise functions are available, print the object NoiseSchedules + to get a listing of stored objects with their docstring descriptions. + + Note: in previous versions of the schedulers the argument `schedule_beta` was used to state the beta schedule + type, this now replaced with `schedule` and most names used with the previous argument now have "_beta" appended + to them, eg. 'schedule_beta="linear"' -> 'schedule="linear_beta"'. The `beta_start` and `beta_end` arguments are + still used for some schedules but these are provided as keyword arguments now. + + Args: + num_train_timesteps: number of diffusion steps used to train the model. + schedule: member of NoiseSchedules, + a named function returning the beta tensor or (betas, alphas, alphas_cumprod) triple + schedule_args: arguments to pass to the schedule function + """ + + def __init__( + self, num_train_timesteps: int = 1000, schedule: str = "linear_beta", **schedule_args + ) -> None: + super().__init__() + schedule_args["num_train_timesteps"] = num_train_timesteps + noise_sched = NoiseSchedules[schedule](**schedule_args) + + # set betas, alphas, alphas_cumprod based off return value from noise function + if isinstance(noise_sched, tuple): + self.betas, self.alphas, self.alphas_cumprod = noise_sched + else: + self.betas = noise_sched + self.alphas = 1.0 - self.betas + self.alphas_cumprod = torch.cumprod(self.alphas, dim=0) + + self.num_train_timesteps = num_train_timesteps + self.one = torch.tensor(1.0) + + # settable values + self.num_inference_steps: int | None = None + self.timesteps = torch.arange(num_train_timesteps - 1, -1, -1) + + def add_noise( + self, original_samples: torch.Tensor, noise: torch.Tensor, timesteps: torch.Tensor + ) -> torch.Tensor: + """ + Add noise to the original samples. + + Args: + original_samples: original samples + noise: noise to add to samples + timesteps: timesteps tensor indicating the timestep to be computed for each sample. + + Returns: + noisy_samples: sample with added noise + """ + # Make sure alphas_cumprod and timestep have same device and dtype as original_samples + self.alphas_cumprod = self.alphas_cumprod.to( + device=original_samples.device, dtype=original_samples.dtype + ) + timesteps = timesteps.to(original_samples.device) + + sqrt_alpha_cumprod: torch.Tensor = unsqueeze_right( + self.alphas_cumprod[timesteps] ** 0.5, original_samples.ndim + ) + sqrt_one_minus_alpha_prod: torch.Tensor = unsqueeze_right( + (1 - self.alphas_cumprod[timesteps]) ** 0.5, original_samples.ndim + ) + + noisy_samples = sqrt_alpha_cumprod * original_samples + sqrt_one_minus_alpha_prod * noise + return noisy_samples + + def get_velocity( + self, sample: torch.Tensor, noise: torch.Tensor, timesteps: torch.Tensor + ) -> torch.Tensor: + # Make sure alphas_cumprod and timestep have same device and dtype as sample + self.alphas_cumprod = self.alphas_cumprod.to(device=sample.device, dtype=sample.dtype) + timesteps = timesteps.to(sample.device) + + sqrt_alpha_prod: torch.Tensor = unsqueeze_right( + self.alphas_cumprod[timesteps] ** 0.5, sample.ndim + ) + sqrt_one_minus_alpha_prod: torch.Tensor = unsqueeze_right( + (1 - self.alphas_cumprod[timesteps]) ** 0.5, sample.ndim + ) + + velocity = sqrt_alpha_prod * noise - sqrt_one_minus_alpha_prod * sample + return velocity diff --git a/itrialspace/src/itrialspace/synthesis/scripts/train_controlnet.py b/itrialspace/src/itrialspace/synthesis/scripts/train_controlnet.py new file mode 100644 index 0000000000000000000000000000000000000000..bcbbd3621f7b0c2615af554c9b8000e495ad2c09 --- /dev/null +++ b/itrialspace/src/itrialspace/synthesis/scripts/train_controlnet.py @@ -0,0 +1,379 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import argparse +import json +import logging +import os +import sys +import time +from datetime import timedelta +from pathlib import Path + +import torch +import torch.distributed as dist +import torch.nn.functional as F +from monai.networks.schedulers import RFlowScheduler + +# from .schedulers.rectified_flow import RFlowScheduler +from monai.networks.schedulers.ddpm import DDPMPredictionType +from monai.networks.utils import copy_model_state +from monai.utils import RankFilter +from torch.amp import GradScaler, autocast +from torch.nn.parallel import DistributedDataParallel as DDP +from torch.utils.tensorboard import SummaryWriter + +from .utils import ( + binarize_labels, + define_instance, + prepare_maisi_controlnet_json_dataloader, + setup_ddp, +) + + +def main(): + parser = argparse.ArgumentParser(description="maisi.controlnet.training") + parser.add_argument( + "-e", + "--environment-file", + default="./configs/environment_maisi_controlnet_train.json", + help="environment json file that stores environment path", + ) + parser.add_argument( + "-c", + "--config-file", + default="./configs/config_maisi-ddpm.json", + help="config json file that stores network hyper-parameters", + ) + parser.add_argument( + "-t", + "--training-config", + default="./configs/config_maisi_controlnet_train.json", + help="config json file that stores training hyper-parameters", + ) + parser.add_argument("-g", "--gpus", default=1, type=int, help="number of gpus per node") + + args = parser.parse_args() + + # Step 0: configuration + logger = logging.getLogger("maisi.controlnet.training") + # whether to use distributed data parallel + use_ddp = args.gpus > 1 + if use_ddp: + rank = int(os.environ["LOCAL_RANK"]) + world_size = int(os.environ["WORLD_SIZE"]) + device = setup_ddp(rank, world_size) + logger.addFilter(RankFilter()) + else: + rank = 0 + world_size = 1 + device = torch.device(f"cuda:{rank}") + + torch.cuda.set_device(device) + logger.info(f"Number of GPUs: {torch.cuda.device_count()}") + logger.info(f"World_size: {world_size}") + + with open(args.environment_file, "r") as env_file: + env_dict = json.load(env_file) + with open(args.config_file, "r") as config_file: + config_dict = json.load(config_file) + with open(args.training_config, "r") as training_config_file: + training_config_dict = json.load(training_config_file) + + for k, v in env_dict.items(): + setattr(args, k, v) + for k, v in config_dict.items(): + setattr(args, k, v) + for k, v in training_config_dict.items(): + setattr(args, k, v) + + # initialize tensorboard writer + if rank == 0: + tensorboard_path = os.path.join(args.tfevent_path, args.exp_name) + Path(tensorboard_path).mkdir(parents=True, exist_ok=True) + tensorboard_writer = SummaryWriter(tensorboard_path) + + # Step 1: set data loader + train_loader, _ = prepare_maisi_controlnet_json_dataloader( + json_data_list=args.json_data_list, + data_base_dir=args.data_base_dir, + rank=rank, + world_size=world_size, + batch_size=args.controlnet_train["batch_size"], + cache_rate=args.controlnet_train["cache_rate"], + fold=args.controlnet_train["fold"], + ) + + # Step 2: define diffusion model and controlnet + # define diffusion Model + unet = define_instance(args, "diffusion_unet_def").to(device) + include_body_region = unet.include_top_region_index_input + include_modality = unet.num_class_embeds is not None + + # load trained diffusion model + if args.trained_diffusion_path is not None: + if not os.path.exists(args.trained_diffusion_path): + raise ValueError("Please download the trained diffusion unet checkpoint.") + diffusion_model_ckpt = torch.load( + args.trained_diffusion_path, map_location=device, weights_only=False + ) + unet.load_state_dict(diffusion_model_ckpt["unet_state_dict"]) + # load scale factor from diffusion model checkpoint + scale_factor = diffusion_model_ckpt["scale_factor"] + logger.info(f"Load trained diffusion model from {args.trained_diffusion_path}.") + logger.info(f"loaded scale_factor from diffusion model ckpt -> {scale_factor}.") + else: + logger.info("trained diffusion model is not loaded.") + scale_factor = 1.0 + logger.info(f"set scale_factor -> {scale_factor}.") + + # define ControlNet + controlnet = define_instance(args, "controlnet_def").to(device) + # copy weights from the DM to the controlnet + copy_model_state(controlnet, unet.state_dict()) + # load trained controlnet model if it is provided + if args.trained_controlnet_path is not None: + if not os.path.exists(args.trained_controlnet_path): + raise ValueError("Please download the trained ControlNet checkpoint.") + controlnet.load_state_dict( + torch.load(args.trained_controlnet_path, map_location=device, weights_only=False)[ + "controlnet_state_dict" + ] + ) + logger.info(f"load trained controlnet model from {args.trained_controlnet_path}") + else: + logger.info("train controlnet model from scratch.") + # we freeze the parameters of the diffusion model. + for p in unet.parameters(): + p.requires_grad = False + + noise_scheduler = define_instance(args, "noise_scheduler") + + if use_ddp: + controlnet = DDP( + controlnet, device_ids=[device], output_device=rank, find_unused_parameters=True + ) + + # Step 3: training config + weighted_loss = args.controlnet_train["weighted_loss"] + weighted_loss_label = args.controlnet_train["weighted_loss_label"] + optimizer = torch.optim.AdamW(params=controlnet.parameters(), lr=args.controlnet_train["lr"]) + total_steps = ( + args.controlnet_train["n_epochs"] * len(train_loader.dataset) + ) / args.controlnet_train["batch_size"] + logger.info(f"total number of training steps: {total_steps}.") + + lr_scheduler = torch.optim.lr_scheduler.PolynomialLR( + optimizer, total_iters=total_steps, power=2.0 + ) + + # Step 4: training + n_epochs = args.controlnet_train["n_epochs"] + scaler = GradScaler("cuda") + total_step = 0 + best_loss = 1e4 + + if weighted_loss > 1.0: + logger.info(f"apply weighted loss = {weighted_loss} on labels: {weighted_loss_label}") + + controlnet.train() + unet.eval() + prev_time = time.time() + for epoch in range(n_epochs): + epoch_loss_ = 0 + for step, batch in enumerate(train_loader): + # logger.info(f"Reading image: {batch['image']}") + # logger.info(f"Reading image: {batch['image'].meta['filename_or_obj']}") + # logger.info(f"[Data Load] Step {step+1}: Reading sample {batch.get('image', 'N/A')}") + # get image embedding and label mask and scale image embedding by the provided scale_factor + images = batch["image"].to(device) * scale_factor + labels = batch["label"].to(device) + # get corresponding conditions + if include_body_region: + top_region_index_tensor = batch["top_region_index"].to(device) + bottom_region_index_tensor = batch["bottom_region_index"].to(device) + # We trained with only CT in this version + if include_modality: + modality_tensor = torch.ones((len(images),), dtype=torch.long).to(device) + spacing_tensor = batch["spacing"].to(device) + + optimizer.zero_grad(set_to_none=True) + + with autocast("cuda", enabled=True): + # generate random noise + noise_shape = list(images.shape) + noise = torch.randn(noise_shape, dtype=images.dtype).to(device) + + # use binary encoding to encode segmentation mask + controlnet_cond = binarize_labels(labels.as_tensor().to(torch.uint8)).float() + + # create timesteps + if isinstance(noise_scheduler, RFlowScheduler): + timesteps = noise_scheduler.sample_timesteps(images) + else: + timesteps = torch.randint( + 0, + noise_scheduler.num_train_timesteps, + (images.shape[0],), + device=images.device, + ).long() + + # create noisy latent + noisy_latent = noise_scheduler.add_noise( + original_samples=images, noise=noise, timesteps=timesteps + ) + + # get controlnet output + # Create a dictionary to store the inputs + controlnet_inputs = { + "x": noisy_latent, + "timesteps": timesteps, + "controlnet_cond": controlnet_cond, + } + if include_modality: + controlnet_inputs.update( + { + "class_labels": modality_tensor, + } + ) + down_block_res_samples, mid_block_res_sample = controlnet(**controlnet_inputs) + + # get diffusion network output + # Create a dictionary to store the inputs + unet_inputs = { + "x": noisy_latent, + "timesteps": timesteps, + "spacing_tensor": spacing_tensor, + "down_block_additional_residuals": down_block_res_samples, + "mid_block_additional_residual": mid_block_res_sample, + } + # Add extra arguments if include_body_region is True + if include_body_region: + unet_inputs.update( + { + "top_region_index_tensor": top_region_index_tensor, + "bottom_region_index_tensor": bottom_region_index_tensor, + } + ) + if include_modality: + unet_inputs.update( + { + "class_labels": modality_tensor, + } + ) + model_output = unet(**unet_inputs) + + if noise_scheduler.prediction_type == DDPMPredictionType.EPSILON: + # predict noise + model_gt = noise + elif noise_scheduler.prediction_type == DDPMPredictionType.SAMPLE: + # predict sample + model_gt = images + elif noise_scheduler.prediction_type == DDPMPredictionType.V_PREDICTION: + # predict velocity + model_gt = images - noise + else: + raise ValueError( + "noise scheduler prediction type has to be chosen from ", + f"[{DDPMPredictionType.EPSILON},{DDPMPredictionType.SAMPLE},{DDPMPredictionType.V_PREDICTION}]", + ) + + if weighted_loss > 1.0: + weights = torch.ones_like(images).to(images.device) + roi = torch.zeros([noise_shape[0]] + [1] + noise_shape[2:]).to(images.device) + interpolate_label = F.interpolate(labels, size=images.shape[2:], mode="nearest") + # assign larger weights for ROI (tumor) + for label in weighted_loss_label: + roi[interpolate_label == label] = 1 + weights[roi.repeat(1, images.shape[1], 1, 1, 1) == 1] = weighted_loss + loss = ( + F.l1_loss(model_output.float(), model_gt.float(), reduction="none") * weights + ).mean() + else: + loss = F.l1_loss(model_output.float(), model_gt.float()) + + scaler.scale(loss).backward() + scaler.step(optimizer) + scaler.update() + lr_scheduler.step() + total_step += 1 + + if rank == 0: + # write train loss for each batch into tensorboard + tensorboard_writer.add_scalar( + "train/train_controlnet_loss_iter", loss.detach().cpu().item(), total_step + ) + batches_done = step + 1 + batches_left = len(train_loader) - batches_done + time_left = timedelta(seconds=batches_left * (time.time() - prev_time)) + prev_time = time.time() + logger.info( + "\r[Epoch %d/%d] [Batch %d/%d] [LR: %.8f] [loss: %.4f] ETA: %s " + % ( + epoch + 1, + n_epochs, + step + 1, + len(train_loader), + lr_scheduler.get_last_lr()[0], + loss.detach().cpu().item(), + time_left, + ) + ) + epoch_loss_ += loss.detach() + + epoch_loss = epoch_loss_ / (step + 1) + + if use_ddp: + dist.barrier() + dist.all_reduce(epoch_loss, op=torch.distributed.ReduceOp.AVG) + + if rank == 0: + tensorboard_writer.add_scalar( + "train/train_controlnet_loss_epoch", epoch_loss.cpu().item(), total_step + ) + # save controlnet only on master GPU (rank 0) + controlnet_state_dict = ( + controlnet.module.state_dict() if world_size > 1 else controlnet.state_dict() + ) + torch.save( + { + "epoch": epoch + 1, + "loss": epoch_loss, + "controlnet_state_dict": controlnet_state_dict, + }, + f"{args.model_dir}/{args.exp_name}_current.pt", + ) + + if epoch_loss < best_loss: + best_loss = epoch_loss + logger.info(f"best loss -> {best_loss}.") + torch.save( + { + "epoch": epoch + 1, + "loss": best_loss, + "controlnet_state_dict": controlnet_state_dict, + }, + f"{args.model_dir}/{args.exp_name}_best.pt", + ) + + torch.cuda.empty_cache() + if use_ddp: + dist.destroy_process_group() + + +if __name__ == "__main__": + logging.basicConfig( + stream=sys.stdout, + level=logging.INFO, + format="[%(asctime)s.%(msecs)03d][%(levelname)5s](%(name)s) - %(message)s", + datefmt="%Y-%m-%d %H:%M:%S", + ) + main() diff --git a/itrialspace/src/itrialspace/synthesis/scripts/transforms.py b/itrialspace/src/itrialspace/synthesis/scripts/transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..49533feccac4d84bb1f41998900e89edd6bd158b --- /dev/null +++ b/itrialspace/src/itrialspace/synthesis/scripts/transforms.py @@ -0,0 +1,354 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import warnings +from typing import List, Optional + +import torch +from monai.transforms import ( + Compose, + DivisiblePadd, + EnsureChannelFirstd, + EnsureTyped, + Lambdad, + LoadImaged, + Orientationd, + RandAdjustContrastd, + RandBiasFieldd, + RandFlipd, + RandGibbsNoised, + RandHistogramShiftd, + RandRotate90d, + RandRotated, + RandScaleIntensityd, + RandShiftIntensityd, + RandSpatialCropd, + RandZoomd, + ResizeWithPadOrCropd, + ScaleIntensityRanged, + ScaleIntensityRangePercentilesd, + SelectItemsd, + Spacingd, + SpatialPadd, +) + +SUPPORT_MODALITIES = ["ct", "mri"] + + +def define_fixed_intensity_transform(modality: str, image_keys: List[str] = ["image"]) -> List: + """ + Define fixed intensity transform based on the modality. + + Args: + modality (str): The imaging modality, either 'ct' or 'mri'. + image_keys (List[str], optional): List of image keys. Defaults to ["image"]. + + Returns: + List: A list of intensity transforms. + """ + if modality not in SUPPORT_MODALITIES: + warnings.warn( + f"Intensity transform only support {SUPPORT_MODALITIES}. Got {modality}. Will not do any intensity transform and will use original intensities." + ) + + modality = modality.lower() # Normalize modality to lowercase + + intensity_transforms = { + "mri": [ + ScaleIntensityRangePercentilesd( + keys=image_keys, lower=0.0, upper=99.5, b_min=0.0, b_max=1, clip=False + ) + ], + "ct": [ + ScaleIntensityRanged( + keys=image_keys, a_min=-1000, a_max=1000, b_min=0.0, b_max=1.0, clip=True + ) + ], + } + + if modality not in intensity_transforms: + return [] + + return intensity_transforms[modality] + + +def define_random_intensity_transform(modality: str, image_keys: List[str] = ["image"]) -> List: + """ + Define random intensity transform based on the modality. + + Args: + modality (str): The imaging modality, either 'ct' or 'mri'. + image_keys (List[str], optional): List of image keys. Defaults to ["image"]. + + Returns: + List: A list of random intensity transforms. + """ + modality = modality.lower() # Normalize modality to lowercase + if modality not in SUPPORT_MODALITIES: + warnings.warn( + f"Intensity transform only support {SUPPORT_MODALITIES}. Got {modality}. Will not do any intensity transform and will use original intensities." + ) + + if modality == "ct": + return [] # CT HU intensity is stable across different datasets + elif modality == "mri": + return [ + RandBiasFieldd(keys=image_keys, prob=0.3, coeff_range=(0.0, 0.3)), + RandGibbsNoised(keys=image_keys, prob=0.3, alpha=(0.5, 1.0)), + RandAdjustContrastd(keys=image_keys, prob=0.3, gamma=(0.5, 2.0)), + RandHistogramShiftd(keys=image_keys, prob=0.05, num_control_points=10), + ] + else: + return [] + + +def define_vae_transform( + is_train: bool, + modality: str, + random_aug: bool, + k: int = 4, + patch_size: List[int] = [128, 128, 128], + val_patch_size: Optional[List[int]] = None, + output_dtype: torch.dtype = torch.float32, + spacing_type: str = "original", + spacing: Optional[List[float]] = None, + image_keys: List[str] = ["image"], + label_keys: List[str] = [], + additional_keys: List[str] = [], + select_channel: int = 0, +) -> tuple: + """ + Define the MAISI VAE transform pipeline for training or validation. + + Args: + is_train (bool): Whether it's for training or not. If True, the output transform will consider random_aug, the cropping will use "patch_size" for random cropping. If False, the output transform will alwasy treat "random_aug" as False, will use "val_patch_size" for central cropping. + modality (str): The imaging modality, either 'ct' or 'mri'. + random_aug (bool): Whether to apply random data augmentation. + k (int, optional): Patches should be divisible by k. Defaults to 4. + patch_size (List[int], optional): Size of the patches. Defaults to [128, 128, 128]. Will random crop patch for training. + val_patch_size (Optional[List[int]], optional): Size of validation patches. Defaults to None. If None, will use the whole volume for validation. If given, will central crop a patch for validation. + output_dtype (torch.dtype, optional): Output data type. Defaults to torch.float32. + spacing_type (str, optional): Type of spacing. Defaults to "original". Choose from ["original", "fixed", "rand_zoom"]. + spacing (Optional[List[float]], optional): Spacing values. Defaults to None. + image_keys (List[str], optional): List of image keys. Defaults to ["image"]. + label_keys (List[str], optional): List of label keys. Defaults to []. + additional_keys (List[str], optional): List of additional keys. Defaults to []. + select_channel (int, optional): Channel to select for multi-channel MRI. Defaults to 0. + + Returns: + tuple: A tuple containing Composed Transform train_transforms or val_transforms depending on 'is_train'. + """ + modality = modality.lower() # Normalize modality to lowercase + if modality not in SUPPORT_MODALITIES: + warnings.warn( + f"Intensity transform only support {SUPPORT_MODALITIES}. Got {modality}. Will not do any intensity transform and will use original intensities." + ) + + if spacing_type not in ["original", "fixed", "rand_zoom"]: + raise ValueError( + f"spacing_type has to be chosen from ['original', 'fixed', 'rand_zoom']. Got {spacing_type}." + ) + + keys = image_keys + label_keys + additional_keys + interp_mode = ["bilinear"] * len(image_keys) + ["nearest"] * len(label_keys) + + common_transform = [ + SelectItemsd(keys=keys, allow_missing_keys=True), + LoadImaged(keys=keys, allow_missing_keys=True), + EnsureChannelFirstd(keys=keys, allow_missing_keys=True), + Orientationd(keys=keys, axcodes="RAS", allow_missing_keys=True), + ] + + if modality == "mri": + common_transform.append( + Lambdad(keys=image_keys, func=lambda x: x[select_channel : select_channel + 1, ...]) + ) + + common_transform.extend(define_fixed_intensity_transform(modality, image_keys=image_keys)) + + if spacing_type == "fixed": + common_transform.append( + Spacingd( + keys=image_keys + label_keys, + allow_missing_keys=True, + pixdim=spacing, + mode=interp_mode, + ) + ) + + random_transform = [] + if is_train and random_aug: + random_transform.extend(define_random_intensity_transform(modality, image_keys=image_keys)) + random_transform.extend( + [ + RandFlipd(keys=keys, allow_missing_keys=True, prob=0.5, spatial_axis=axis) + for axis in range(3) + ] + + [ + RandRotate90d(keys=keys, allow_missing_keys=True, prob=0.5, spatial_axes=axes) + for axes in [(0, 1), (1, 2), (0, 2)] + ] + + [ + RandScaleIntensityd( + keys=image_keys, allow_missing_keys=True, prob=0.3, factors=(0.9, 1.1) + ), + RandShiftIntensityd( + keys=image_keys, allow_missing_keys=True, prob=0.3, offsets=0.05 + ), + ] + ) + + if spacing_type == "rand_zoom": + random_transform.extend( + [ + RandZoomd( + keys=image_keys + label_keys, + allow_missing_keys=True, + prob=0.3, + min_zoom=0.5, + max_zoom=1.5, + keep_size=False, + mode=interp_mode, + ), + RandRotated( + keys=image_keys + label_keys, + allow_missing_keys=True, + prob=0.3, + range_x=0.1, + range_y=0.1, + range_z=0.1, + keep_size=True, + mode=interp_mode, + ), + ] + ) + + if is_train: + train_crop = [ + SpatialPadd(keys=keys, spatial_size=patch_size, allow_missing_keys=True), + RandSpatialCropd( + keys=keys, + roi_size=patch_size, + allow_missing_keys=True, + random_size=False, + random_center=True, + ), + ] + else: + val_crop = ( + [DivisiblePadd(keys=keys, allow_missing_keys=True, k=k)] + if val_patch_size is None + else [ + ResizeWithPadOrCropd( + keys=keys, allow_missing_keys=True, spatial_size=val_patch_size + ) + ] + ) + + final_transform = [EnsureTyped(keys=keys, dtype=output_dtype, allow_missing_keys=True)] + + if is_train: + train_transforms = Compose( + common_transform + random_transform + train_crop + final_transform + if random_aug + else common_transform + train_crop + final_transform + ) + return train_transforms + else: + val_transforms = Compose(common_transform + val_crop + final_transform) + return val_transforms + + +class VAE_Transform: + """ + A class to handle MAISI VAE transformations for different modalities. + """ + + def __init__( + self, + is_train: bool, + random_aug: bool, + k: int = 4, + patch_size: List[int] = [128, 128, 128], + val_patch_size: Optional[List[int]] = None, + output_dtype: torch.dtype = torch.float32, + spacing_type: str = "original", + spacing: Optional[List[float]] = None, + image_keys: List[str] = ["image"], + label_keys: List[str] = [], + additional_keys: List[str] = [], + select_channel: int = 0, + ): + """ + Initialize the VAE_Transform. + + Args: + is_train (bool): Whether it's for training or not. If True, the output transform will consider random_aug, the cropping will use "patch_size" for random cropping. If False, the output transform will alwasy treat "random_aug" as False, will use "val_patch_size" for central cropping. + random_aug (bool): Whether to apply random data augmentation for training. + k (int, optional): Patches should be divisible by k. Defaults to 4. + patch_size (List[int], optional): Size of the patches. Defaults to [128, 128, 128]. Will random crop patch for training. + val_patch_size (Optional[List[int]], optional): Size of validation patches. Defaults to None. If None, will use the whole volume for validation. If given, will central crop a patch for validation. + output_dtype (torch.dtype, optional): Output data type. Defaults to torch.float32. + spacing_type (str, optional): Type of spacing. Defaults to "original". Choose from ["original", "fixed", "rand_zoom"]. + spacing (Optional[List[float]], optional): Spacing values. Defaults to None. + image_keys (List[str], optional): List of image keys. Defaults to ["image"]. + label_keys (List[str], optional): List of label keys. Defaults to []. + additional_keys (List[str], optional): List of additional keys. Defaults to []. + select_channel (int, optional): Channel to select for multi-channel MRI. Defaults to 0. + """ + if spacing_type not in ["original", "fixed", "rand_zoom"]: + raise ValueError( + f"spacing_type has to be chosen from ['original', 'fixed', 'rand_zoom']. Got {spacing_type}." + ) + + self.is_train = is_train + self.transform_dict = {} + + for modality in ["ct", "mri"]: + self.transform_dict[modality] = define_vae_transform( + is_train=is_train, + modality=modality, + random_aug=random_aug, + k=k, + patch_size=patch_size, + val_patch_size=val_patch_size, + output_dtype=output_dtype, + spacing_type=spacing_type, + spacing=spacing, + image_keys=image_keys, + label_keys=label_keys, + additional_keys=additional_keys, + select_channel=select_channel, + ) + + def __call__(self, img: dict, fixed_modality: Optional[str] = None) -> dict: + """ + Apply the appropriate transform to the input image. + + Args: + img (dict): Input image dictionary. + fixed_modality (Optional[str], optional): Fixed modality to use. Defaults to None. + + Returns: + Composed Transform + + Raises: + ValueError: If the modality is not 'ct' or 'mri'. + """ + modality = fixed_modality or img["class"] + modality = modality.lower() # Normalize modality to lowercase + if modality not in ["ct", "mri"]: + warnings.warn( + f"Intensity transform only support {SUPPORT_MODALITIES}. Got {modality}. Will not do any intensity transform and will use original intensities." + ) + + transform = self.transform_dict[modality] + return transform(img) diff --git a/itrialspace/src/itrialspace/synthesis/scripts/utils.py b/itrialspace/src/itrialspace/synthesis/scripts/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..8683e513b7b0aa5885cfaaf4dc51032b4501af7a --- /dev/null +++ b/itrialspace/src/itrialspace/synthesis/scripts/utils.py @@ -0,0 +1,1012 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import copy +import json +import logging +import math +import os +from argparse import Namespace +from datetime import timedelta +from typing import Any, Sequence + +import numpy as np +import skimage +import torch +import torch.distributed as dist +from monai.bundle import ConfigParser +from monai.config import DtypeLike, NdarrayOrTensor +from monai.data import CacheDataset, DataLoader, partition_dataset +from monai.transforms import Compose, EnsureTyped, Lambdad, LoadImaged, Orientationd +from monai.transforms.utils_morphological_ops import dilate, erode +from monai.utils import ( + TransformBackends, + convert_data_type, + convert_to_dst_type, + get_equivalent_dtype, +) +from scipy import stats +from torch import Tensor + + +def remap_labels(mask, label_dict_remap_json): + """ + Remap labels in the mask according to the provided label dictionary. + + This function reads a JSON file containing label mapping information and applies + the mapping to the input mask. + + Args: + mask (Tensor): The input mask tensor to be remapped. + label_dict_remap_json (str): Path to the JSON file containing the label mapping dictionary. + + Returns: + Tensor: The remapped mask tensor. + """ + with open(label_dict_remap_json, "r") as f: + mapping_dict = json.load(f) + mapper = MapLabelValue( + orig_labels=[pair[0] for pair in mapping_dict.values()], + target_labels=[pair[1] for pair in mapping_dict.values()], + dtype=torch.uint8, + ) + return mapper(mask[0, ...])[None, ...].to(mask.device) + + +def get_index_arr(img): + """ + Generate an index array for the given image. + + This function creates a 3D array of indices corresponding to the dimensions of the input image. + + Args: + img (ndarray): The input image array. + + Returns: + ndarray: A 3D array containing the indices for each dimension of the input image. + """ + return np.moveaxis( + np.moveaxis( + np.stack( + np.meshgrid( + np.arange(img.shape[0]), np.arange(img.shape[1]), np.arange(img.shape[2]) + ) + ), + 0, + 3, + ), + 0, + 1, + ) + + +def supress_non_largest_components(img, target_label, default_val=0): + """ + Suppress all components except the largest one(s) for specified target labels. + + This function identifies the largest component(s) for each target label and + suppresses all other smaller components. + + Args: + img (ndarray): The input image array. + target_label (list): List of label values to process. + default_val (int, optional): Value to assign to suppressed voxels. Defaults to 0. + + Returns: + tuple: A tuple containing: + - ndarray: Modified image with non-largest components suppressed. + - int: Number of voxels that were changed. + """ + index_arr = get_index_arr(img) + img_mod = copy.deepcopy(img) + new_background = np.zeros(img.shape, dtype=np.bool_) + for label in target_label: + label_cc = skimage.measure.label(img == label, connectivity=3) + uv, uc = np.unique(label_cc, return_counts=True) + dominant_vals = uv[np.argsort(uc)[::-1][:2]] + if len(dominant_vals) >= 2: # Case: no predictions + new_background = np.logical_or( + new_background, + np.logical_not( + np.logical_or(label_cc == dominant_vals[0], label_cc == dominant_vals[1]) + ), + ) + + for voxel in index_arr[new_background]: + img_mod[tuple(voxel)] = default_val + diff = np.sum((img - img_mod) > 0) + + return img_mod, diff + + +def erode_one_img( + mask_t: Tensor, filter_size: int | Sequence[int] = 3, pad_value: float = 1.0 +) -> Tensor: + """ + Erode 2D/3D binary mask with data type as torch tensor. + + Args: + mask_t: input 2D/3D binary mask, [M,N] or [M,N,P] torch tensor. + filter_size: erosion filter size, has to be odd numbers, default to be 3. + pad_value: the filled value for padding. We need to pad the input before filtering + to keep the output with the same size as input. Usually use default value + and not changed. + + Return: + Tensor: eroded mask, same shape as input. + """ + return ( + erode( + mask_t.float() + .unsqueeze(0) + .unsqueeze( + 0, + ), + filter_size, + pad_value=pad_value, + ) + .squeeze(0) + .squeeze(0) + ) + + +def dilate_one_img( + mask_t: Tensor, filter_size: int | Sequence[int] = 3, pad_value: float = 0.0 +) -> Tensor: + """ + Dilate 2D/3D binary mask with data type as torch tensor. + + Args: + mask_t: input 2D/3D binary mask, [M,N] or [M,N,P] torch tensor. + filter_size: dilation filter size, has to be odd numbers, default to be 3. + pad_value: the filled value for padding. We need to pad the input before filtering + to keep the output with the same size as input. Usually use default value + and not changed. + + Return: + Tensor: dilated mask, same shape as input. + """ + return ( + dilate( + mask_t.float() + .unsqueeze(0) + .unsqueeze( + 0, + ), + filter_size, + pad_value=pad_value, + ) + .squeeze(0) + .squeeze(0) + ) + + +def binarize_labels(x: Tensor, bits: int = 8) -> Tensor: + """ + Convert input tensor to binary representation. + + This function takes an input tensor and converts it to a binary representation + using the specified number of bits. + + Args: + x (Tensor): Input tensor with shape (B, 1, H, W, D). + bits (int, optional): Number of bits to use for binary representation. Defaults to 8. + + Returns: + Tensor: Binary representation of the input tensor with shape (B, bits, H, W, D). + """ + mask = 2 ** torch.arange(bits).to(x.device, x.dtype) + return x.unsqueeze(-1).bitwise_and(mask).ne(0).byte().squeeze(1).permute(0, 4, 1, 2, 3) + + +def setup_ddp(rank: int, world_size: int) -> torch.device: + """ + Initialize the distributed process group. + + Args: + rank (int): rank of the current process. + world_size (int): number of processes participating in the job. + + Returns: + torch.device: device of the current process. + """ + dist.init_process_group( + backend="nccl", + init_method="env://", + timeout=timedelta(seconds=36000), + rank=rank, + world_size=world_size, + ) + dist.barrier() + device = torch.device(f"cuda:{rank}") + return device + + +def define_instance(args: Namespace, instance_def_key: str) -> Any: + """ + Define and instantiate an object based on the provided arguments and instance definition key. + + This function uses a ConfigParser to parse the arguments and instantiate an object + defined by the instance_def_key. + + Args: + args: An object containing the arguments to be parsed. + instance_def_key (str): The key used to retrieve the instance definition from the parsed content. + + Returns: + The instantiated object as defined by the instance_def_key in the parsed configuration. + """ + parser = ConfigParser(vars(args)) + parser.parse(True) + return parser.get_parsed_content(instance_def_key, instantiate=True) + + +def add_data_dir2path(list_files: list, data_dir: str, fold: int = None) -> tuple[list, list]: + """ + Read a list of data dictionary. + + Args: + list_files (list): input data to load and transform to generate dataset for model. + data_dir (str): directory of files. + fold (int, optional): fold index for cross validation. Defaults to None. + + Returns: + tuple[list, list]: A tuple of two arrays (training, validation). + """ + new_list_files = copy.deepcopy(list_files) + if fold is not None: + new_list_files_train = [] + new_list_files_val = [] + for d in new_list_files: + d["image"] = os.path.join(data_dir, d["image"]) + + if "label" in d: + d["label"] = os.path.join(data_dir, d["label"]) + + if fold is not None: + if d["fold"] == fold: + new_list_files_val.append(copy.deepcopy(d)) + else: + new_list_files_train.append(copy.deepcopy(d)) + + if fold is not None: + return new_list_files_train, new_list_files_val + else: + return new_list_files, [] + + +def prepare_maisi_controlnet_json_dataloader( + json_data_list: list | str, + data_base_dir: list | str, + batch_size: int = 1, + fold: int = 0, + cache_rate: float = 0.0, + rank: int = 0, + world_size: int = 1, +) -> tuple[DataLoader, DataLoader]: + """ + Prepare dataloaders for training and validation. + + Args: + json_data_list (list | str): the name of JSON files listing the data. + data_base_dir (list | str): directory of files. + batch_size (int, optional): how many samples per batch to load . Defaults to 1. + fold (int, optional): fold index for cross validation. Defaults to 0. + cache_rate (float, optional): percentage of cached data in total. Defaults to 0.0. + rank (int, optional): rank of the current process. Defaults to 0. + world_size (int, optional): number of processes participating in the job. Defaults to 1. + + Returns: + tuple[DataLoader, DataLoader]: A tuple of two dataloaders (training, validation). + """ + use_ddp = world_size > 1 + if isinstance(json_data_list, list): + assert isinstance(data_base_dir, list) + list_train = [] + list_valid = [] + for data_list, data_root in zip(json_data_list, data_base_dir): + with open(data_list, "r") as f: + json_data = json.load(f)["training"] + train, val = add_data_dir2path(json_data, data_root, fold) + list_train += train + list_valid += val + else: + with open(json_data_list, "r") as f: + json_data = json.load(f)["training"] + list_train, list_valid = add_data_dir2path(json_data, data_base_dir, fold) + + common_transform = [ + LoadImaged(keys=["image", "label"], image_only=True, ensure_channel_first=True), + Orientationd(keys=["label"], axcodes="RAS"), + EnsureTyped(keys=["label"], dtype=torch.uint8, track_meta=True), + Lambdad( + keys="top_region_index", func=lambda x: torch.FloatTensor(x), allow_missing_keys=True + ), + Lambdad( + keys="bottom_region_index", func=lambda x: torch.FloatTensor(x), allow_missing_keys=True + ), + Lambdad(keys="spacing", func=lambda x: torch.FloatTensor(x)), + Lambdad( + keys=["top_region_index", "bottom_region_index", "spacing"], + func=lambda x: x * 1e2, + allow_missing_keys=True, + ), + ] + train_transforms, val_transforms = Compose(common_transform), Compose(common_transform) + + train_loader = None + + if use_ddp: + list_train = partition_dataset( + data=list_train, + shuffle=True, + num_partitions=world_size, + even_divisible=True, + )[rank] + train_ds = CacheDataset( + data=list_train, transform=train_transforms, cache_rate=cache_rate, num_workers=8 + ) + train_loader = DataLoader( + train_ds, batch_size=batch_size, shuffle=True, num_workers=8, pin_memory=True + ) + if use_ddp: + list_valid = partition_dataset( + data=list_valid, + shuffle=True, + num_partitions=world_size, + even_divisible=False, + )[rank] + val_ds = CacheDataset( + data=list_valid, + transform=val_transforms, + cache_rate=cache_rate, + num_workers=8, + ) + val_loader = DataLoader( + val_ds, batch_size=batch_size, shuffle=False, num_workers=2, pin_memory=False + ) + return train_loader, val_loader + + +def prepare_maisi_controlnet_infer_dataloader( + json_data_list: list | str, + data_base_dir: list | str, + batch_size: int = 1, + cache_rate: float = 0.0, + rank: int = 0, + world_size: int = 1, +) -> DataLoader: + """ + Prepare dataloader for inference (test set). + + Args: + json_data_list (list | str): the name of JSON files listing the data. + data_base_dir (list | str): directory of files. + batch_size (int, optional): how many samples per batch to load. Defaults to 1. + cache_rate (float, optional): percentage of cached data in total. Defaults to 0.0. + rank (int, optional): rank of the current process. Defaults to 0. + world_size (int, optional): number of processes participating in the job. Defaults to 1. + + Returns: + DataLoader: Dataloader for inference. + """ + use_ddp = world_size > 1 + if isinstance(json_data_list, list): + assert isinstance(data_base_dir, list) + list_infer = [] + for data_list, data_root in zip(json_data_list, data_base_dir): + with open(data_list, "r") as f: + # Use "testing" key for test set + json_data = json.load(f)["testing"] + infer, _ = add_data_dir2path(json_data, data_root, fold=None) + list_infer += infer + else: + with open(json_data_list, "r") as f: + json_data = json.load(f)["testing"] + list_infer, _ = add_data_dir2path(json_data, data_base_dir, fold=None) + + common_transform = [ + LoadImaged(keys=["image", "label"], image_only=True, ensure_channel_first=True), + Orientationd(keys=["label"], axcodes="RAS"), + EnsureTyped(keys=["label"], dtype=torch.uint8, track_meta=True), + Lambdad( + keys="top_region_index", func=lambda x: torch.FloatTensor(x), allow_missing_keys=True + ), + Lambdad( + keys="bottom_region_index", func=lambda x: torch.FloatTensor(x), allow_missing_keys=True + ), + Lambdad(keys="spacing", func=lambda x: torch.FloatTensor(x)), + Lambdad( + keys=["top_region_index", "bottom_region_index", "spacing"], + func=lambda x: x * 1e2, + allow_missing_keys=True, + ), + ] + infer_transforms = Compose(common_transform) + + if use_ddp: + list_infer = partition_dataset( + data=list_infer, + shuffle=False, + num_partitions=world_size, + even_divisible=False, + )[rank] + infer_ds = CacheDataset( + data=list_infer, transform=infer_transforms, cache_rate=cache_rate, num_workers=8 + ) + infer_loader = DataLoader( + infer_ds, batch_size=batch_size, shuffle=False, num_workers=2, pin_memory=False + ) + return infer_loader + + +def add_data_dir2path_test(list_files: list, data_dir: str, fold: int = None) -> tuple[list, list]: + """ + Read a list of data dictionary. + + Args: + list_files (list): input data to load and transform to generate dataset for model. + data_dir (str): directory of files. + fold (int, optional): fold index for cross validation. Defaults to None. + + Returns: + tuple[list, list]: A tuple of two arrays (training, validation). + """ + new_list_files = copy.deepcopy(list_files) + if fold is not None: + new_list_files_train = [] + new_list_files_val = [] + for d in new_list_files: + d["label"] = os.path.join(data_dir, d["label"]) + + if fold is not None: + if d["fold"] == fold: + new_list_files_val.append(copy.deepcopy(d)) + else: + new_list_files_train.append(copy.deepcopy(d)) + + if fold is not None: + return new_list_files_train, new_list_files_val + else: + return new_list_files, [] + + +def prepare_maisi_controlnet_test_dataloader( + json_data_list: list | str, + data_base_dir: list | str, + batch_size: int = 1, + cache_rate: float = 0.0, + rank: int = 0, + world_size: int = 1, +) -> DataLoader: + """ + Prepare dataloader for inference (test set). + + Args: + json_data_list (list | str): the name of JSON files listing the data. + data_base_dir (list | str): directory of files. + batch_size (int, optional): how many samples per batch to load. Defaults to 1. + cache_rate (float, optional): percentage of cached data in total. Defaults to 0.0. + rank (int, optional): rank of the current process. Defaults to 0. + world_size (int, optional): number of processes participating in the job. Defaults to 1. + + Returns: + DataLoader: Dataloader for inference. + """ + use_ddp = world_size > 1 + if isinstance(json_data_list, list): + assert isinstance(data_base_dir, list) + list_infer = [] + for data_list, data_root in zip(json_data_list, data_base_dir): + with open(data_list, "r") as f: + # Use "testing" key for test set + json_data = json.load(f)["testing"] + infer, _ = add_data_dir2path_test(json_data, data_root, fold=None) + list_infer += infer + else: + with open(json_data_list, "r") as f: + json_data = json.load(f)["testing"] + list_infer, _ = add_data_dir2path_test(json_data, data_base_dir, fold=None) + + common_transform = [ + LoadImaged(keys=["label"], image_only=True, ensure_channel_first=True), + Orientationd(keys=["label"], axcodes="RAS"), + EnsureTyped(keys=["label"], dtype=torch.uint8, track_meta=True), + Lambdad( + keys="top_region_index", func=lambda x: torch.FloatTensor(x), allow_missing_keys=True + ), + Lambdad( + keys="bottom_region_index", func=lambda x: torch.FloatTensor(x), allow_missing_keys=True + ), + Lambdad(keys="spacing", func=lambda x: torch.FloatTensor(x)), + Lambdad( + keys=["top_region_index", "bottom_region_index", "spacing"], + func=lambda x: x * 1e2, + allow_missing_keys=True, + ), + ] + infer_transforms = Compose(common_transform) + + if use_ddp: + list_infer = partition_dataset( + data=list_infer, + shuffle=False, + num_partitions=world_size, + even_divisible=False, + )[rank] + infer_ds = CacheDataset( + data=list_infer, transform=infer_transforms, cache_rate=cache_rate, num_workers=8 + ) + infer_loader = DataLoader( + infer_ds, batch_size=batch_size, shuffle=False, num_workers=2, pin_memory=False + ) + return infer_loader + + +def organ_fill_by_closing(data, target_label, device, close_times=2, filter_size=3, pad_value=0.0): + """ + Fill holes in an organ mask using morphological closing operations. + + This function performs a series of dilation and erosion operations to fill holes + in the organ mask identified by the target label. + + Args: + data (ndarray): The input data containing organ labels. + target_label (int): The label of the organ to be processed. + device (str): The device to perform the operations on (e.g., 'cuda:0'). + close_times (int, optional): Number of times to perform the closing operation. Defaults to 2. + filter_size (int, optional): Size of the filter for dilation and erosion. Defaults to 3. + pad_value (float, optional): Value used for padding in dilation and erosion. Defaults to 0.0. + + Returns: + ndarray: Boolean mask of the filled organ. + """ + mask = (data == target_label).astype(np.uint8) + mask = torch.from_numpy(mask).to(device) + for _ in range(close_times): + mask = dilate_one_img(mask, filter_size=filter_size, pad_value=pad_value) + mask = erode_one_img(mask, filter_size=filter_size, pad_value=pad_value) + return mask.cpu().numpy().astype(np.bool_) + + +def organ_fill_by_removed_mask(data, target_label, remove_mask, device): + """ + Fill an organ mask in regions where it was previously removed. + + Args: + data (ndarray): The input data containing organ labels. + target_label (int): The label of the organ to be processed. + remove_mask (ndarray): Boolean mask indicating regions where the organ was removed. + device (str): The device to perform the operations on (e.g., 'cuda:0'). + + Returns: + ndarray: Boolean mask of the filled organ in previously removed regions. + """ + mask = (data == target_label).astype(np.uint8) + mask = dilate_one_img(torch.from_numpy(mask).to(device), filter_size=3, pad_value=0.0) + mask = dilate_one_img(mask, filter_size=3, pad_value=0.0) + roi_oragn_mask = dilate_one_img(mask, filter_size=3, pad_value=0.0).cpu().numpy() + return (roi_oragn_mask * remove_mask).astype(np.bool_) + + +def get_body_region_index_from_mask(input_mask): + """ + Determine the top and bottom body region indices from an input mask. + + Args: + input_mask (Tensor): Input mask tensor containing body region labels. + + Returns: + tuple: Two lists representing the top and bottom region indices. + """ + region_indices = {} + # head and neck + region_indices["region_0"] = [22, 120] + # thorax + region_indices["region_1"] = [28, 29, 30, 31, 32] + # abdomen + region_indices["region_2"] = [1, 2, 3, 4, 5, 14] + # pelvis and lower + region_indices["region_3"] = [93, 94] + + nda = input_mask.cpu().numpy().squeeze() + unique_elements = np.lib.arraysetops.unique(nda) + unique_elements = list(unique_elements) + # print(f"nda: {nda.shape} {unique_elements}.") + overlap_array = np.zeros(len(region_indices), dtype=np.uint8) + for _j in range(len(region_indices)): + overlap = any(element in region_indices[f"region_{_j}"] for element in unique_elements) + overlap_array[_j] = np.uint8(overlap) + overlap_array_indices = np.nonzero(overlap_array)[0] + top_region_index = np.eye(len(region_indices), dtype=np.uint8)[ + np.amin(overlap_array_indices), ... + ] + top_region_index = list(top_region_index) + top_region_index = [int(_k) for _k in top_region_index] + bottom_region_index = np.eye(len(region_indices), dtype=np.uint8)[ + np.amax(overlap_array_indices), ... + ] + bottom_region_index = list(bottom_region_index) + bottom_region_index = [int(_k) for _k in bottom_region_index] + # print(f"{top_region_index} {bottom_region_index}") + return top_region_index, bottom_region_index + + +def general_mask_generation_post_process(volume_t, target_tumor_label=None, device="cuda:0"): + """ + Perform post-processing on a generated mask volume. + + This function applies various refinement steps to improve the quality of the generated mask, + including body mask refinement, tumor prediction refinement, and organ-specific processing. + + Args: + volume_t (ndarray): Input volume containing organ and tumor labels. + target_tumor_label (int, optional): Label of the target tumor. Defaults to None. + device (str, optional): Device to perform operations on. Defaults to "cuda:0". + + Returns: + ndarray: Post-processed volume with refined organ and tumor labels. + """ + # assume volume_t is np array with shape (H,W,D) + hepatic_vessel = volume_t == 25 + airway = volume_t == 132 + + # ------------ refine body mask pred + body_region_mask = ( + erode_one_img(torch.from_numpy((volume_t > 0)).to(device), filter_size=3, pad_value=0.0) + .cpu() + .numpy() + ) + body_region_mask, _ = supress_non_largest_components(body_region_mask, [1]) + body_region_mask = ( + dilate_one_img(torch.from_numpy(body_region_mask).to(device), filter_size=3, pad_value=0.0) + .cpu() + .numpy() + .astype(np.uint8) + ) + volume_t = volume_t * body_region_mask + + # ------------ refine tumor pred + tumor_organ_dict = {23: 28, 24: 4, 26: 1, 27: 62, 128: 200} + for t in [23, 24, 26, 27, 128]: + if t != target_tumor_label: + volume_t[volume_t == t] = tumor_organ_dict[t] + else: + volume_t[organ_fill_by_closing(volume_t, target_label=t, device=device)] = t + volume_t[organ_fill_by_closing(volume_t, target_label=t, device=device)] = t + # we only keep the largest connected componet for tumors except hepatic tumor and bone lesion + if target_tumor_label != 26 and target_tumor_label != 128: + volume_t, _ = supress_non_largest_components( + volume_t, [target_tumor_label], default_val=200 + ) + target_tumor = volume_t == target_tumor_label + + # ------------ remove undesired organ pred + # general post-process non-largest components suppression + # process 4 ROI organs + spleen + 2 kidney + 5 lung lobes + duodenum + inferior vena cava + oran_list = [1, 4, 10, 12, 3, 28, 29, 30, 31, 32, 5, 14, 13, 6, 7, 8, 9, 10] + if target_tumor_label != 128: + oran_list += list(range(33, 60)) # + list(range(63,87)) + data, _ = supress_non_largest_components( + volume_t, oran_list, default_val=200 + ) # 200 is body region + organ_remove_mask = (volume_t - data).astype(np.bool_) + # process intestinal system (stomach 12, duodenum 13, small bowel 19, colon 62) + intestinal_mask_ = ( + (data == 12).astype(np.uint8) + + (data == 13).astype(np.uint8) + + (data == 19).astype(np.uint8) + + (data == 62).astype(np.uint8) + ) + intestinal_mask, _ = supress_non_largest_components(intestinal_mask_, [1], default_val=0) + # process small bowel 19 + small_bowel_remove_mask = (data == 19).astype(np.uint8) - (data == 19).astype( + np.uint8 + ) * intestinal_mask + # process colon 62 + colon_remove_mask = (data == 62).astype(np.uint8) - (data == 62).astype( + np.uint8 + ) * intestinal_mask + intestinal_remove_mask = (small_bowel_remove_mask + colon_remove_mask).astype(np.bool_) + data[intestinal_remove_mask] = 200 + + # ------------ full correponding organ in removed regions + for organ_label in oran_list: + data[organ_fill_by_closing(data, target_label=organ_label, device=device)] = organ_label + + if target_tumor_label == 23 and np.sum(target_tumor) > 0: + # speical process for cases with lung tumor + dia_lung_tumor_mask = ( + dilate_one_img(torch.from_numpy((data == 23)).to(device), filter_size=3, pad_value=0.0) + .cpu() + .numpy() + ) + tmp = ( + (data * (dia_lung_tumor_mask.astype(np.uint8) - (data == 23).astype(np.uint8))) + .astype(np.float32) + .flatten() + ) + tmp[tmp == 0] = float("nan") + mode = int(stats.mode(tmp.flatten(), nan_policy="omit")[0]) + if mode in [28, 29, 30, 31, 32]: + dia_lung_tumor_mask = ( + dilate_one_img( + torch.from_numpy(dia_lung_tumor_mask).to(device), filter_size=3, pad_value=0.0 + ) + .cpu() + .numpy() + ) + lung_remove_mask = dia_lung_tumor_mask.astype(np.uint8) - (data == 23).astype( + np.uint8 + ).astype(np.uint8) + data[ + organ_fill_by_removed_mask( + data, target_label=mode, remove_mask=lung_remove_mask, device=device + ) + ] = mode + dia_lung_tumor_mask = ( + dilate_one_img( + torch.from_numpy(dia_lung_tumor_mask).to(device), filter_size=3, pad_value=0.0 + ) + .cpu() + .numpy() + ) + data[ + organ_fill_by_removed_mask( + data, + target_label=23, + remove_mask=dia_lung_tumor_mask * organ_remove_mask, + device=device, + ) + ] = 23 + for organ_label in [28, 29, 30, 31, 32]: + data[organ_fill_by_closing(data, target_label=organ_label, device=device)] = organ_label + data[organ_fill_by_closing(data, target_label=organ_label, device=device)] = organ_label + data[organ_fill_by_closing(data, target_label=organ_label, device=device)] = organ_label + + if target_tumor_label == 26 and np.sum(target_tumor) > 0: + # speical process for cases with hepatic tumor + # process liver 1 + data[ + organ_fill_by_removed_mask( + data, target_label=1, remove_mask=intestinal_remove_mask, device=device + ) + ] = 1 + data[ + organ_fill_by_removed_mask( + data, target_label=1, remove_mask=intestinal_remove_mask, device=device + ) + ] = 1 + # process spleen 2 + data[ + organ_fill_by_removed_mask( + data, target_label=3, remove_mask=organ_remove_mask, device=device + ) + ] = 3 + data[ + organ_fill_by_removed_mask( + data, target_label=3, remove_mask=organ_remove_mask, device=device + ) + ] = 3 + dia_tumor_mask = ( + dilate_one_img( + torch.from_numpy((data == target_tumor_label)).to(device), + filter_size=3, + pad_value=0.0, + ) + .cpu() + .numpy() + ) + dia_tumor_mask = ( + dilate_one_img( + torch.from_numpy(dia_tumor_mask).to(device), filter_size=3, pad_value=0.0 + ) + .cpu() + .numpy() + ) + data[ + organ_fill_by_removed_mask( + data, + target_label=target_tumor_label, + remove_mask=dia_tumor_mask * organ_remove_mask, + device=device, + ) + ] = target_tumor_label + # refine hepatic tumor + hepatic_tumor_vessel_liver_mask_ = ( + (data == 26).astype(np.uint8) + + (data == 25).astype(np.uint8) + + (data == 1).astype(np.uint8) + ) + hepatic_tumor_vessel_liver_mask_ = (hepatic_tumor_vessel_liver_mask_ > 1).astype(np.uint8) + hepatic_tumor_vessel_liver_mask, _ = supress_non_largest_components( + hepatic_tumor_vessel_liver_mask_, [1], default_val=0 + ) + removed_region = ( + hepatic_tumor_vessel_liver_mask_ - hepatic_tumor_vessel_liver_mask + ).astype(np.bool_) + data[removed_region] = 200 + target_tumor = (target_tumor * hepatic_tumor_vessel_liver_mask).astype(np.bool_) + # refine liver + data[organ_fill_by_closing(data, target_label=1, device=device)] = 1 + data[organ_fill_by_closing(data, target_label=1, device=device)] = 1 + data[organ_fill_by_closing(data, target_label=1, device=device)] = 1 + + if target_tumor_label == 27 and np.sum(target_tumor) > 0: + # speical process for cases with colon tumor + dia_tumor_mask = ( + dilate_one_img( + torch.from_numpy((data == target_tumor_label)).to(device), + filter_size=3, + pad_value=0.0, + ) + .cpu() + .numpy() + ) + dia_tumor_mask = ( + dilate_one_img( + torch.from_numpy(dia_tumor_mask).to(device), filter_size=3, pad_value=0.0 + ) + .cpu() + .numpy() + ) + data[ + organ_fill_by_removed_mask( + data, + target_label=target_tumor_label, + remove_mask=dia_tumor_mask * organ_remove_mask, + device=device, + ) + ] = target_tumor_label + + if target_tumor_label == 129 and np.sum(target_tumor) > 0: + # speical process for cases with kidney tumor + for organ_label in [5, 14]: + data[organ_fill_by_closing(data, target_label=organ_label, device=device)] = organ_label + data[organ_fill_by_closing(data, target_label=organ_label, device=device)] = organ_label + data[organ_fill_by_closing(data, target_label=organ_label, device=device)] = organ_label + # TODO: current model does not support hepatic vessel by size control. + # we treat it as liver for better visiaulization + print( + "Current model does not support hepatic vessel by size control, " + "so we treat generated hepatic vessel as part of liver for better visiaulization." + ) + data[hepatic_vessel] = 1 + data[airway] = 132 + if target_tumor_label is not None: + data[target_tumor] = target_tumor_label + + return data + + +class MapLabelValue: + """ + Utility to map label values to another set of values. + For example, map [3, 2, 1] to [0, 1, 2], [1, 2, 3] -> [0.5, 1.5, 2.5], ["label3", "label2", "label1"] -> [0, 1, 2], + [3.5, 2.5, 1.5] -> ["label0", "label1", "label2"], etc. + The label data must be numpy array or array-like data and the output data will be numpy array. + + """ + + backend = [TransformBackends.NUMPY, TransformBackends.TORCH] + + def __init__( + self, orig_labels: Sequence, target_labels: Sequence, dtype: DtypeLike = np.float32 + ) -> None: + """ + Args: + orig_labels: original labels that map to others. + target_labels: expected label values, 1: 1 map to the `orig_labels`. + dtype: convert the output data to dtype, default to float32. + if dtype is from PyTorch, the transform will use the pytorch backend, else with numpy backend. + + """ + if len(orig_labels) != len(target_labels): + raise ValueError("orig_labels and target_labels must have the same length.") + + self.orig_labels = orig_labels + self.target_labels = target_labels + self.pair = tuple((o, t) for o, t in zip(self.orig_labels, self.target_labels) if o != t) + type_dtype = type(dtype) + if getattr(type_dtype, "__module__", "") == "torch": + self.use_numpy = False + self.dtype = get_equivalent_dtype(dtype, data_type=torch.Tensor) + else: + self.use_numpy = True + self.dtype = get_equivalent_dtype(dtype, data_type=np.ndarray) + + def __call__(self, img: NdarrayOrTensor): + """ + Apply the label mapping to the input image. + + Args: + img (NdarrayOrTensor): Input image to be remapped. + + Returns: + NdarrayOrTensor: Remapped image. + """ + if self.use_numpy: + img_np, *_ = convert_data_type(img, np.ndarray) + _out_shape = img_np.shape + img_flat = img_np.flatten() + try: + out_flat = img_flat.astype(self.dtype) + except ValueError: + # can't copy unchanged labels as the expected dtype is not supported, must map all the label values + out_flat = np.zeros(shape=img_flat.shape, dtype=self.dtype) + for o, t in self.pair: + out_flat[img_flat == o] = t + out_t = out_flat.reshape(_out_shape) + else: + img_t, *_ = convert_data_type(img, torch.Tensor) + out_t = img_t.detach().clone().to(self.dtype) # type: ignore + for o, t in self.pair: + out_t[img_t == o] = t + out, *_ = convert_to_dst_type(src=out_t, dst=img, dtype=self.dtype) + return out + + +def KL_loss(z_mu, z_sigma): + """ + Compute the Kullback-Leibler (KL) divergence loss for a variational autoencoder (VAE). + + The KL divergence measures how one probability distribution diverges from a second, expected probability distribution. + In the context of VAEs, this loss term ensures that the learned latent space distribution is close to a standard normal distribution. + + Args: + z_mu (torch.Tensor): Mean of the latent variable distribution, shape [N,C,H,W,D] or [N,C,H,W]. + z_sigma (torch.Tensor): Standard deviation of the latent variable distribution, same shape as 'z_mu'. + + Returns: + torch.Tensor: The computed KL divergence loss, averaged over the batch. + """ + eps = 1e-10 + kl_loss = 0.5 * torch.sum( + z_mu.pow(2) + z_sigma.pow(2) - torch.log(z_sigma.pow(2) + eps) - 1, + dim=list(range(1, len(z_sigma.shape))), + ) + return torch.sum(kl_loss) / kl_loss.shape[0] + + +def dynamic_infer(inferer, model, images): + """ + Perform dynamic inference using a model and an inferer, typically a monai SlidingWindowInferer. + + This function determines whether to use the model directly or to use the provided inferer + (such as a sliding window inferer) based on the size of the input images. + + Args: + inferer: An inference object, typically a monai SlidingWindowInferer, which handles patch-based inference. + model (torch.nn.Module): The model used for inference. + images (torch.Tensor): The input images for inference, shape [N,C,H,W,D] or [N,C,H,W]. + + Returns: + torch.Tensor: The output from the model or the inferer, depending on the input size. + """ + if torch.numel(images[0:1, 0:1, ...]) <= math.prod(inferer.roi_size): + return model(images) + else: + # Extract the spatial dimensions from the images tensor (H, W, D) + spatial_dims = images.shape[2:] + orig_roi = inferer.roi_size + + # Check that roi has the same number of dimensions as spatial_dims + if len(orig_roi) != len(spatial_dims): + raise ValueError( + f"ROI length ({len(orig_roi)}) does not match spatial dimensions ({len(spatial_dims)})." + ) + + # Iterate and adjust each ROI dimension + adjusted_roi = [min(roi_dim, img_dim) for roi_dim, img_dim in zip(orig_roi, spatial_dims)] + inferer.roi_size = adjusted_roi + output = inferer(network=model, inputs=images) + inferer.roi_size = orig_roi + return output diff --git a/itrialspace/src/itrialspace/synthesis/scripts/utils_plot.py b/itrialspace/src/itrialspace/synthesis/scripts/utils_plot.py new file mode 100644 index 0000000000000000000000000000000000000000..7cd8a0ca79be57ebbbcacad8c507296881e7215b --- /dev/null +++ b/itrialspace/src/itrialspace/synthesis/scripts/utils_plot.py @@ -0,0 +1,199 @@ +# Copyright (c) MONAI Consortium +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# http://www.apache.org/licenses/LICENSE-2.0 +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and + + +import matplotlib.pyplot as plt +import numpy as np +import torch +import torch.nn.functional as F +from monai.transforms import AsDiscrete + + +def find_label_center_loc(x): + """ + Find the center location of non-zero elements in a binary mask. + + Args: + x (torch.Tensor): Binary mask tensor. Expected shape: [H, W, D] or [C, H, W, D]. + + Returns: + list: Center locations for each dimension. Each element is either + the middle index of non-zero locations or None if no non-zero elements exist. + """ + label_loc = torch.where(x != 0) + center_loc = [] + for loc in label_loc: + unique_loc = torch.unique(loc) + if len(unique_loc) == 0: + center_loc.append(None) + else: + center_loc.append(unique_loc[len(unique_loc) // 2]) + + return center_loc + + +def normalize_label_to_uint8(colorize, label, n_label): + """ + Normalize and colorize a label tensor to a uint8 image. + + Args: + colorize (torch.Tensor): Weight tensor for colorization. Expected shape: [3, n_label, 1, 1]. + label (torch.Tensor): Input label tensor. Expected shape: [1, H, W]. + n_label (int): Number of unique labels. + + Returns: + numpy.ndarray: Normalized and colorized image as uint8 numpy array. Shape: [H, W, 3]. + """ + with torch.no_grad(): + post_label = AsDiscrete(to_onehot=n_label) + label = post_label(label).permute(1, 0, 2, 3) + label = F.conv2d(label, weight=colorize) + label = torch.clip(label, 0, 1).squeeze().permute(1, 2, 0).cpu().numpy() + + draw_img = (label * 255).astype(np.uint8) + + return draw_img + + +def visualize_one_slice_in_3d( + image, axis: int = 2, center=None, mask_bool=True, n_label=105, colorize=None +): + """ + Extract and visualize a 2D slice from a 3D image or label tensor. + + Args: + image (torch.Tensor): Input 3D image or label tensor. Expected shape: [1, H, W, D]. + axis (int, optional): Axis along which to extract the slice (0, 1, or 2). Defaults to 2. + center (int, optional): Index of the slice to extract. If None, the middle slice is used. + mask_bool (bool, optional): If True, treat the input as a label mask and normalize it. Defaults to True. + n_label (int, optional): Number of labels in the mask. Used only if mask_bool is True. Defaults to 105. + colorize (torch.Tensor, optional): Colorization weights for label normalization. + Expected shape: [3, n_label, 1, 1] if provided. + + Returns: + numpy.ndarray: 2D slice of the input. If mask_bool is True, returns a normalized uint8 array + with shape [3, H, W]. Otherwise, returns a float32 array with shape [3, H, W]. + + Raises: + ValueError: If the specified axis is not 0, 1, or 2. + """ + # draw image + if center is None: + center = image.shape[2:][axis] // 2 + if axis == 0: + draw_img = image[..., center, :, :] + elif axis == 1: + draw_img = image[..., :, center, :] + elif axis == 2: + draw_img = image[..., :, :, center] + else: + raise ValueError("axis should be in [0,1,2]") + if mask_bool: + draw_img = normalize_label_to_uint8(colorize, draw_img, n_label) + else: + draw_img = draw_img.squeeze().cpu().numpy().astype(np.float32) + draw_img = np.stack((draw_img,) * 3, axis=-1) + return draw_img + + +def show_image(image, title="mask"): + """ + Plot and display an input image. + + Args: + image (numpy.ndarray): Image to be displayed. Expected shape: [H, W] for grayscale or [H, W, 3] for RGB. + title (str, optional): Title for the plot. Defaults to "mask". + """ + plt.figure("check", (24, 12)) + plt.subplot(1, 2, 1) + plt.title(title) + plt.imshow(image) + plt.show() + + +def to_shape(a, shape): + """ + Pad an image to a desired shape. + + This function pads a 3D numpy array (image) with zeros to reach the specified shape. + The padding is added equally on both sides of each dimension, with any odd padding + added to the end. + + Args: + a (numpy.ndarray): Input 3D array to be padded. Expected shape: [X, Y, Z]. + shape (tuple): Desired output shape as (x_, y_, z_). + + Returns: + numpy.ndarray: Padded array with the desired shape [x_, y_, z_]. + + Note: + If the input shape is larger than the desired shape in any dimension, + no padding is removed; the original size is maintained for that dimension. + Padding is done using numpy's pad function with 'constant' mode (zero-padding). + """ + x_, y_, z_ = shape + x, y, z = a.shape + x_pad = x_ - x + y_pad = y_ - y + z_pad = z_ - z + return np.pad( + a, + ( + (x_pad // 2, x_pad // 2 + x_pad % 2), + (y_pad // 2, y_pad // 2 + y_pad % 2), + (z_pad // 2, z_pad // 2 + z_pad % 2), + ), + mode="constant", + ) + + +def get_xyz_plot( + image, center_loc_axis, mask_bool=True, n_label=105, colorize=None, target_class_index=0 +): + """ + Generate a concatenated XYZ plot of 2D slices from a 3D image. + + This function creates visualizations of three orthogonal slices (XY, XZ, YZ) from a 3D image + and concatenates them into a single 2D image. + + Args: + image (torch.Tensor): Input 3D image tensor. Expected shape: [1, H, W, D]. + center_loc_axis (list): List of three integers specifying the center locations for each axis. + mask_bool (bool, optional): Whether to apply masking. Defaults to True. + n_label (int, optional): Number of labels for visualization. Defaults to 105. + colorize (torch.Tensor, optional): Colorization weights. Expected shape: [3, n_label, 1, 1] if provided. + target_class_index (int, optional): Index of the target class. Defaults to 0. + + Returns: + numpy.ndarray: Concatenated 2D image of the three orthogonal slices. Shape: [max(H,W,D), 3*max(H,W,D), 3]. + + Note: + The output image is padded to ensure all slices have the same dimensions. + """ + target_shape = list(image.shape[1:]) # [1,H,W,D] + img_list = [] + + for axis in range(3): + center = center_loc_axis[axis] + + img = visualize_one_slice_in_3d( + torch.flip(image.unsqueeze(0), [-3, -2, -1]), + axis, + center=center, + mask_bool=mask_bool, + n_label=n_label, + colorize=colorize, + ) + img = img.transpose([2, 1, 0]) + + img = to_shape(img, (3, max(target_shape), max(target_shape))) + img_list.append(img) + img = np.concatenate(img_list, axis=2).transpose([1, 2, 0]) + return img diff --git a/itrialspace/src/itrialspace/synthesis/tools/INTEGRATION_PLAN.md b/itrialspace/src/itrialspace/synthesis/tools/INTEGRATION_PLAN.md new file mode 100644 index 0000000000000000000000000000000000000000..1742e96162f4373b9365af0108a64876a15a73d5 --- /dev/null +++ b/itrialspace/src/itrialspace/synthesis/tools/INTEGRATION_PLAN.md @@ -0,0 +1,337 @@ +# iTrialSpace -> NodMAISI Integration Pipeline +## Technical Design & Implementation Plan + +> **Historical design note.** This is the original integration design document. Some +> component names, paths, and environment recipes (e.g. `module load miniconda`, +> `monai-auto3dseg`) predate the public-release monorepo layout. For the authoritative +> package layout, install, and run instructions see the top-level `docs/` — +> `docs/architecture.md`, `docs/installation.md`, and `docs/running_the_pipeline.md`. + +--- + +## 1. Integration Architecture (High-Level) + +``` +iTrialSpace Manifest Mask Insertion Engine NodMAISI ++------------------+ +---------------------------+ +------------------+ +| CohortManifest |--->| insert_manifest() |--->| Combined masks | +| (CSV, 9 modes) | | - placement | | (label 23 = | +| | | - resample | | nodule, uint8) | ++------------------+ | - label stamping (23) | +--------+---------+ + +---------------------------+ | + v + +---------------------------+ +------------------+ + | run_itrialspace_to_ct.py |<---| audit.json | + | | +------------------+ + | Per case: | + | 1. Load mask | + | 2. Canonicalize RAS+ | + | 3. Resize to valid dims | + | 4. Write dataset JSON | + | 5. Run NodMAISI infer | + | 6. Sanity checks | + | 7. QC PNGs | + | 8. Write audit | + +------------+--------------+ + | + v + +---------------------------+ + | generated_cts/ | + | mode1_.../ | + | case_0000/ | + | synthetic_ct.nii.gz | + | input_mask.nii.gz | + | host_ct.nii.gz -> | + | nodmaisi_audit.json | + | qc/ | + | qc_slice_*.png | + | case_0001/ | + | ... | + | pipeline_summary.json | + +---------------------------+ +``` + +### Data Flow + +| Stage | Input | Output | Tool | +|-------|-------|--------|------| +| 1. Manifest planning | Raw datasets, profiles | CohortManifest CSV | iTrialSpace | +| 2. Mask insertion | Manifest + host organ segs + donor masks | Combined masks (label 23) + audit.json | itrialspace_mask_inserter | +| 3. CT synthesis | Combined masks + audit.json | Synthetic CTs + QC | run_itrialspace_to_ct.py + NodMAISI | + +--- + +## 2. NodMAISI Input Requirements (Determined from Code Analysis) + +### 2.1 What NodMAISI Expects + +The ControlNet inference script (`infer_testV2_controlnet.py`) requires: + +1. **A dataset JSON** with structure: + ```json + {"testing": [{"label": "mask.nii.gz", "dim": [512,512,256], "spacing": [0.7,0.7,1.25]}]} + ``` + +2. **A segmentation label mask** (NIfTI, uint8) — this is the ControlNet conditioning input. + - Loaded via MONAI `LoadImaged`, oriented to RAS via `Orientationd(axcodes="RAS")` + - Converted to 8-channel binary via `binarize_labels()` (bitwise decomposition) + - The 8-bit binary representation is fed as `controlnet_cond` (shape: `[B, 8, H, W, D]`) + +3. **Label 23 = lung nodule/tumor** — this is the same label used by iTrialSpace! No remapping needed. + +4. **Spacing** is multiplied by 100 before being fed to the diffusion U-Net as a conditioning tensor. + +5. **Modality** = 1 (CT) as an integer class embedding. + +### 2.2 Size Constraints (from `check_input()`) + +- `dim[0] == dim[1]` (square axial slices), must be in `{256, 384, 512}` +- `dim[2]` must be in `{128, 256, 384, 512, 640, 768}` +- `spacing[0] == spacing[1]` (isotropic in-plane) +- The latent shape is `(4, dim[0]//4, dim[1]//4, dim[2]//4)` — all dims must be divisible by 4 + +### 2.3 Output Format + +- Synthetic CT in HU range `[-1000, 1000]` +- Background (where mask == 0) is set to -1000 HU +- Saved as NIfTI via MONAI `SaveImage` with `_image` postfix + +--- + +## 3. Geometry/Orientation Handling + +### 3.1 Preprocessing (mask -> NodMAISI input) + +The driver script `run_itrialspace_to_ct.py` performs: + +1. **Load mask** via nibabel +2. **Canonicalize to RAS+** via `nib.as_closest_canonical()` +3. **Snap dimensions** to nearest valid NodMAISI size: + - XY: nearest of {256, 384, 512} + - Z: nearest of {128, 256, 384, 512, 640, 768} +4. **Resize if needed** using `scipy.ndimage.zoom(order=0)` (nearest-neighbor for labels) +5. **Adjust spacing** proportionally: `new_spacing = old_spacing * old_dim / new_dim` +6. **Write** resized mask as uint8 NIfTI with diagonal affine + +### 3.2 Post-inference Geometry Check + +After NodMAISI inference: +- Verify synthetic CT shape matches the input mask shape +- Verify spacing consistency +- Check for NaN values +- Verify HU range is within [-1000, 1000] +- All recorded in per-case audit JSON + +### 3.3 No Back-Resampling Needed + +NodMAISI outputs in the same grid as the input mask. If the mask was resized, the synthetic CT is at the resized resolution. The original dimensions are recorded in the audit for downstream consumers that may need to resample back. + +--- + +## 4. Output Directory Structure + +``` +generated_cts/ +└── mode1_controlled_prevalence/ + ├── case_0000/ + │ ├── synthetic_ct.nii.gz # Generated CT [-1000, 1000] HU + │ ├── input_mask.nii.gz # Prepared mask (RAS+, resized) + │ ├── host_ct.nii.gz # Symlink to original host CT + │ ├── nodmaisi_audit.json # Per-case audit (params, timing, checks) + │ ├── dataset.json # NodMAISI dataset JSON (intermediate) + │ ├── _tmp_env.json # NodMAISI env config (intermediate) + │ └── qc/ + │ ├── qc_slice_00_z0118.png # Axial slice through nodule + │ ├── qc_slice_01_z0125.png + │ └── qc_slice_02_z0132.png + ├── case_0001/ + │ └── ... + └── pipeline_summary.json # Global run summary +``` + +--- + +## 5. File Naming Conventions + +| File | Convention | Source | +|------|-----------|--------| +| Case directory | `case_{case_id:04d}` | iTrialSpace case_id, zero-padded | +| Synthetic CT | `synthetic_ct.nii.gz` | Fixed name in config | +| Input mask | `input_mask.nii.gz` | Preprocessed copy of inserted mask | +| Host CT link | `host_ct.nii.gz` | Symlink to original | +| QC slices | `qc_slice_{idx:02d}_z{slice:04d}.png` | Axial slice index | +| Per-case audit | `nodmaisi_audit.json` | Fixed name in config | + +--- + +## 6. QC Outputs + +For each case, when QC is enabled: + +### PNG Montages +- 3 axial slices (configurable) through the nodule region +- Each PNG shows side-by-side panels: + - **Host CT** (if available) at the same slice + - **Synthetic CT + Mask overlay** (nodule label 23 in red) + - **Synthetic CT** alone +- Window: center=-600, width=1500 (lung window) + +### Audit JSON (per-case) +```json +{ + "case_id": "0042", + "status": "success", + "timestamp": "2026-03-06T14:32:15", + "input_mask_path": "/scratch/.../inserted_masks/.../mask.nii.gz", + "synthetic_ct_path": "/scratch/.../generated_cts/.../synthetic_ct.nii.gz", + "geometry": { + "original_dim": [412, 412, 262], + "original_spacing": [0.703, 0.703, 1.25], + "nodmaisi_dim": [384, 384, 256], + "nodmaisi_spacing": [0.754, 0.754, 1.28], + "resized": true + }, + "nodmaisi_params": { + "num_inference_steps": 30, + "noise_factor": 1.0, + "modality": 1, + "seed": 42 + }, + "timing": { + "prep_sec": 2.3, + "inference_sec": 185.7, + "qc_sec": 1.2, + "total_sec": 189.2 + }, + "sanity_checks": { + "shape_match": true, + "has_nodule_label": true, + "ct_min_hu": -1000.0, + "ct_max_hu": 812.3, + "has_nan": false + } +} +``` + +--- + +## 7. Runnable Commands + +### 7.1 Local Test — Single Case + +```bash +cd /home/ft42/NoMAISI +module load miniconda/py39_4.12.0 +source activate monai-auto3dseg +export MONAI_DATA_DIRECTORY=/home/ft42/NoMAISI/ +export PYTHONPATH=/home/ft42/NoMAISI:$PYTHONPATH + +# Dry run first (no GPU needed) +python tools/run_itrialspace_to_ct.py \ + --audit /scratch/railabs/ft42/VLST_Project/Data/iTrialSpace/inserted_masks/mode1_controlled_prevalence/audit.json \ + --config tools/integration_config.yaml \ + --outdir /tmp/test_nodmaisi \ + --case-ids 0 \ + --dry-run -vv + +# Real inference (requires GPU) +python tools/run_itrialspace_to_ct.py \ + --audit /scratch/railabs/ft42/VLST_Project/Data/iTrialSpace/inserted_masks/mode1_controlled_prevalence/audit.json \ + --config tools/integration_config.yaml \ + --outdir /scratch/railabs/ft42/VLST_Project/Data/iTrialSpace/generated_cts/mode1_test \ + --case-ids 0 \ + -v +``` + +### 7.2 SLURM — All 9 Modes (sequential per mode) + +```bash +cd /home/ft42/NoMAISI/slurm_nodmaisi +mkdir -p logs + +# Dry run all modes +./submit_all_nodmaisi.sh --dry-run + +# Submit all modes +./submit_all_nodmaisi.sh + +# Submit selected modes +./submit_all_nodmaisi.sh 1 8 +``` + +### 7.3 SLURM — Array Job (one case per GPU task) + +```bash +cd /home/ft42/NoMAISI/slurm_nodmaisi + +# Step 1: Generate case list from audit +AUDIT=/scratch/railabs/ft42/VLST_Project/Data/iTrialSpace/inserted_masks/mode1_controlled_prevalence/audit.json +python3 -c " +import json +audit = json.load(open('${AUDIT}')) +cases = sorted(set(str(r['case_id']) for r in audit['records'] if r['status']=='success')) +open('/tmp/mode1_controlled_prevalence_cases.txt','w').write('\n'.join(cases)) +print(f'{len(cases)} cases') +" + +# Step 2: Submit array job +N_CASES=$(wc -l < /tmp/mode1_controlled_prevalence_cases.txt) +sbatch --array=0-$((N_CASES - 1))%10 mode1_nodmaisi_array.sub +# ^^ max 10 concurrent GPU tasks +``` + +### 7.4 From Mask Directory (no audit) + +```bash +python tools/run_itrialspace_to_ct.py \ + --mask-root /scratch/.../inserted_masks/mode1_controlled_prevalence \ + --config tools/integration_config.yaml \ + --outdir /scratch/.../generated_cts/mode1 \ + -v +``` + +--- + +## 8. End-to-End Validation Checklist + +### Pre-flight +- [ ] NodMAISI model checkpoints exist at configured paths +- [ ] `monai-auto3dseg` conda environment is activated +- [ ] `MONAI_DATA_DIRECTORY` is set +- [ ] iTrialSpace mask insertion has completed (audit.json exists) +- [ ] GPU is available (`nvidia-smi` shows free VRAM) + +### Per-case Validation +- [ ] `input_mask.nii.gz` is RAS+ oriented, uint8 +- [ ] Mask dimensions match a valid NodMAISI size +- [ ] `dataset.json` is well-formed +- [ ] NodMAISI inference completes without error +- [ ] `synthetic_ct.nii.gz` exists and is non-empty +- [ ] Synthetic CT shape matches input mask shape +- [ ] CT intensity range is within [-1000, 1000] HU +- [ ] No NaN values in synthetic CT +- [ ] Mask contains label 23 (nodule voxels) +- [ ] QC PNGs show anatomically plausible CT with visible nodule +- [ ] `nodmaisi_audit.json` has all expected fields + +### Post-run +- [ ] `pipeline_summary.json` reports n_success > 0 +- [ ] Failed cases have clear error messages +- [ ] QC PNGs can be visually inspected for artifacts +- [ ] Synthetic CT can be loaded in ITK-SNAP or 3D Slicer + +--- + +## 9. Key Design Decisions + +1. **Subprocess invocation** — NodMAISI is called via `subprocess.run()` rather than Python import, to avoid namespace pollution, ensure clean GPU state between cases, and match the existing SLURM workflow. + +2. **Per-case dataset JSON** — Each case gets its own temporary `dataset.json` and `_tmp_env.json` to avoid modifying any shared NodMAISI config files. + +3. **Nearest-neighbor resize** — When mask dimensions don't match NodMAISI's valid sizes, we resize using order=0 (nearest) to preserve integer label values. Spacing is adjusted proportionally. + +4. **No changes to NodMAISI core** — All integration logic lives in `tools/` and `slurm_nodmaisi/`. The existing NodMAISI scripts and configs are untouched. + +5. **Label 23 alignment** — iTrialSpace's default nodule label (23) matches NodMAISI's lung tumor label (23). No label remapping is needed. This is the critical compatibility point. + +6. **Defensive processing** — Cases that fail are logged and skipped; processing continues. The summary report lists all failures. diff --git a/itrialspace/src/itrialspace/synthesis/tools/__init__.py b/itrialspace/src/itrialspace/synthesis/tools/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/itrialspace/src/itrialspace/synthesis/tools/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/tools/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..672f6aa17a0854239c13cb4f05aa8d0b0601982c Binary files /dev/null and b/itrialspace/src/itrialspace/synthesis/tools/__pycache__/__init__.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/synthesis/tools/__pycache__/run_itrialspace_to_ct.cpython-310.pyc b/itrialspace/src/itrialspace/synthesis/tools/__pycache__/run_itrialspace_to_ct.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..54fa1224ced3641604d93b8b4d5c2afb312bb8ab Binary files /dev/null and b/itrialspace/src/itrialspace/synthesis/tools/__pycache__/run_itrialspace_to_ct.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/synthesis/tools/integration_config.yaml b/itrialspace/src/itrialspace/synthesis/tools/integration_config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4613a38f94a484b31b23aa0c1b4cc61d41b1a063 --- /dev/null +++ b/itrialspace/src/itrialspace/synthesis/tools/integration_config.yaml @@ -0,0 +1,76 @@ +# ============================================================================ +# iTrialSpace -> NodMAISI Integration Pipeline — Configuration +# ============================================================================ + +# -- Paths to NodMAISI model components ----------------------------------- +# Paths use ${VAR} placeholders expanded by itrialspace.config.settings. +# Model weights are NOT bundled — set NODMAISI_MODELS_DIR to the directory holding +# autoencoder.pt / diffusion_unet.pt / controlnet *.pt (see docs/installation.md). +nodmaisi: + project_dir: ${ITRIALSPACE_ROOT}/src/itrialspace/synthesis + model_config: configs/config_maisi3d-rflow.json + controlnet_config: configs/infr_config_NoMAISI_controlnet.json + env_config: configs/infr_env_NoMAISI_DLCSD24_demo.json + # Model checkpoints (absolute via NODMAISI_MODELS_DIR, or relative to project_dir) + autoencoder_path: ${NODMAISI_MODELS_DIR}/autoencoder.pt + diffusion_unet_path: ${NODMAISI_MODELS_DIR}/diffusion_unet.pt + controlnet_path: ${NODMAISI_MODELS_DIR}/Experiments_NoMAISI_512xy_256z_771p25m_finetune_500epoch_best.pt + +# -- Inference parameters ------------------------------------------------- +inference: + num_inference_steps: 30 + autoencoder_sliding_window_infer_size: [80, 80, 64] + autoencoder_sliding_window_infer_overlap: 0.25 + noise_factor: 1.0 + modality: 1 # 1 = CT + seed: 42 + device: "cuda:0" + +# -- iTrialSpace mask parameters ------------------------------------------ +itrialspace: + nodule_label_value: 23 # Label value used by iTrialSpace for inserted nodules + # Base directory for resolving relative paths in iTrialSpace manifests/audits + base_dir: ${ITRIALSPACE_DATA_DIR} + # Root of iTrialSpace trial manifests (JSON/CSV with host_ct_path per case) + manifest_root: ${ITRIALSPACE_DATA_DIR}/manifests + +# -- Output structure ----------------------------------------------------- +output: + # Root for generated CTs. {trial_name} is substituted at runtime. + root: ${ITRIALSPACE_OUTPUT_DIR}/generated_cts + # Per-case subdirectory template + case_dir_template: "case_{case_id}" + # Filenames inside each case directory + synthetic_ct_name: synthetic_ct.nii.gz + input_mask_name: input_mask.nii.gz + host_ct_link_name: host_ct.nii.gz + qc_dir_name: qc + audit_name: nodmaisi_audit.json + +# -- QC settings ---------------------------------------------------------- +qc: + enabled: true + # Number of axial slices to render (evenly spaced through the nodule region) + num_slices: 3 + # Window level / width for CT display (HU) + window_center: -600 + window_width: 1500 + # PNG DPI + dpi: 150 + +# -- Geometry constraints (from NodMAISI check_input) --------------------- +geometry: + # Valid XY sizes for NodMAISI (first two dims must be equal) + valid_xy_sizes: [256, 384, 512] + # Valid Z sizes + valid_z_sizes: [128, 256, 384, 512, 640, 768] + # Target spacing for resampling if needed (null = use mask's native spacing) + target_spacing: null + # If true, resample mask to nearest valid size; if false, skip cases that don't fit + auto_resize: true + +# -- Conda / environment (for SLURM scripts) ----------------------------- +environment: + conda_module: "" + conda_env: ${ITRIALSPACE_CONDA_ENV} + monai_data_directory: ${ITRIALSPACE_ROOT}/src/itrialspace/synthesis diff --git a/itrialspace/src/itrialspace/synthesis/tools/run_itrialspace_to_ct.py b/itrialspace/src/itrialspace/synthesis/tools/run_itrialspace_to_ct.py new file mode 100644 index 0000000000000000000000000000000000000000..fe34f4b7be0e47d42d068f2792988cb158bd70bd --- /dev/null +++ b/itrialspace/src/itrialspace/synthesis/tools/run_itrialspace_to_ct.py @@ -0,0 +1,1348 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +run_itrialspace_to_ct.py — Integration pipeline: iTrialSpace masks -> NodMAISI -> synthetic CTs. + +Reads an iTrialSpace CohortManifest (CSV/JSON) or a directory of inserted masks, +prepares NodMAISI-compatible inputs, runs ControlNet-conditioned CT synthesis, +and produces synthetic CTs with QC outputs. + +Usage: + # From manifest (reads host_ct_path, host_organ_seg_path, inserted mask from audit) + python tools/run_itrialspace_to_ct.py \\ + --manifest /path/to/manifest.csv \\ + --audit /path/to/audit.json \\ + --config tools/integration_config.yaml \\ + --outdir $ITRIALSPACE_DATA_DIR/.../generated_cts/mode1 \\ + --jobs 1 + + # From a directory of inserted masks + python tools/run_itrialspace_to_ct.py \\ + --mask-root $ITRIALSPACE_DATA_DIR/.../inserted_masks/mode1_controlled_prevalence \\ + --config tools/integration_config.yaml \\ + --outdir $ITRIALSPACE_DATA_DIR/.../generated_cts/mode1 + + # Dry-run (validate inputs, skip inference) + python tools/run_itrialspace_to_ct.py \\ + --audit /path/to/audit.json \\ + --config tools/integration_config.yaml \\ + --outdir /tmp/test --dry-run +""" + +from __future__ import annotations + +import argparse +import gc +import json +import logging +import os +import sys +import time +from dataclasses import dataclass, field +from datetime import datetime + +import nibabel as nib +import numpy as np + +logger = logging.getLogger("itrialspace_to_ct") + +# --------------------------------------------------------------------------- +# Data structures +# --------------------------------------------------------------------------- + + +@dataclass +class CaseSpec: + """Specification for a single case to synthesize.""" + + case_id: str + mask_path: str # path to combined inserted mask (label map) + host_ct_path: str = "" # optional: for QC overlay / linking + dim: tuple = (512, 512, 256) # (X, Y, Z) volume dimensions + spacing: tuple = (0.7, 0.7, 1.25) # voxel spacing in mm + subdir: str = "" # subdirectory bucket (e.g., size_curve_10-15mm) + host_patient_id: str = "" + host_dataset: str = "" + donor_annotation_id: str = "" + trial_name: str = "" + + +@dataclass +class CaseResult: + """Result record for a single case.""" + + case_id: str = "" + status: str = "pending" # success | failed | skipped | dry_run + reason: str = "" + # Paths + input_mask_path: str = "" + host_ct_path: str = "" + synthetic_ct_path: str = "" + qc_png_paths: list = field(default_factory=list) + # Geometry + original_dim: tuple = () + original_spacing: tuple = () + nodmaisi_dim: tuple = () + nodmaisi_spacing: tuple = () + resized: bool = False + # Timing + prep_sec: float = 0.0 + inference_sec: float = 0.0 + qc_sec: float = 0.0 + total_sec: float = 0.0 + # Sanity checks + shape_match: bool = False + has_nodule_label: bool = False + ct_min_hu: float = 0.0 + ct_max_hu: float = 0.0 + has_nan: bool = False + + +# --------------------------------------------------------------------------- +# Configuration loader +# --------------------------------------------------------------------------- + + +def load_config(config_path: str) -> dict: + """Load YAML integration config, expanding ${VAR} placeholders portably.""" + from itrialspace.config import settings + + return settings.load_yaml(config_path) + + +# --------------------------------------------------------------------------- +# Case discovery +# --------------------------------------------------------------------------- + + +def _mask_stem(path: str) -> str: + """Derive a case ID from a mask filename. + + Strips ``_mask.nii.gz`` or ``.nii.gz`` suffix to produce a + human-readable, globally unique identifier. + """ + name = os.path.basename(path) + for suffix in ("_mask.nii.gz", ".nii.gz"): + if name.endswith(suffix): + return name[: -len(suffix)] + return name + + +def _build_host_ct_index(manifest_root: str) -> tuple[dict[str, str], dict[str, str]]: + """Build host CT lookup indices from manifest JSON/CSVs. + + Returns two dicts: + - **pid_index**: ``host_patient_id → host_ct_path`` + - **case_index**: ``"/" → host_ct_path`` + + The *pid_index* handles most datasets. The *case_index* is a fallback + for LUNA16 whose mask filenames use truncated hashes that don't match + the full DICOM UID stored as ``host_patient_id`` in the manifest. + """ + import glob as _glob + + pid_index: dict[str, str] = {} + case_index: dict[str, str] = {} + + def _ingest(records: list, trial_name: str): + for rec in records: + pid = str(rec.get("host_patient_id", "")) + hcp = str(rec.get("host_ct_path", "")) + cid = rec.get("case_id") + if not hcp: + continue + if pid: + pid_index[pid] = hcp + if trial_name and cid is not None: + case_index[f"{trial_name}/{int(cid)}"] = hcp + + # JSON manifests (structured, fast) + for jp in sorted(_glob.glob(os.path.join(manifest_root, "**", "*.json"), recursive=True)): + try: + with open(jp) as f: + data = json.load(f) + cases = data.get("cases") or data.get("records") or [] + tname = data.get("trial_name", "") + # If no trial_name field, infer from filename stem + if not tname: + tname = os.path.basename(jp).replace(".json", "") + _ingest(cases, tname) + except Exception: + continue + + # CSV manifests (supplement) + for cp in sorted(_glob.glob(os.path.join(manifest_root, "**", "*.csv"), recursive=True)): + try: + import pandas as pd + + df = pd.read_csv(cp) + tname = "" + if "trial_name" in df.columns: + tname = str(df["trial_name"].iloc[0]) + if not tname: + tname = os.path.basename(cp).replace(".csv", "") + for _, row in df.iterrows(): + rec = row.to_dict() + rec = {k: (str(v) if pd.notna(v) else "") for k, v in rec.items()} + pid = rec.get("host_patient_id", "") + hcp = rec.get("host_ct_path", "") + cid = rec.get("case_id") + if not hcp: + continue + if pid and pid not in pid_index: + pid_index[pid] = hcp + if tname and cid: + key = f"{tname}/{int(float(cid))}" + if key not in case_index: + case_index[key] = hcp + except Exception: + continue + + logger.info( + "Host-CT index: %d by patient-id, %d by trial/case from %s", + len(pid_index), + len(case_index), + manifest_root, + ) + return pid_index, case_index + + +def _parse_host_id(mask_stem: str) -> str: + """Extract the host patient ID from an iTrialSpace mask filename stem. + + Expects the ``--host---`` convention, e.g. + ``iTS--size_curve_10-15mm--C0000--host-DLCS_1092--src-DLCS24--nod-…`` + returns ``"DLCS_1092"``. Returns ``""`` if the pattern isn't found. + """ + import re + + m = re.search(r"--host-(.+?)--", mask_stem) + return m.group(1) if m else "" + + +def _parse_trial_case(mask_stem: str) -> tuple[str, str]: + """Extract (trial_name, integer_case_id) from an iTrialSpace mask filename. + + ``iTS--size_curve_10-15mm--C0036--host-…`` → ``("size_curve_10-15mm", "36")``. + Returns ``("", "")`` if either field isn't found. + """ + import re + + parts = mask_stem.split("--") + # parts: ["iTS", "size_curve_10-15mm", "C0036", "host-…", …] + trial = parts[1] if len(parts) > 1 else "" + cid_match = re.search(r"--C(\d+)--", mask_stem) + cid = str(int(cid_match.group(1))) if cid_match else "" + return trial, cid + + +def cases_from_audit(audit_path: str, cfg: dict) -> list[CaseSpec]: + """Build CaseSpecs from an iTrialSpace audit.json. + + If *audit_path* is a file, reads it directly. + If *audit_path* does not exist but its parent directory contains + sub-directory audit.json files, merge them all. + + Each case_id is the mask filename stem (without ``_mask.nii.gz``), + which is globally unique and self-documenting. + """ + audit_files: list[str] = [] + root_dir: str = "" + + if os.path.isfile(audit_path): + audit_files.append(audit_path) + root_dir = os.path.dirname(audit_path) + else: + # Try to discover audit.json files in subdirectories + parent = os.path.dirname(audit_path) + if os.path.isdir(parent): + import glob as _glob + + audit_files = sorted( + _glob.glob(os.path.join(parent, "**", "audit.json"), recursive=True) + ) + root_dir = parent + + if not audit_files: + logger.error("No audit.json found at %s or in subdirectories", audit_path) + return [] + + seen: dict[str, CaseSpec] = {} + for af in audit_files: + with open(af) as f: + audit = json.load(f) + + # Derive subdirectory name from the audit file's parent + af_dir = os.path.dirname(af) + subdir = os.path.basename(af_dir) if af_dir != root_dir else "" + + records = audit.get("records", []) + for rec in records: + if rec.get("status") != "success": + continue + + combined_path = rec.get("output_combined_path", "") + if not combined_path or not os.path.isfile(combined_path): + logger.warning( + "Case %s: combined mask not found at %s", rec.get("case_id"), combined_path + ) + continue + + cid = _mask_stem(combined_path) + if cid in seen: + continue + + try: + img = nib.load(combined_path) + img_can = nib.as_closest_canonical(img) + dim = tuple(int(d) for d in img_can.shape[:3]) + spacing = tuple(float(s) for s in img_can.header.get_zooms()[:3]) + except Exception as e: + logger.warning("Case %s: cannot read mask header: %s", cid, e) + continue + + seen[cid] = CaseSpec( + case_id=cid, + mask_path=combined_path, + host_ct_path=rec.get("host_ct_path", ""), + dim=dim, + spacing=spacing, + subdir=subdir, + host_patient_id=rec.get("host_patient_id", ""), + host_dataset=rec.get("host_dataset", ""), + donor_annotation_id=rec.get("donor_annotation_id", ""), + trial_name=audit.get("trial_name", ""), + ) + + cases = list(seen.values()) + src = ( + audit_path if len(audit_files) == 1 else f"{len(audit_files)} audit files under {root_dir}" + ) + logger.info("Discovered %d cases from %s", len(cases), src) + return cases + + +def cases_from_mask_root(mask_root: str, cfg: dict) -> list[CaseSpec]: + """Build CaseSpecs by scanning a directory of inserted mask NIfTIs. + + Searches recursively so subdirectory layouts (per-bucket, per-lobe, etc.) + are handled automatically. Each case_id is the mask filename stem + (without ``_mask.nii.gz``), which is globally unique. + + Host CT paths are resolved from the iTrialSpace manifest JSON / CSV + files (``itrialspace.manifest_root`` in config). These manifests already + record ``host_ct_path`` for every case: + + 1. Look up by ``host_patient_id`` (parsed from ``--host---``). + 2. Fallback: look up by ``trial_name/case_id_int`` (parsed from + ``----C--``). Handles LUNA16 whose mask filenames + use truncated hashes instead of the full DICOM UID. + """ + import glob + + # Build host-CT lookup from manifests (JSON + CSV) + manifest_root = cfg.get("itrialspace", {}).get("manifest_root", "") + pid_index: dict[str, str] = {} + case_index: dict[str, str] = {} + if manifest_root and os.path.isdir(manifest_root): + pid_index, case_index = _build_host_ct_index(manifest_root) + + # Recursive search: finds masks in root *and* subdirectories + masks = sorted(glob.glob(os.path.join(mask_root, "**", "*.nii.gz"), recursive=True)) + + cases = [] + n_host_found = 0 + for mp in masks: + case_id = _mask_stem(mp) + # Derive subdir from relative path (empty if mask is at root) + mp_dir = os.path.dirname(mp) + subdir = os.path.basename(mp_dir) if mp_dir != mask_root else "" + + # Resolve host CT via manifest lookup + host_ct = "" + # Strategy 1: by host_patient_id + host_id = _parse_host_id(case_id) + if host_id and host_id in pid_index: + host_ct = pid_index[host_id] + # Strategy 2: by trial_name / integer case_id (handles LUNA16 hash IDs) + if not host_ct: + trial, cid_int = _parse_trial_case(case_id) + key = f"{trial}/{cid_int}" + if key in case_index: + host_ct = case_index[key] + if host_ct: + n_host_found += 1 + + try: + img = nib.load(mp) + img_can = nib.as_closest_canonical(img) + dim = tuple(int(d) for d in img_can.shape[:3]) + spacing = tuple(float(s) for s in img_can.header.get_zooms()[:3]) + except Exception as e: + logger.warning("Skipping %s: %s", mp, e) + continue + + cases.append( + CaseSpec( + case_id=case_id, + mask_path=mp, + host_ct_path=host_ct, + dim=dim, + spacing=spacing, + subdir=subdir, + ) + ) + + logger.info( + "Discovered %d masks from %s (host CT resolved: %d/%d)", + len(cases), + mask_root, + n_host_found, + len(cases), + ) + return cases + + +def cases_from_manifest(manifest_path: str, mask_root: str, cfg: dict) -> list[CaseSpec]: + """Build CaseSpecs from an iTrialSpace CSV manifest + mask directory.""" + import pandas as pd + + df = pd.read_csv(manifest_path) + if "case_id" not in df.columns: + raise ValueError("Manifest must have a 'case_id' column") + + # Group by case_id, take first row per case + grouped = df.groupby("case_id", sort=False).first().reset_index() + cases = [] + for _, row in grouped.iterrows(): + cid = str(row["case_id"]) + # Try to find the combined mask in mask_root by pattern + import glob + + pattern = os.path.join(mask_root, f"*C{cid.zfill(4)}*_mask.nii.gz") + matches = glob.glob(pattern) + if not matches: + pattern2 = os.path.join(mask_root, f"*case{cid.zfill(4)}*") + matches = glob.glob(pattern2) + if not matches: + logger.warning("Case %s: no mask found in %s", cid, mask_root) + continue + mp = matches[0] + + try: + img = nib.load(mp) + img_can = nib.as_closest_canonical(img) + dim = tuple(int(d) for d in img_can.shape[:3]) + spacing = tuple(float(s) for s in img_can.header.get_zooms()[:3]) + except Exception as e: + logger.warning("Case %s: cannot read %s: %s", cid, mp, e) + continue + + cases.append( + CaseSpec( + case_id=cid, + mask_path=mp, + host_ct_path=str(row.get("host_ct_path", "")), + dim=dim, + spacing=spacing, + host_patient_id=str(row.get("host_patient_id", "")), + host_dataset=str(row.get("host_dataset", "")), + donor_annotation_id=str(row.get("donor_annotation_id", "")), + trial_name=str(row.get("trial_name", "")), + ) + ) + logger.info("Discovered %d cases from manifest %s", len(cases), manifest_path) + return cases + + +# --------------------------------------------------------------------------- +# Geometry validation / adjustment +# --------------------------------------------------------------------------- + + +def snap_to_valid_size(dim: tuple, geom_cfg: dict, spacing: tuple | None = None) -> tuple: + """Snap volume dimensions to nearest valid NodMAISI size. + + If *spacing* is provided and the physical FOV in XY + (spacing[0] * dim[0]) is below the NodMAISI minimum (256 mm), + the smallest valid XY size whose grid alone meets the threshold + is chosen. This allows ``prepare_mask_for_nodmaisi`` to clamp + the spacing to the minimum FOV / snapped_dim, satisfying the + ``check_input`` guard. + """ + valid_xy = sorted(geom_cfg.get("valid_xy_sizes", [256, 384, 512])) + valid_z = sorted(geom_cfg.get("valid_z_sizes", [128, 256, 384, 512, 640, 768])) + min_fov_xy = geom_cfg.get("min_fov_xy_mm", 256) + + def _nearest(val, choices): + return min(choices, key=lambda c: abs(c - val)) + + xy = _nearest(dim[0], valid_xy) # NodMAISI requires dim[0] == dim[1] + + # If the original physical FOV is below the minimum, pick the + # smallest valid XY size so floor-spacing = min_fov / xy stays + # reasonable (closer to original spacing). + if spacing is not None and spacing[0] * dim[0] < min_fov_xy: + # Choose largest valid xy to keep adjusted spacing close to original + xy = valid_xy[-1] # 512 — safest bet for borderline CTs + + z = _nearest(dim[2], valid_z) + return (xy, xy, z) + + +def prepare_mask_for_nodmaisi( + case: CaseSpec, output_dir: str, geom_cfg: dict, nodule_label: int = 23 +) -> dict: + """Load mask, ensure RAS+ orientation, resize if needed, write dataset JSON. + + Returns dict with keys: label_path, dim, spacing, resized, original_dim. + """ + img = nib.load(case.mask_path) + img_can = nib.as_closest_canonical(img) + data = np.asarray(img_can.dataobj) + spacing = tuple(float(s) for s in img_can.header.get_zooms()[:3]) + original_dim = data.shape[:3] + + target_dim = snap_to_valid_size(original_dim, geom_cfg, spacing=spacing) + resized = target_dim != original_dim + + if resized: + from scipy.ndimage import zoom as ndimage_zoom + + # NodMAISI requires isotropic XY spacing (spacing[0] == spacing[1]). + # When the original volume has non-square XY (dim_x != dim_y) and + # target_dim forces square XY, a naive resize creates anisotropic + # spacing. Fix: pad the shorter XY axis to match the longer one + # *before* resizing, so the zoom factor is identical for X and Y. + dx, dy, dz = data.shape[:3] + if dx != dy and target_dim[0] == target_dim[1]: + pad_dim = max(dx, dy) + pad_x = pad_dim - dx + pad_y = pad_dim - dy + # Symmetric padding (centered content) + px_before, px_after = pad_x // 2, pad_x - pad_x // 2 + py_before, py_after = pad_y // 2, pad_y - pad_y // 2 + data = np.pad( + data, + ((px_before, px_after), (py_before, py_after), (0, 0)), + mode="constant", + constant_values=0, + ) + logger.info( + "Padded non-square XY (%d,%d) -> (%d,%d) before resize " + "to preserve isotropic spacing.", + dx, + dy, + pad_dim, + pad_dim, + ) + original_dim = data.shape[:3] # update for zoom calculation + + zoom_factors = tuple(t / o for t, o in zip(target_dim, original_dim)) + # Use nearest-neighbor for label maps to preserve integer values + data_resized = ndimage_zoom(data.astype(np.float32), zoom_factors, order=0) + data = np.round(data_resized).astype(np.uint8) + # Adjust spacing proportionally + spacing = tuple(s * o / t for s, o, t in zip(spacing, original_dim, target_dim)) + + # NodMAISI requires spacing[0] == spacing[1] (exact equality). + # Source NIfTI headers sometimes store pixdim with float32 rounding, + # producing sp_x ≈ sp_y but not exactly equal. Force equality when + # the target grid is square. + if target_dim[0] == target_dim[1] and spacing[0] != spacing[1]: + avg_sp = (spacing[0] + spacing[1]) / 2.0 + spacing = (avg_sp, avg_sp, spacing[2]) + + # Ensure FOV meets NodMAISI's minimum (256 mm in XY). + # If the physical extent is still below the threshold after snapping + # (because the original CT was physically small), clamp spacing up so + # that target_dim[0] * spacing[0] >= min_fov. + min_fov_xy = geom_cfg.get("min_fov_xy_mm", 256) + fov_xy = target_dim[0] * spacing[0] + if fov_xy < min_fov_xy: + floor_sp = min_fov_xy / target_dim[0] + logger.warning( + "FOV too small (%.1f mm < %d mm). Clamping XY spacing " + "from %.4f to %.4f mm to satisfy NodMAISI constraint.", + fov_xy, + min_fov_xy, + spacing[0], + floor_sp, + ) + spacing = (floor_sp, floor_sp, spacing[2]) + + # Clamp Z spacing to NodMAISI's valid range [0.5, 5.0] mm. + # Ultra-thin-slice CTs (e.g. 0.27 mm) can produce z-spacing below + # the minimum after resizing to 256 slices. + sp_z = spacing[2] + if sp_z < 0.5: + logger.warning( + "Z spacing %.4f mm below minimum 0.5 mm; clamping to 0.5 mm.", + sp_z, + ) + spacing = (spacing[0], spacing[1], 0.5) + elif sp_z > 5.0: + logger.warning( + "Z spacing %.4f mm above maximum 5.0 mm; clamping to 5.0 mm.", + sp_z, + ) + spacing = (spacing[0], spacing[1], 5.0) + + # Save the prepared mask to the case output directory + os.makedirs(output_dir, exist_ok=True) + label_path = os.path.join(output_dir, "input_mask.nii.gz") + # Build a new affine with the (possibly adjusted) spacing + affine = np.diag(list(spacing) + [1.0]) + nib.save(nib.Nifti1Image(data.astype(np.uint8), affine), label_path) + + return { + "label_path": label_path, + "dim": list(target_dim), + "spacing": list(spacing), + "resized": resized, + "original_dim": list(original_dim), + } + + +def write_dataset_json(label_path: str, dim: list, spacing: list, output_dir: str) -> str: + """Write a NodMAISI-compatible dataset JSON for a single case.""" + # NodMAISI expects label path relative to data_base_dir + dataset = { + "name": "itrialspace_case", + "numTest": 1, + "testing": [ + { + "label": os.path.basename(label_path), + "fold": 0, + "dim": dim, + "spacing": spacing, + } + ], + } + json_path = os.path.join(output_dir, "dataset.json") + with open(json_path, "w") as f: + json.dump(dataset, f, indent=2) + return json_path + + +# --------------------------------------------------------------------------- +# NodMAISI inference wrapper +# --------------------------------------------------------------------------- + +# Default and fallback sliding-window sizes for autoencoder inference. +# If the first attempt OOMs or produces no output, retry with the smaller size. +_DEFAULT_AE_WINDOW = [80, 80, 64] +_FALLBACK_AE_WINDOW = [64, 64, 48] + + +def validate_condition_mask(label_path: str, cfg: dict) -> dict: + """Pre-NodMAISI QC gate — validate the prepared condition mask. + + Checks: + 1. File exists and is readable. + 2. Mask has the expected nodule label (default 23). + 3. Dimensions match a valid NodMAISI size. + 4. No NaN/Inf values. + 5. Nodule label occupies a physically plausible volume. + + Returns a dict: ``{"ok": bool, "reason": str, "details": dict}``. + """ + nodule_label = cfg.get("itrialspace", {}).get("nodule_label_value", 23) + geom_cfg = cfg.get("geometry", {}) + valid_xy = set(geom_cfg.get("valid_xy_sizes", [256, 384, 512])) + valid_z = set(geom_cfg.get("valid_z_sizes", [128, 256, 384, 512, 640, 768])) + + details: dict = {} + try: + img = nib.load(label_path) + data = np.asarray(img.dataobj) + details["shape"] = list(data.shape[:3]) + details["dtype"] = str(data.dtype) + except Exception as e: + return {"ok": False, "reason": f"Cannot read mask: {e}", "details": details} + + # 1) NaN / Inf check + if np.any(np.isnan(data)) or np.any(np.isinf(data)): + return {"ok": False, "reason": "Mask contains NaN or Inf values", "details": details} + + # 2) Dimension validity + dim = data.shape[:3] + if dim[0] != dim[1]: + return { + "ok": False, + "reason": f"X/Y dimensions differ ({dim[0]} vs {dim[1]}); NodMAISI requires square XY", + "details": details, + } + if dim[0] not in valid_xy: + return { + "ok": False, + "reason": f"XY size {dim[0]} not in valid set {sorted(valid_xy)}", + "details": details, + } + if dim[2] not in valid_z: + return { + "ok": False, + "reason": f"Z size {dim[2]} not in valid set {sorted(valid_z)}", + "details": details, + } + + # 3) Nodule label presence + n_nodule_vox = int(np.sum(data == nodule_label)) + details["n_nodule_voxels"] = n_nodule_vox + if n_nodule_vox == 0: + return { + "ok": False, + "reason": f"Mask contains no voxels with nodule label {nodule_label}", + "details": details, + } + + # 4) Plausibility: nodule should be < 10% of total volume + total_voxels = int(np.prod(dim)) + ratio = n_nodule_vox / total_voxels if total_voxels > 0 else 1.0 + details["nodule_volume_ratio"] = round(ratio, 6) + if ratio > 0.10: + return { + "ok": False, + "reason": f"Nodule label occupies {ratio:.1%} of volume (>10%); likely corrupt mask", + "details": details, + } + + return {"ok": True, "reason": "", "details": details} + + +def run_nodmaisi_inference( + case_dir: str, + dataset_json: str, + cfg: dict, + dry_run: bool = False, + ae_window: list | None = None, +) -> str | None: + """Run NodMAISI inference for a single case via subprocess. + + Parameters + ---------- + ae_window : list, optional + Override autoencoder_sliding_window_infer_size for this run. + Used by the retry path to reduce memory pressure. + + Returns the path to the generated synthetic CT, or None on failure. + """ + nodmaisi_cfg = cfg["nodmaisi"] + infer_cfg = cfg["inference"] + project_dir = nodmaisi_cfg["project_dir"] + + # Build a temporary environment config that points to this case's data + env_override = { + "model_dir": os.path.join(project_dir, "models") + "/", + "output_dir": case_dir, + "tfevent_path": os.path.join(case_dir, "tfevent"), + "trained_autoencoder_path": _resolve_path(nodmaisi_cfg["autoencoder_path"], project_dir), + "trained_diffusion_path": _resolve_path(nodmaisi_cfg["diffusion_unet_path"], project_dir), + "trained_controlnet_path": _resolve_path(nodmaisi_cfg["controlnet_path"], project_dir), + "exp_name": "iTS_case", + "data_base_dir": [case_dir], + "json_data_list": [dataset_json], + } + + # Apply sliding-window override for retry / reduced-memory runs + effective_window = ae_window or infer_cfg.get( + "autoencoder_sliding_window_infer_size", _DEFAULT_AE_WINDOW + ) + env_override["autoencoder_sliding_window_infer_size"] = effective_window + + # Write temporary env config + tmp_env_path = os.path.join(case_dir, "_tmp_env.json") + with open(tmp_env_path, "w") as f: + json.dump(env_override, f, indent=2) + + model_config = _resolve_path(nodmaisi_cfg["model_config"], project_dir) + controlnet_config = _resolve_path(nodmaisi_cfg["controlnet_config"], project_dir) + + if dry_run: + logger.info("[DRY RUN] Would run NodMAISI with env=%s", tmp_env_path) + return None + + import subprocess + + cmd = [ + sys.executable, + "-m", + "scripts.infer_testV2_controlnet", + "-c", + model_config, + "-e", + tmp_env_path, + "-t", + controlnet_config, + ] + + env = os.environ.copy() + env["MONAI_DATA_DIRECTORY"] = project_dir + + logger.info("Running NodMAISI: %s", " ".join(cmd)) + result = subprocess.run( + cmd, + capture_output=True, + text=True, + cwd=project_dir, + env=env, + timeout=3600, + ) + + if result.returncode != 0: + logger.error( + "NodMAISI failed (rc=%d):\nSTDOUT: %s\nSTDERR: %s", + result.returncode, + result.stdout[-2000:], + result.stderr[-2000:], + ) + # Persist stderr for structured failure diagnostics + stderr_path = os.path.join(case_dir, "_last_stderr.txt") + with open(stderr_path, "w") as f: + f.write(result.stderr[-4000:] if result.stderr else "") + return None + + # Find the generated image in case_dir (MONAI SaveImage appends _image suffix) + import glob + + candidates = glob.glob(os.path.join(case_dir, "*_image.nii.gz")) + if not candidates: + candidates = glob.glob(os.path.join(case_dir, "*.nii.gz")) + candidates = [ + c + for c in candidates + if "input_mask" not in c and "dataset" not in c and "_label" not in c + ] + + if candidates: + # Rename to standard name + out_cfg = cfg.get("output", {}) + final_name = out_cfg.get("synthetic_ct_name", "synthetic_ct.nii.gz") + final_path = os.path.join(case_dir, final_name) + os.rename(candidates[0], final_path) + return final_path + + logger.error("No synthetic CT found in %s after inference", case_dir) + # Persist stderr even on rc=0 for diagnostic purposes + stderr_path = os.path.join(case_dir, "_last_stderr.txt") + with open(stderr_path, "w") as f: + f.write(result.stderr[-4000:] if result.stderr else "") + return None + + +def _resolve_path(p: str, base: str) -> str: + """Resolve a possibly relative path against a base directory.""" + if os.path.isabs(p): + return p + return os.path.join(base, p) + + +# --------------------------------------------------------------------------- +# QC: PNG generation +# --------------------------------------------------------------------------- + + +def generate_qc( + case_dir: str, + synthetic_ct_path: str, + mask_path: str, + host_ct_path: str, + cfg: dict, + nodule_label: int = 23, +) -> list[str]: + """Generate QC PNG montages showing host CT, mask overlay, and synthetic CT.""" + qc_cfg = cfg.get("qc", {}) + if not qc_cfg.get("enabled", True): + return [] + + try: + import matplotlib + + matplotlib.use("Agg") + import matplotlib.pyplot as plt + + except ImportError: + logger.warning("matplotlib not available; skipping QC PNGs") + return [] + + num_slices = qc_cfg.get("num_slices", 3) + wc = qc_cfg.get("window_center", -600) + ww = qc_cfg.get("window_width", 1500) + dpi = qc_cfg.get("dpi", 150) + vmin, vmax = wc - ww / 2, wc + ww / 2 + + qc_dir = os.path.join(case_dir, cfg.get("output", {}).get("qc_dir_name", "qc")) + os.makedirs(qc_dir, exist_ok=True) + + # Load volumes + synth_data = np.asarray(nib.as_closest_canonical(nib.load(synthetic_ct_path)).dataobj) + mask_data = np.asarray(nib.as_closest_canonical(nib.load(mask_path)).dataobj) + + has_host = host_ct_path and os.path.isfile(host_ct_path) + if has_host: + try: + host_data = np.asarray(nib.as_closest_canonical(nib.load(host_ct_path)).dataobj) + except Exception: + has_host = False + host_data = None + else: + host_data = None + + # Find axial slices that contain nodule label + nodule_slices = np.where(np.any(mask_data == nodule_label, axis=(0, 1)))[0] + if len(nodule_slices) == 0: + # Fallback: evenly spaced slices through the volume + nodule_slices = np.linspace(0, synth_data.shape[2] - 1, num_slices + 2, dtype=int)[1:-1] + else: + # Pick evenly spaced slices through the nodule Z-range + indices = np.linspace(0, len(nodule_slices) - 1, num_slices, dtype=int) + nodule_slices = nodule_slices[indices] + + png_paths = [] + for si, k in enumerate(nodule_slices): + ncols = 3 if has_host else 2 + fig, axes = plt.subplots(1, ncols, figsize=(5 * ncols, 5)) + + col = 0 + if has_host: + axes[col].imshow( + host_data[:, :, k].T, + cmap="gray", + vmin=vmin, + vmax=vmax, + origin="lower", + aspect="equal", + ) + axes[col].set_title(f"Host CT (z={k})") + axes[col].axis("off") + col += 1 + + # Mask overlay on synthetic CT + axes[col].imshow( + synth_data[:, :, k].T, cmap="gray", vmin=vmin, vmax=vmax, origin="lower", aspect="equal" + ) + nodule_overlay = np.ma.masked_where(mask_data[:, :, k] != nodule_label, mask_data[:, :, k]) + axes[col].imshow(nodule_overlay.T, cmap="autumn", alpha=0.5, origin="lower", aspect="equal") + axes[col].set_title(f"Synth CT + Mask (z={k})") + axes[col].axis("off") + col += 1 + + # Synthetic CT alone + axes[col].imshow( + synth_data[:, :, k].T, cmap="gray", vmin=vmin, vmax=vmax, origin="lower", aspect="equal" + ) + axes[col].set_title(f"Synthetic CT (z={k})") + axes[col].axis("off") + + png_name = f"qc_slice_{si:02d}_z{k:04d}.png" + png_path = os.path.join(qc_dir, png_name) + fig.tight_layout() + fig.savefig(png_path, dpi=dpi, bbox_inches="tight") + plt.close(fig) + png_paths.append(png_path) + + return png_paths + + +# --------------------------------------------------------------------------- +# Sanity checks +# --------------------------------------------------------------------------- + + +def sanity_check(synthetic_ct_path: str, mask_path: str, nodule_label: int = 23) -> dict: + """Run sanity checks on the synthetic CT.""" + checks = { + "shape_match": False, + "has_nodule_label": False, + "ct_min_hu": 0.0, + "ct_max_hu": 0.0, + "has_nan": False, + } + try: + ct_img = nib.load(synthetic_ct_path) + ct_data = np.asarray(ct_img.dataobj) + mask_img = nib.load(mask_path) + mask_data = np.asarray(mask_img.dataobj) + + checks["shape_match"] = ct_data.shape[:3] == mask_data.shape[:3] + checks["has_nodule_label"] = bool(np.any(mask_data == nodule_label)) + checks["ct_min_hu"] = float(np.nanmin(ct_data)) + checks["ct_max_hu"] = float(np.nanmax(ct_data)) + checks["has_nan"] = bool(np.any(np.isnan(ct_data))) + except Exception as e: + logger.error("Sanity check failed: %s", e) + return checks + + +# --------------------------------------------------------------------------- +# Per-case orchestrator +# --------------------------------------------------------------------------- + + +def process_one_case(case: CaseSpec, cfg: dict, outdir: str, dry_run: bool = False) -> CaseResult: + """Full pipeline for a single case: prepare -> infer -> QC -> audit.""" + t0 = time.time() + result = CaseResult( + case_id=case.case_id, input_mask_path=case.mask_path, host_ct_path=case.host_ct_path + ) + + out_cfg = cfg.get("output", {}) + # Mirror input subdirectory structure: subdir/case_id + if case.subdir: + case_dir = os.path.join(outdir, case.subdir, case.case_id) + else: + case_dir = os.path.join(outdir, case.case_id) + os.makedirs(case_dir, exist_ok=True) + + geom_cfg = cfg.get("geometry", {}) + nodule_label = cfg.get("itrialspace", {}).get("nodule_label_value", 23) + + # --- Step 1: Prepare mask --- + t_prep = time.time() + try: + prep = prepare_mask_for_nodmaisi(case, case_dir, geom_cfg, nodule_label) + except Exception as e: + result.status = "failed" + result.reason = f"Mask preparation failed: {e}" + result.total_sec = time.time() - t0 + return result + + result.original_dim = tuple(prep["original_dim"]) + result.original_spacing = tuple(case.spacing) + result.nodmaisi_dim = tuple(prep["dim"]) + result.nodmaisi_spacing = tuple(prep["spacing"]) + result.resized = prep["resized"] + + dataset_json = write_dataset_json(prep["label_path"], prep["dim"], prep["spacing"], case_dir) + result.prep_sec = time.time() - t_prep + + # --- Step 1b: Pre-NodMAISI QC gate (validate condition mask) --- + qc_gate = validate_condition_mask(prep["label_path"], cfg) + if not qc_gate["ok"]: + result.status = "failed" + result.reason = f"Pre-NodMAISI QC gate rejected mask: {qc_gate['reason']}" + result.total_sec = time.time() - t0 + return result + + # --- Step 2: Symlink host CT (optional) --- + if case.host_ct_path and os.path.isfile(case.host_ct_path): + link_name = out_cfg.get("host_ct_link_name", "host_ct.nii.gz") + link_path = os.path.join(case_dir, link_name) + if not os.path.exists(link_path): + try: + os.symlink(case.host_ct_path, link_path) + except OSError: + pass # skip if symlinking not supported + + # --- Step 3: Run NodMAISI inference --- + if dry_run: + result.status = "dry_run" + result.reason = "Dry run — inference skipped" + result.total_sec = time.time() - t0 + return result + + t_infer = time.time() + synthetic_ct_path = run_nodmaisi_inference(case_dir, dataset_json, cfg) + result.inference_sec = time.time() - t_infer + + # Retry with smaller sliding window if first attempt produced no output + if synthetic_ct_path is None: + infer_cfg = cfg.get("inference", {}) + current_window = infer_cfg.get("autoencoder_sliding_window_infer_size", _DEFAULT_AE_WINDOW) + if current_window != _FALLBACK_AE_WINDOW: + logger.warning( + "Case %s: first attempt produced no output, retrying with " + "reduced sliding window %s → %s", + case.case_id, + current_window, + _FALLBACK_AE_WINDOW, + ) + t_retry = time.time() + synthetic_ct_path = run_nodmaisi_inference( + case_dir, + dataset_json, + cfg, + ae_window=_FALLBACK_AE_WINDOW, + ) + retry_sec = time.time() - t_retry + result.inference_sec += retry_sec + if synthetic_ct_path is not None: + logger.info( + "Case %s: retry succeeded with reduced window (%.1fs)", + case.case_id, + retry_sec, + ) + + if synthetic_ct_path is None: + # Collect structured diagnostics for the failure + diag: dict = {"case_id": case.case_id} + try: + diag["mask_dim"] = list(result.nodmaisi_dim) + diag["mask_spacing"] = list(result.nodmaisi_spacing) + diag["mask_resized"] = result.resized + # Check for GPU memory info + try: + import torch + + if torch.cuda.is_available(): + diag["gpu_mem_allocated_MB"] = round(torch.cuda.memory_allocated() / 1e6, 1) + diag["gpu_mem_reserved_MB"] = round(torch.cuda.memory_reserved() / 1e6, 1) + diag["gpu_name"] = torch.cuda.get_device_name(0) + except Exception: + pass + # Log stderr tail from last subprocess run + last_stderr_path = os.path.join(case_dir, "_last_stderr.txt") + if os.path.isfile(last_stderr_path): + with open(last_stderr_path) as f: + diag["stderr_tail"] = f.read()[-2000:] + except Exception: + pass + + # Write structured failure log + fail_log_path = os.path.join(case_dir, "nodmaisi_failure.json") + with open(fail_log_path, "w") as f: + json.dump(diag, f, indent=2, default=str) + + result.status = "failed" + result.reason = ( + f"NodMAISI inference produced no output " + f"(dim={list(result.nodmaisi_dim)}, retried={current_window != _FALLBACK_AE_WINDOW})" + ) + result.total_sec = time.time() - t0 + return result + + result.synthetic_ct_path = synthetic_ct_path + + # --- Step 4: Sanity checks --- + checks = sanity_check(synthetic_ct_path, prep["label_path"], nodule_label) + result.shape_match = checks["shape_match"] + result.has_nodule_label = checks["has_nodule_label"] + result.ct_min_hu = checks["ct_min_hu"] + result.ct_max_hu = checks["ct_max_hu"] + result.has_nan = checks["has_nan"] + + # --- Step 5: QC PNGs --- + t_qc = time.time() + try: + result.qc_png_paths = generate_qc( + case_dir, synthetic_ct_path, prep["label_path"], case.host_ct_path, cfg, nodule_label + ) + except Exception as e: + logger.warning("QC generation failed for case %s: %s", case.case_id, e) + result.qc_sec = time.time() - t_qc + + result.status = "success" + result.total_sec = time.time() - t0 + return result + + +# --------------------------------------------------------------------------- +# Write per-case audit JSON +# --------------------------------------------------------------------------- + + +def write_case_audit(result: CaseResult, case_dir: str, cfg: dict): + """Write a per-case NodMAISI audit JSON.""" + audit = { + "case_id": result.case_id, + "status": result.status, + "reason": result.reason, + "timestamp": datetime.now().isoformat(), + "input_mask_path": result.input_mask_path, + "host_ct_path": result.host_ct_path, + "synthetic_ct_path": result.synthetic_ct_path, + "geometry": { + "original_dim": result.original_dim, + "original_spacing": result.original_spacing, + "nodmaisi_dim": result.nodmaisi_dim, + "nodmaisi_spacing": result.nodmaisi_spacing, + "resized": result.resized, + }, + "nodmaisi_params": { + "num_inference_steps": cfg.get("inference", {}).get("num_inference_steps", 30), + "noise_factor": cfg.get("inference", {}).get("noise_factor", 1.0), + "modality": cfg.get("inference", {}).get("modality", 1), + "seed": cfg.get("inference", {}).get("seed", 42), + "autoencoder_sliding_window_infer_size": cfg.get("inference", {}).get( + "autoencoder_sliding_window_infer_size", [80, 80, 64] + ), + }, + "timing": { + "prep_sec": round(result.prep_sec, 2), + "inference_sec": round(result.inference_sec, 2), + "qc_sec": round(result.qc_sec, 2), + "total_sec": round(result.total_sec, 2), + }, + "sanity_checks": { + "shape_match": result.shape_match, + "has_nodule_label": result.has_nodule_label, + "ct_min_hu": round(result.ct_min_hu, 1), + "ct_max_hu": round(result.ct_max_hu, 1), + "has_nan": result.has_nan, + }, + "qc_pngs": result.qc_png_paths, + } + audit_name = cfg.get("output", {}).get("audit_name", "nodmaisi_audit.json") + audit_path = os.path.join(case_dir, audit_name) + with open(audit_path, "w") as f: + json.dump(audit, f, indent=2, default=str) + + +# --------------------------------------------------------------------------- +# Main +# --------------------------------------------------------------------------- + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser( + prog="run_itrialspace_to_ct", + description="iTrialSpace masks -> NodMAISI -> synthetic CTs", + ) + parser.add_argument("--manifest", "-m", help="iTrialSpace manifest CSV") + parser.add_argument("--audit", "-a", help="iTrialSpace audit.json (preferred)") + parser.add_argument("--mask-root", help="Directory of inserted mask NIfTIs") + parser.add_argument("--config", "-c", required=True, help="Integration config YAML") + parser.add_argument("--outdir", "-o", required=True, help="Output directory") + parser.add_argument("--jobs", "-j", type=int, default=1, help="Parallelism (future)") + parser.add_argument("--dry-run", action="store_true", help="Validate only, no inference") + parser.add_argument("--verbose", "-v", action="count", default=0) + parser.add_argument("--case-ids", nargs="*", help="Process only these case IDs") + + args = parser.parse_args(argv) + + # Logging + level = logging.WARNING + if args.verbose == 1: + level = logging.INFO + elif args.verbose >= 2: + level = logging.DEBUG + logging.basicConfig( + level=level, + format="%(asctime)s [%(name)s] %(levelname)s: %(message)s", + datefmt="%H:%M:%S", + ) + + cfg = load_config(args.config) + + # --- Discover cases --- + if args.audit: + cases = cases_from_audit(args.audit, cfg) + elif args.mask_root: + cases = cases_from_mask_root(args.mask_root, cfg) + elif args.manifest and args.mask_root: + cases = cases_from_manifest(args.manifest, args.mask_root, cfg) + elif args.manifest: + # Need mask_root too if not using audit + parser.error("--manifest requires --mask-root to locate combined masks") + return 1 + else: + parser.error("Provide --audit, --mask-root, or --manifest + --mask-root") + return 1 + + # Filter by case IDs if specified + if args.case_ids: + id_set = set(args.case_ids) + cases = [c for c in cases if c.case_id in id_set] + + if not cases: + logger.error("No cases found. Check input paths.") + return 1 + + os.makedirs(args.outdir, exist_ok=True) + + # --- Process cases --- + results = [] + t_total = time.time() + for i, case in enumerate(cases): + logger.info("=== Case %d/%d: %s ===", i + 1, len(cases), case.case_id) + result = process_one_case(case, cfg, args.outdir, dry_run=args.dry_run) + results.append(result) + + # Write per-case audit + if case.subdir: + case_dir = os.path.join(args.outdir, case.subdir, case.case_id) + else: + case_dir = os.path.join(args.outdir, case.case_id) + write_case_audit(result, case_dir, cfg) + + logger.info(" Status: %s Time: %.1fs", result.status, result.total_sec) + + # Free GPU memory between cases + gc.collect() + try: + import torch + + torch.cuda.empty_cache() + except Exception: + pass + + # --- Summary report --- + elapsed = time.time() - t_total + n_ok = sum(1 for r in results if r.status == "success") + n_fail = sum(1 for r in results if r.status == "failed") + n_dry = sum(1 for r in results if r.status == "dry_run") + + print(f"\n{'=' * 60}") + print(f" iTrialSpace -> NodMAISI Pipeline {'DRY RUN' if args.dry_run else 'COMPLETE'}") + print(f"{'=' * 60}") + print(f" Total cases: {len(results)}") + print(f" Success: {n_ok}") + print(f" Failed: {n_fail}") + if n_dry: + print(f" Dry-run: {n_dry}") + print(f" Elapsed: {elapsed:.1f}s") + print(f" Output dir: {args.outdir}") + + if n_fail > 0: + print("\nFailed cases:") + for r in results: + if r.status == "failed": + print(f" case {r.case_id}: {r.reason}") + + # Write summary — use per-case path for single-case (array job) runs + # to avoid race conditions when many tasks write to the same outdir. + summary = { + "pipeline": "itrialspace_to_nodmaisi", + "timestamp": datetime.now().isoformat(), + "total_cases": len(results), + "n_success": n_ok, + "n_failed": n_fail, + "n_dry_run": n_dry, + "elapsed_sec": round(elapsed, 1), + "config": args.config, + "cases": [ + { + "case_id": r.case_id, + "status": r.status, + "reason": r.reason, + "synthetic_ct": r.synthetic_ct_path, + "total_sec": round(r.total_sec, 2), + } + for r in results + ], + } + if len(results) == 1: + # Array-job mode: write per-case summary inside the case output dir + # Check flat layout first, then sub-bin layout + case_dir = os.path.join(args.outdir, results[0].case_id) + if not os.path.isdir(case_dir): + # Search sub-directories for the case (sub-bin layout) + for entry in os.listdir(args.outdir) if os.path.isdir(args.outdir) else []: + candidate = os.path.join(args.outdir, entry, results[0].case_id) + if os.path.isdir(candidate): + case_dir = candidate + break + if os.path.isdir(case_dir): + summary_path = os.path.join(case_dir, "pipeline_summary.json") + else: + summary_path = os.path.join(args.outdir, "pipeline_summary.json") + else: + summary_path = os.path.join(args.outdir, "pipeline_summary.json") + with open(summary_path, "w") as f: + json.dump(summary, f, indent=2, default=str) + + return 1 if n_fail > 0 and n_ok == 0 else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/itrialspace/src/itrialspace/trials/__init__.py b/itrialspace/src/itrialspace/trials/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/itrialspace/src/itrialspace/trials/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/trials/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7f4df1770ffe6cf69d39e8ff75c24b175c1f01b9 Binary files /dev/null and b/itrialspace/src/itrialspace/trials/__pycache__/__init__.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/trials/__pycache__/run_trial.cpython-310.pyc b/itrialspace/src/itrialspace/trials/__pycache__/run_trial.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c0391dfb36bcdd5d7b1f1762fdcf9b6d64e3d48a Binary files /dev/null and b/itrialspace/src/itrialspace/trials/__pycache__/run_trial.cpython-310.pyc differ diff --git a/itrialspace/src/itrialspace/trials/run_trial.py b/itrialspace/src/itrialspace/trials/run_trial.py new file mode 100644 index 0000000000000000000000000000000000000000..96508ee1ff75ae128788ade261fc0b601aa32fd0 --- /dev/null +++ b/itrialspace/src/itrialspace/trials/run_trial.py @@ -0,0 +1,670 @@ +#!/usr/bin/env python3 +""" +iTrialSpace Trial Runner — builds a cohort manifest from a trial mode. + +Usage: + python run_trial.py --mode [OPTIONS] + +Modes: + 1 controlled_prevalence Fixed malignancy prevalence + 2 size_detection_curve One cohort per size bucket (FROC) + 3 location_sensitivity One cohort per lobe + 4 demographic_strat Cohorts by demographic strata + 5 counterfactual Same cohort, one parameter varied + 6 cross_dataset One cohort per dataset as sole donor + 7 bootstrap_confidence N bootstrap replicates of a base cohort + 8 algorithm_comparison Single standardised cohort for comparing models + 9 screening_simulation Multi-round screening protocol + 10 multi_nodule Single vs multi-nodule sub-cohorts + 11 digital_twin_isolation Per-nodule isolation within host anatomy + 12 digital_twin_complete Full multi-nodule digital twin per CT scan + 13 digital_twin_cross Cross-patient host anatomy + donor nodules + +All manifests are written to --output-dir (default: ./output/). +""" + +from __future__ import annotations + +import argparse +import json +import os +import sys +import time + +# Add itrialspace to path +ITRIALSPACE_ROOT = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +sys.path.insert(0, ITRIALSPACE_ROOT) + + +def load_index(): + """Load the full NoduleIndex from the dataset registry. + + The dataset registry config is discovered via ``itrialspace.config.settings`` + (configs/datasets.yaml → datasets.example.yaml → bundled default), with paths + resolved from ``$ITRIALSPACE_DATA_DIR``. + """ + from itrialspace import DatasetRegistry, NoduleIndex + + registry = DatasetRegistry.from_yaml() + print("Loading index from configured dataset registry ...") + idx = NoduleIndex.from_registry(registry, verbose=True) + print(f"Loaded {len(idx.df):,} nodules from {idx.df['dataset'].nunique()} datasets") + return idx + + +def build_and_save(builder, specs, output_dir, verify_paths=True, args=None): + """Build manifests from specs and save to output_dir.""" + os.makedirs(output_dir, exist_ok=True) + + if not isinstance(specs, list): + specs = [specs] + + for i, spec in enumerate(specs): + print(f"\n{'='*60}") + print(f"Building: {spec.trial_name} ({i+1}/{len(specs)})") + print(f" n_cases={spec.n_cases}, mode={spec.cohort_mode}, seed={spec.seed}") + if spec.malignancy_prevalence is not None: + print(f" target prevalence={spec.malignancy_prevalence:.3f}") + print(f"{'='*60}") + + t0 = time.time() + + if spec.n_bootstrap > 1: + manifests = builder.build_all(spec, verbose=True) + for j, m in enumerate(manifests): + name = f"{spec.trial_name}_boot{j:03d}" + csv_path = os.path.join(output_dir, f"{name}.csv") + m.to_csv(csv_path) + print(f" Bootstrap {j}: {len(m)} cases → {csv_path}") + manifest = manifests[0] # use first for summary + else: + manifest = builder.build(spec, verbose=True) + csv_path = os.path.join(output_dir, f"{spec.trial_name}.csv") + json_path = os.path.join(output_dir, f"{spec.trial_name}.json") + manifest.to_csv(csv_path) + manifest.to_json(json_path) + print(f" Saved CSV: {csv_path}") + print(f" Saved JSON: {json_path}") + + elapsed = time.time() - t0 + print(f"\n Built in {elapsed:.1f}s") + + # Summary + summary = manifest.summary() + print(f" Cases: {summary['n_cases']}") + if "n_malignant" in summary: + print(f" Malignant: {summary['n_malignant']}, Benign: {summary['n_benign']}") + if "malignancy_rate" in summary: + print(f" Actual prevalence: {summary['malignancy_rate']:.4f}") + if "donor_datasets" in summary: + print(f" Donor datasets: {summary['donor_datasets']}") + + # Audit + audit = manifest.audit() + if len(audit) > 0: + print("\n Audit:") + for _, row in audit.iterrows(): + print( + f" {row['metric']}: target={row['target']}, actual={row['actual']}, dev={row['deviation']}" + ) + + # Path verification + if verify_paths: + missing = manifest.verify_paths() + n_total = len(manifest) * 4 + n_found = n_total - len(missing) + print(f"\n Paths: {n_found}/{n_total} exist ({n_found/n_total*100:.1f}%)") + if len(missing) > 0: + by_type = missing["path_type"].value_counts().to_dict() + print(f" Missing by type: {by_type}") + + # Save run config + config_path = os.path.join(output_dir, "_run_config.json") + with open(config_path, "w") as f: + json.dump( + { + "mode": args.mode, + "n_specs": len(specs), + "trial_names": [s.trial_name for s in specs], + "args": vars(args), + }, + f, + indent=2, + default=str, + ) + print(f"\nRun config saved to {config_path}") + + +def run(args): + from itrialspace.site.cohort_builder import CohortBuilder + from itrialspace.site.path_resolver import PathResolver + + idx = load_index() + builder = CohortBuilder(idx, PathResolver()) + + mode = args.mode + + # ── Mode 1: Controlled Prevalence ──────────────────────────────────── + if mode == "controlled_prevalence": + from itrialspace.site.trial_modes import controlled_prevalence_study + + spec = controlled_prevalence_study( + n_cases=args.n_cases, + prevalence=args.prevalence, + template=args.template, + seed=args.seed, + ) + build_and_save(builder, spec, args.output_dir, args.verify_paths, args) + + # ── Mode 2: Size Detection Curve ───────────────────────────────────── + elif mode == "size_detection_curve": + from itrialspace.site.trial_modes import size_detection_curve + + specs = size_detection_curve( + n_per_bucket=args.n_per_bucket, + label=args.label, + template=args.template, + seed=args.seed, + ) + build_and_save(builder, specs, args.output_dir, args.verify_paths, args) + + # ── Mode 3: Location Sensitivity ───────────────────────────────────── + elif mode == "location_sensitivity": + from itrialspace.site.trial_modes import location_sensitivity + + specs = location_sensitivity( + n_per_lobe=args.n_per_lobe, + label=args.label, + diameter_range=(args.diam_min, args.diam_max), + template=args.template, + seed=args.seed, + ) + build_and_save(builder, specs, args.output_dir, args.verify_paths, args) + + # ── Mode 4: Demographic Stratification ─────────────────────────────── + elif mode == "demographic_strat": + from itrialspace.site.trial_modes import demographic_stratification + + specs = demographic_stratification( + n_per_stratum=args.n_per_stratum, + template=args.template, + seed=args.seed, + ) + build_and_save(builder, specs, args.output_dir, args.verify_paths, args) + + # ── Mode 5: Counterfactual Cohort ──────────────────────────────────── + elif mode == "counterfactual": + from itrialspace.site.trial_modes import counterfactual_cohort + + values = [float(v) for v in args.values.split(",")] if args.values else None + specs = counterfactual_cohort( + n_cases=args.n_cases, + template=args.template, + vary_param=args.vary_param, + values=values, + seed=args.seed, + ) + build_and_save(builder, specs, args.output_dir, args.verify_paths, args) + + # ── Mode 6: Cross-Dataset Generalization ───────────────────────────── + elif mode == "cross_dataset": + from itrialspace.site.trial_modes import cross_dataset_generalization + + datasets = args.datasets.split(",") if args.datasets else None + specs = cross_dataset_generalization( + n_cases=args.n_cases, + datasets=datasets, + seed=args.seed, + ) + build_and_save(builder, specs, args.output_dir, args.verify_paths, args) + + # ── Mode 7: Bootstrap Confidence ───────────────────────────────────── + elif mode == "bootstrap_confidence": + from itrialspace.site.trial_modes import bootstrap_confidence, controlled_prevalence_study + + base = controlled_prevalence_study( + n_cases=args.n_cases, + prevalence=args.prevalence, + template=args.template, + seed=args.seed, + ) + spec = bootstrap_confidence(base, n_bootstrap=args.n_bootstrap) + build_and_save(builder, spec, args.output_dir, args.verify_paths, args) + + # ── Mode 8: Algorithm Comparison ───────────────────────────────────── + elif mode == "algorithm_comparison": + from itrialspace.site.trial_modes import algorithm_comparison + + spec = algorithm_comparison( + n_cases=args.n_cases, + template=args.template, + seed=args.seed, + ) + build_and_save(builder, spec, args.output_dir, args.verify_paths, args) + + # ── Mode 9: Screening Protocol Simulation ──────────────────────────── + elif mode == "screening_simulation": + from itrialspace.site.trial_modes import screening_protocol_simulation + + specs = screening_protocol_simulation( + template=args.template, + n_rounds=args.n_rounds, + n_cases_per_round=args.n_cases_per_round, + prevalence_decay=args.prevalence_decay, + seed=args.seed, + ) + build_and_save(builder, specs, args.output_dir, args.verify_paths, args) + + # ── Mode 10: Multi-Nodule Realism Study ────────────────────────────── + elif mode == "multi_nodule": + from itrialspace.site.trial_modes import multi_nodule_realism_study + + specs = multi_nodule_realism_study( + n_cases=args.n_cases, + multi_nodule_fraction=args.multi_nodule_fraction, + companion_strategy=args.companion_strategy, + template=args.template, + seed=args.seed, + ) + build_and_save(builder, specs, args.output_dir, args.verify_paths, args) + + # ── Mode 11: Digital Twin Isolation ──────────────────────────────── + elif mode == "digital_twin_isolation": + from itrialspace.site.trial_modes import digital_twin_isolation + + if not args.dataset: + print("ERROR: --dataset is required for digital_twin_isolation mode") + sys.exit(1) + + iso_spec = digital_twin_isolation( + dataset=args.dataset, + max_patients=args.max_patients, + all_patients=args.all_patients, + max_nodules_per_patient=args.max_nodules_per_patient, + label=args.iso_label, + diameter_min=args.diameter_min, + diameter_max=args.diameter_max, + seed=args.seed, + ) + + print(f"\n{'='*60}") + print(f"Building: {iso_spec.trial_name}") + print(f" dataset={iso_spec.dataset}, seed={iso_spec.seed}") + if iso_spec.max_patients: + print(f" max_patients={iso_spec.max_patients}") + else: + print(" all_patients=True") + print(f"{'='*60}") + + t0 = time.time() + manifest = builder.build_digital_twin_isolation(iso_spec, verbose=True) + elapsed = time.time() - t0 + + output_dir = args.output_dir + os.makedirs(output_dir, exist_ok=True) + csv_path = os.path.join(output_dir, f"{iso_spec.trial_name}.csv") + json_path = os.path.join(output_dir, f"{iso_spec.trial_name}.json") + manifest.to_csv(csv_path) + manifest.to_json(json_path) + + print(f"\n Built in {elapsed:.1f}s") + print(f" Saved CSV: {csv_path}") + print(f" Saved JSON: {json_path}") + + summary = manifest.summary() + print(f" Cases: {summary['n_cases']}") + if "n_malignant" in summary: + print(f" Malignant: {summary['n_malignant']}, Benign: {summary['n_benign']}") + + if args.verify_paths: + missing = manifest.verify_paths() + n_total = len(manifest) * 4 + n_found = n_total - len(missing) + print(f"\n Paths: {n_found}/{n_total} exist ({n_found/n_total*100:.1f}%)") + if len(missing) > 0: + by_type = missing["path_type"].value_counts().to_dict() + print(f" Missing by type: {by_type}") + + # Save run config + config_path = os.path.join(output_dir, "_run_config.json") + with open(config_path, "w") as f: + json.dump( + { + "mode": mode, + "dataset": iso_spec.dataset, + "trial_name": iso_spec.trial_name, + "args": vars(args), + }, + f, + indent=2, + default=str, + ) + print(f"\nRun config saved to {config_path}") + + # ── Mode 12: Digital Twin Complete ───────────────────────────────── + elif mode == "digital_twin_complete": + from itrialspace.site.trial_modes import digital_twin_complete + + if not args.dataset: + print("ERROR: --dataset is required for digital_twin_complete mode") + sys.exit(1) + + complete_spec = digital_twin_complete( + dataset=args.dataset, + max_patients=args.max_patients, + all_patients=args.all_patients, + label=args.iso_label, + diameter_min=args.diameter_min, + diameter_max=args.diameter_max, + seed=args.seed, + ) + + print(f"\n{'='*60}") + print(f"Building: {complete_spec.trial_name}") + print(f" dataset={complete_spec.dataset}, seed={complete_spec.seed}") + if complete_spec.max_patients: + print(f" max_patients={complete_spec.max_patients}") + else: + print(" all_patients=True") + print(f"{'='*60}") + + t0 = time.time() + manifest = builder.build_digital_twin_complete(complete_spec, verbose=True) + elapsed = time.time() - t0 + + output_dir = args.output_dir + os.makedirs(output_dir, exist_ok=True) + csv_path = os.path.join(output_dir, f"{complete_spec.trial_name}.csv") + json_path = os.path.join(output_dir, f"{complete_spec.trial_name}.json") + manifest.to_csv(csv_path) + manifest.to_json(json_path) + + print(f"\n Built in {elapsed:.1f}s") + print(f" Saved CSV: {csv_path}") + print(f" Saved JSON: {json_path}") + + summary = manifest.summary() + print(f" Cases: {summary['n_cases']}") + if "n_malignant" in summary: + print(f" Malignant: {summary['n_malignant']}, Benign: {summary['n_benign']}") + + if args.verify_paths: + missing = manifest.verify_paths() + n_total = len(manifest) * 4 + n_found = n_total - len(missing) + print(f"\n Paths: {n_found}/{n_total} exist ({n_found/n_total*100:.1f}%)") + if len(missing) > 0: + by_type = missing["path_type"].value_counts().to_dict() + print(f" Missing by type: {by_type}") + + # Save run config + config_path = os.path.join(output_dir, "_run_config.json") + with open(config_path, "w") as f: + json.dump( + { + "mode": mode, + "dataset": complete_spec.dataset, + "trial_name": complete_spec.trial_name, + "args": vars(args), + }, + f, + indent=2, + default=str, + ) + print(f"\nRun config saved to {config_path}") + + # ── Mode 13: Digital Twin Cross ──────────────────────────────────── + elif mode == "digital_twin_cross": + from itrialspace.site.trial_modes import digital_twin_cross + + if not args.host_dataset: + print("ERROR: --host-dataset is required for digital_twin_cross mode") + sys.exit(1) + if not args.donor_dataset: + print("ERROR: --donor-dataset is required for digital_twin_cross mode") + sys.exit(1) + + cross_spec = digital_twin_cross( + host_dataset=args.host_dataset, + donor_dataset=args.donor_dataset, + max_host_patients=args.max_host_patients, + all_host_patients=args.all_host_patients, + max_donor_patients=args.max_donor_patients, + all_donor_patients=args.all_donor_patients, + max_donor_nodules=args.max_donor_nodules, + donor_transfer_mode=args.donor_transfer_mode, + pairing_policy=args.pairing_policy, + n_hosts_per_donor=args.n_hosts_per_donor, + placement_strategy=args.placement_strategy, + label=args.iso_label, + diameter_min=args.diameter_min, + diameter_max=args.diameter_max, + seed=args.seed, + ) + + print(f"\n{'='*60}") + print(f"Building: {cross_spec.trial_name}") + print(f" host_dataset={cross_spec.host_dataset}, donor_dataset={cross_spec.donor_dataset}") + print(f" donor_transfer_mode={cross_spec.donor_transfer_mode}") + print(f" pairing_policy={cross_spec.pairing_policy}") + print(f" placement_strategy={cross_spec.placement_strategy}") + print(f" seed={cross_spec.seed}") + print(f"{'='*60}") + + t0 = time.time() + manifest = builder.build_digital_twin_cross(cross_spec, verbose=True) + elapsed = time.time() - t0 + + output_dir = args.output_dir + os.makedirs(output_dir, exist_ok=True) + csv_path = os.path.join(output_dir, f"{cross_spec.trial_name}.csv") + json_path = os.path.join(output_dir, f"{cross_spec.trial_name}.json") + manifest.to_csv(csv_path) + manifest.to_json(json_path) + + print(f"\n Built in {elapsed:.1f}s") + print(f" Saved CSV: {csv_path}") + print(f" Saved JSON: {json_path}") + + summary = manifest.summary() + print(f" Cases: {summary['n_cases']}") + if "n_malignant" in summary: + print(f" Malignant: {summary['n_malignant']}, Benign: {summary['n_benign']}") + + if args.verify_paths: + missing = manifest.verify_paths() + n_total = len(manifest) * 4 + n_found = n_total - len(missing) + print(f"\n Paths: {n_found}/{n_total} exist ({n_found/n_total*100:.1f}%)") + if len(missing) > 0: + by_type = missing["path_type"].value_counts().to_dict() + print(f" Missing by type: {by_type}") + + # Save run config + config_path = os.path.join(output_dir, "_run_config.json") + with open(config_path, "w") as f: + json.dump( + { + "mode": mode, + "host_dataset": cross_spec.host_dataset, + "donor_dataset": cross_spec.donor_dataset, + "trial_name": cross_spec.trial_name, + "args": vars(args), + }, + f, + indent=2, + default=str, + ) + print(f"\nRun config saved to {config_path}") + + else: + print(f"Unknown mode: {mode}") + print( + "Available modes: controlled_prevalence, size_detection_curve, " + "location_sensitivity, demographic_strat, counterfactual, " + "cross_dataset, bootstrap_confidence, algorithm_comparison, " + "screening_simulation, multi_nodule, digital_twin_isolation, " + "digital_twin_complete, digital_twin_cross" + ) + sys.exit(1) + + print("\nDone!") + + +def build_parser(): + parser = argparse.ArgumentParser( + description="iTrialSpace Trial Runner — build cohort manifests from trial modes", + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog=__doc__, + ) + parser.add_argument("--mode", required=True, help="Trial mode name") + parser.add_argument( + "--output-dir", default="./output", help="Output directory (default: ./output)" + ) + parser.add_argument("--seed", type=int, default=42, help="Random seed (default: 42)") + parser.add_argument("--template", default="NLST", help="Trial template (default: NLST)") + parser.add_argument( + "--verify-paths", + action="store_true", + default=True, + help="Verify file paths exist (default: True)", + ) + parser.add_argument("--no-verify-paths", dest="verify_paths", action="store_false") + + # Mode-specific arguments + parser.add_argument("--n-cases", type=int, default=500, help="Number of cases") + parser.add_argument("--prevalence", type=float, default=0.05, help="Malignancy prevalence") + parser.add_argument("--label", type=int, default=1, help="Label filter (0=benign, 1=malignant)") + parser.add_argument( + "--n-per-bucket", type=int, default=100, help="Cases per size bucket (mode 2)" + ) + parser.add_argument("--n-per-lobe", type=int, default=100, help="Cases per lobe (mode 3)") + parser.add_argument("--n-per-stratum", type=int, default=200, help="Cases per stratum (mode 4)") + parser.add_argument("--diam-min", type=float, default=6.0, help="Min diameter mm (mode 3)") + parser.add_argument("--diam-max", type=float, default=15.0, help="Max diameter mm (mode 3)") + parser.add_argument( + "--vary-param", default="malignancy_prevalence", help="Parameter to vary (mode 5)" + ) + parser.add_argument("--values", default=None, help="Comma-separated values to vary (mode 5)") + parser.add_argument("--datasets", default=None, help="Comma-separated dataset names (mode 6)") + parser.add_argument( + "--n-bootstrap", type=int, default=100, help="Bootstrap replicates (mode 7)" + ) + parser.add_argument("--n-rounds", type=int, default=3, help="Screening rounds (mode 9)") + parser.add_argument( + "--n-cases-per-round", type=int, default=500, help="Cases per round (mode 9)" + ) + parser.add_argument( + "--prevalence-decay", type=float, default=0.7, help="Prevalence decay (mode 9)" + ) + parser.add_argument( + "--multi-nodule-fraction", + type=float, + default=0.25, + help="Fraction of multi-nodule cases (mode 10, default: 0.25)", + ) + parser.add_argument( + "--companion-strategy", + default="all_companions", + help="Companion strategy (mode 10, default: all_companions)", + ) + + # Mode 11/12: Digital twin arguments + parser.add_argument( + "--dataset", default=None, help="Source dataset name (mode 11/12, e.g. DLCS24)" + ) + iso_group = parser.add_mutually_exclusive_group() + iso_group.add_argument( + "--max-patients", type=int, default=None, help="Max host patients to select (mode 11/12)" + ) + iso_group.add_argument( + "--all-patients", + action="store_true", + default=False, + help="Use all eligible patients (mode 11/12)", + ) + parser.add_argument( + "--max-nodules-per-patient", + type=int, + default=None, + help="Cap isolation cases per patient (mode 11)", + ) + parser.add_argument( + "--iso-label", + type=int, + default=None, + help="Filter nodules by label (mode 11/12/13, 0=benign, 1=malignant, None=any)", + ) + parser.add_argument( + "--diameter-min", type=float, default=None, help="Min nodule diameter mm (mode 11/12/13)" + ) + parser.add_argument( + "--diameter-max", type=float, default=None, help="Max nodule diameter mm (mode 11/12/13)" + ) + + # Mode 13: Digital twin cross arguments + parser.add_argument( + "--host-dataset", default=None, help="Host anatomy dataset (mode 13, e.g. DLCS24)" + ) + parser.add_argument( + "--donor-dataset", default=None, help="Donor nodule dataset (mode 13, e.g. LUNA25)" + ) + cross_host_group = parser.add_mutually_exclusive_group() + cross_host_group.add_argument( + "--max-host-patients", type=int, default=None, help="Max host patients (mode 13)" + ) + cross_host_group.add_argument( + "--all-host-patients", + action="store_true", + default=False, + help="Use all eligible host patients (mode 13)", + ) + cross_donor_group = parser.add_mutually_exclusive_group() + cross_donor_group.add_argument( + "--max-donor-patients", type=int, default=None, help="Max donor patients (mode 13)" + ) + cross_donor_group.add_argument( + "--all-donor-patients", + action="store_true", + default=False, + help="Use all eligible donor patients (mode 13)", + ) + parser.add_argument( + "--max-donor-nodules", type=int, default=None, help="Max total donor nodules (mode 13)" + ) + parser.add_argument( + "--donor-transfer-mode", + default="single", + choices=["single", "complete"], + help="Donor transfer mode (mode 13, default: single)", + ) + parser.add_argument( + "--pairing-policy", + default="one_to_one", + choices=["one_to_one", "one_to_many_hosts", "donor_patient_complete"], + help="Pairing policy (mode 13, default: one_to_one)", + ) + parser.add_argument( + "--n-hosts-per-donor", + type=int, + default=3, + help="Hosts per donor for one_to_many_hosts (mode 13, default: 3)", + ) + parser.add_argument( + "--placement-strategy", + default="profile_faithful_transfer", + choices=["profile_faithful_transfer", "host_constrained_transfer"], + help="Placement strategy (mode 13, default: profile_faithful_transfer)", + ) + return parser + + +def main(argv=None): + """Console-script entry point (``its-trials``).""" + parser = build_parser() + args = parser.parse_args(argv) + run(args) + + +if __name__ == "__main__": + main() diff --git a/itrialspace/src/itrialspace/utils/__init__.py b/itrialspace/src/itrialspace/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/itrialspace/src/itrialspace/utils/__pycache__/__init__.cpython-310.pyc b/itrialspace/src/itrialspace/utils/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0640416f91fbd01d4f0cbc586e54bd3bdacd0d39 Binary files /dev/null and b/itrialspace/src/itrialspace/utils/__pycache__/__init__.cpython-310.pyc differ