AnonymousUN commited on
Commit
da53a66
Β·
verified Β·
1 Parent(s): f4d2622

Add full itrialspace framework, including code, slurm scripts, and configs

Browse files

- Add core trial simulation logic, configuration files (`datasets.yaml`, `trials.yaml`), and command-line interfaces.
- Add infrastructure scripts for Slurm cluster job submission across multiple trial modes.
- Implement VLM evaluation modules, retrieval mechanisms, and synthetic mask insertion tools.
- Include pre-trained model weights for NoMAISI-based synthesis under `nodmaisi_synth/models/`.
- Add documentation, environmental setups (`environment.yml`, `requirements.lock.txt`), and project metadata (`pyproject.toml`).

This view is limited to 50 files because it contains too many changes. Β  See raw diff
Files changed (50) hide show
  1. itrialspace/.dockerignore +39 -0
  2. itrialspace/.env +35 -0
  3. itrialspace/.env.example +51 -0
  4. itrialspace/.gitignore +79 -0
  5. itrialspace/.pre-commit-config.yaml +31 -0
  6. itrialspace/CHANGELOG.md +34 -0
  7. itrialspace/CODE_OF_CONDUCT.md +32 -0
  8. itrialspace/CONTRIBUTING.md +74 -0
  9. itrialspace/LICENSE +20 -0
  10. itrialspace/README.md +336 -0
  11. itrialspace/blinded_doc/architecture.md +65 -0
  12. itrialspace/blinded_doc/configuration.md +79 -0
  13. itrialspace/blinded_doc/data.md +62 -0
  14. itrialspace/blinded_doc/dataset_card.md +250 -0
  15. itrialspace/blinded_doc/index.md +32 -0
  16. itrialspace/blinded_doc/installation.md +179 -0
  17. itrialspace/blinded_doc/nodulemap.md +286 -0
  18. itrialspace/blinded_doc/pipeline.md +36 -0
  19. itrialspace/blinded_doc/quickstart.md +74 -0
  20. itrialspace/blinded_doc/reproducibility.md +24 -0
  21. itrialspace/blinded_doc/retriever.md +246 -0
  22. itrialspace/blinded_doc/running_the_pipeline.md +277 -0
  23. itrialspace/blinded_doc/trial_modes.md +31 -0
  24. itrialspace/blinded_doc/vlm_eval.md +296 -0
  25. itrialspace/blinded_doc/vlm_eval_implementation.md +265 -0
  26. itrialspace/blinded_doc/walkthrough_mode1.md +170 -0
  27. itrialspace/configs/datasets.example.yaml +35 -0
  28. itrialspace/configs/features.yaml +111 -0
  29. itrialspace/configs/integration.example.yaml +76 -0
  30. itrialspace/configs/mask_inserter.example.yaml +113 -0
  31. itrialspace/configs/paths.example.yaml +61 -0
  32. itrialspace/configs/trials.yaml +157 -0
  33. itrialspace/docker/Dockerfile +35 -0
  34. itrialspace/docker/Dockerfile.gpu +51 -0
  35. itrialspace/docker/itrialspace.def +68 -0
  36. itrialspace/environment.lock.yml +18 -0
  37. itrialspace/environment.yml +30 -0
  38. itrialspace/infra/slurm/README.md +47 -0
  39. itrialspace/infra/slurm/_gen_caselist.py +37 -0
  40. itrialspace/infra/slurm/env.sh +88 -0
  41. itrialspace/infra/slurm/mask_inserter/mode10_insert_masks.sub +84 -0
  42. itrialspace/infra/slurm/mask_inserter/mode10_insert_masks_array.sub +101 -0
  43. itrialspace/infra/slurm/mask_inserter/mode11_insert_masks.sub +85 -0
  44. itrialspace/infra/slurm/mask_inserter/mode11_insert_masks_array.sub +103 -0
  45. itrialspace/infra/slurm/mask_inserter/mode12_insert_masks.sub +84 -0
  46. itrialspace/infra/slurm/mask_inserter/mode12_insert_masks_array.sub +102 -0
  47. itrialspace/infra/slurm/mask_inserter/mode13_insert_masks.sub +84 -0
  48. itrialspace/infra/slurm/mask_inserter/mode13_insert_masks_array.sub +103 -0
  49. itrialspace/infra/slurm/mask_inserter/mode1_insert_masks.sub +95 -0
  50. itrialspace/infra/slurm/mask_inserter/mode1_insert_masks_array.sub +108 -0
itrialspace/.dockerignore ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .git
2
+ .github
3
+ **/__pycache__
4
+ *.py[cod]
5
+ *.egg-info
6
+ .pytest_cache
7
+ .ruff_cache
8
+ .ipynb_checkpoints
9
+
10
+ # Never copy heavy/host-specific artifacts into the image
11
+ models/
12
+ weights/
13
+ logs/
14
+ *.log
15
+ *.out
16
+ *.err
17
+ *_artifacts/
18
+ outputs/
19
+ generated_cts/
20
+ inserted_masks/
21
+ paper_analysis/
22
+ *.pt
23
+ *.pth
24
+ *.ckpt
25
+ *.nii
26
+ *.nii.gz
27
+ *.parquet
28
+
29
+ # Local config & secrets
30
+ .env
31
+ configs/datasets.yaml
32
+ configs/paths.yaml
33
+ configs/integration.yaml
34
+ configs/mask_inserter.yaml
35
+ configs/eval.yaml
36
+
37
+ docs/_build/
38
+ .venv/
39
+ venv/
itrialspace/.env ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # iTrialSpace environment β€” this machine (Duke DRCC). Gitignored; edit freely.
2
+ # Read automatically by infra/slurm/env.sh and itrialspace.config.settings.
3
+
4
+ # ── Data root (inputs: raw_ct/ masks/ profiles/ meta/) ──────────────────────
5
+ ITRIALSPACE_DATA_DIR=/path/to/iTrialSpace
6
+
7
+ # ── Output root (generated: manifests/ inserted_masks/ generated_cts/ ...) ──
8
+ # Defaults to ITRIALSPACE_DATA_DIR. Uncomment to send all outputs elsewhere:
9
+ ITRIALSPACE_OUTPUT_DIR=/path/to/outputs_iTrialSpace
10
+
11
+ # ── NoduleMap build artifacts (embeddings, edges, metadata) ─────────────────
12
+ # Default would be $ITRIALSPACE_OUTPUT_DIR/nodulemap_artifacts; set explicitly here:
13
+ NODULEMAP_ARTIFACTS=/path/to/outputs_iTrialSpace/nodulemap_artifacts
14
+
15
+ # ── Conda env used by SLURM scripts ─────────────────────────────────────────
16
+ ITRIALSPACE_CONDA_ENV=itrialspace
17
+
18
+ # ── Service ports ────────────────────────────────────────────────────────────
19
+ NODULEMAP_PORT=8422
20
+ RETRIEVER_API_PORT=8421
21
+ RETRIEVER_UI_PORT=8501
22
+
23
+ # ── SLURM partitions (Duke DRCC) ────────────────────────────────────────────
24
+ SLURM_PARTITION_GPU=vram48
25
+ SLURM_PARTITION_CPU=defq
26
+
27
+ # ── NodMAISI synthesis model weights (Step 3 of the pipeline) ───────────────
28
+ NODMAISI_MODELS_DIR=/path/to/nodmaisi_synth/models
29
+
30
+ # ── Optional CADe/CADx external dependencies (see docs) ─────────────────────
31
+ # EVAL_WEIGHTS_DIR=/path/to/weights
32
+ # EVAL_CONFIGS_DIR=/path/to/configs
33
+
34
+ # HuggingFace access token (gitignored; local only). Clear before sharing.
35
+ HF_TOKEN= "Put your HuggingFace token here if you want to use HuggingFace APIs for model loading, dataset access, etc. Clear this before sharing!"
itrialspace/.env.example ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # iTrialSpace environment configuration β€” copy to `.env` and edit for your machine.
2
+ # These variables drive ALL path resolution; nothing is hardcoded in code or configs.
3
+ #
4
+ # cp .env.example .env
5
+ #
6
+ # `itrialspace.config.settings` reads these (falling back to the defaults shown).
7
+
8
+ # ── Data root ────────────────────────────────────────────────────────────────
9
+ # Single base directory holding the unified data layout:
10
+ # $ITRIALSPACE_DATA_DIR/{raw_ct,masks,profiles,meta,manifests,...}
11
+ # Default: ~/.itrialspace/data
12
+ ITRIALSPACE_DATA_DIR=/path/to/iTrialSpace/data
13
+
14
+ # Repo root (auto-detected from the installed package if unset).
15
+ # ITRIALSPACE_ROOT=/home/you/itrialspace
16
+
17
+ # Directory for generated outputs (manifests, inserted masks, synthetic CTs, reports).
18
+ # Default: $ITRIALSPACE_DATA_DIR
19
+ # ITRIALSPACE_OUTPUT_DIR=/path/to/iTrialSpace/outputs
20
+
21
+ # ── Build artifacts ──────────────────────────────────────────────────────────
22
+ # Where NoduleMap build artifacts (embeddings, edge graphs, metadata) are written β€”
23
+ # and read back from when serving. Set this to point the server at pre-built artifacts,
24
+ # or to choose where `its-nodulemap build/edges` (and rebuild_nodulemap.sub) save them.
25
+ # Default: $ITRIALSPACE_OUTPUT_DIR/nodulemap_artifacts
26
+ # NODULEMAP_ARTIFACTS=/path/to/iTrialSpace/outputs/nodulemap_artifacts
27
+ # NODULEMAP_EXPORTS=/path/to/iTrialSpace/outputs/nodulemap_exports # neighbour/donor exports
28
+
29
+ # ── HuggingFace access token (VLM eval: MedGemma is gated; some LLaVA-Med too) ──
30
+ # Create one at https://huggingface.co/settings/tokens and accept each gated model's
31
+ # license. Read by itrialspace.config.settings.hf_token() and passed to the model
32
+ # loaders β€” NEVER hardcoded in code. Leave blank for public-only models (BiomedCLIP
33
+ # needs no token). When sharing this repo, clear this value; each user supplies their
34
+ # own. (Both HF_TOKEN and the legacy HUGGING_FACE_HUB_TOKEN are honoured.)
35
+ # HF_TOKEN=
36
+
37
+ # ── Model weights (NOT bundled β€” see docs/installation.md) ──────────────────
38
+ # NodMAISI synthesis model weights (autoencoder.pt, diffusion_unet.pt, controlnet *.pt)
39
+ # NODMAISI_MODELS_DIR=/path/to/nodmaisi/models
40
+
41
+ # ── Service ports ────────────────────────────────────────────────────────────
42
+ NODULEMAP_PORT=8422
43
+ RETRIEVER_API_PORT=8421
44
+ RETRIEVER_UI_PORT=8501
45
+
46
+ # ── HPC / SLURM (only used by infra/slurm/*) ────────────────────────────────
47
+ ITRIALSPACE_CONDA_ENV=itrialspace
48
+ SLURM_PARTITION_GPU=vram48
49
+ SLURM_PARTITION_CPU=defq
50
+ # SLURM_ACCOUNT=
51
+ # CONDA_PROFILE=/cm/shared/apps/miniconda/etc/profile.d/conda.sh
itrialspace/.gitignore ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ── Python ──────────────────────────────────────────────────────────────────
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.egg-info/
5
+ *.egg
6
+ .eggs/
7
+ build/
8
+ dist/
9
+ .installed.cfg
10
+ .Python
11
+ .venv/
12
+ venv/
13
+ env/
14
+
15
+ # ── Caches / tooling ────────────────────────────────────────────────────────
16
+ .pytest_cache/
17
+ .ruff_cache/
18
+ .mypy_cache/
19
+ .ipynb_checkpoints/
20
+ .coverage
21
+ htmlcov/
22
+
23
+ # ── Model weights (host externally; see docs/installation.md) ───────────────
24
+ *.pt
25
+ *.pth
26
+ *.ckpt
27
+ *.safetensors
28
+ models/
29
+ weights/
30
+ # …but DO track source-code packages named "models" (model *adapters*, not weights).
31
+ !src/itrialspace/evaluation/vlm_eval/models/
32
+ !src/itrialspace/evaluation/vlm_eval/models/*.py
33
+
34
+ # ── Logs & SLURM output ─────────────────────────────────────────────────────
35
+ logs/*
36
+ !logs/.gitkeep
37
+ *.log
38
+ *.out
39
+ *.err
40
+ slurm-*.out
41
+
42
+ # ── Generated data / artifacts (regenerate; not source) ─────────────────────
43
+ *_artifacts/
44
+ nodulemap_artifacts/
45
+ nodulemap_exports/
46
+ exports/
47
+ outputs/
48
+ generated_cts/
49
+ inserted_masks/
50
+ manifests/
51
+ paper_analysis/
52
+
53
+ # ── Large medical data (never committed; use ITRIALSPACE_DATA_DIR) ──────────
54
+ *.nii
55
+ *.nii.gz
56
+ *.parquet
57
+ *.csv
58
+
59
+ # ── Local config & secrets ──────────────────────────────────────────────────
60
+ # Path-sensitive configs are shipped as *.example.yaml; the resolved local copies
61
+ # (datasets.yaml, paths.yaml, integration.yaml, mask_inserter.yaml, eval.yaml) are
62
+ # user-specific and ignored. Non-path configs (trials.yaml, features.yaml) ARE committed.
63
+ .env
64
+ configs/datasets.yaml
65
+ configs/paths.yaml
66
+ configs/integration.yaml
67
+ configs/mask_inserter.yaml
68
+ configs/eval.yaml
69
+
70
+ # ── Study / manuscript layer (not part of the public release) ───────────────
71
+ # Paper-specific analysis orchestration + narrative. It *uses* the public engine
72
+ # (itrialspace.evaluation.vlm_eval.eval_analysis) but is kept private.
73
+ studies/
74
+
75
+ # ── OS / editor ─────────────────────────────────────────────────────────────
76
+ .DS_Store
77
+ *.swp
78
+ .idea/
79
+ .vscode/
itrialspace/.pre-commit-config.yaml ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ repos:
2
+ - repo: https://github.com/pre-commit/pre-commit-hooks
3
+ rev: v4.6.0
4
+ hooks:
5
+ - id: trailing-whitespace
6
+ - id: end-of-file-fixer
7
+ - id: check-yaml
8
+ exclude: ^infra/slurm/ # SLURM headers contain non-standard directives
9
+ - id: check-added-large-files
10
+ args: ["--maxkb=2048"]
11
+ - id: check-merge-conflict
12
+ - id: mixed-line-ending
13
+
14
+ - repo: https://github.com/astral-sh/ruff-pre-commit
15
+ rev: v0.4.10
16
+ hooks:
17
+ - id: ruff
18
+ args: ["--fix"]
19
+
20
+ - repo: https://github.com/psf/black
21
+ rev: 24.4.2
22
+ hooks:
23
+ - id: black
24
+
25
+ - repo: local
26
+ hooks:
27
+ - id: check-portability
28
+ name: check for hardcoded absolute paths
29
+ entry: python tools/check_portability.py
30
+ language: system
31
+ pass_filenames: false
itrialspace/CHANGELOG.md ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Changelog
2
+
3
+ All notable changes to iTrialSpace are documented here. The format is based on
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres
5
+ to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
+
7
+ ## [Unreleased]
8
+
9
+ ### Added
10
+ - Public-release monorepo layout: single installable `itrialspace` distribution
11
+ (`src/` layout) with optional-dependency extras (`imaging`, `web`, `synthesis`,
12
+ `vlm`, `eval`, `dev`, `all`).
13
+ - Configuration/portability layer (`itrialspace.config.settings`): all paths are
14
+ resolved from `ITRIALSPACE_DATA_DIR` and friends β€” no hardcoded absolute paths.
15
+ - Console entry points: `its`, `its-insert`, `its-trials`, `its-nodulemap`,
16
+ `its-retriever`.
17
+ - Packaging, container, and CI tooling: `pyproject.toml`, `environment.yml`,
18
+ `docker/Dockerfile`, GitHub Actions CI, pre-commit, portability guard.
19
+ - Consolidated documentation under `docs/`.
20
+
21
+ ### Changed
22
+ - Components re-namespaced under `itrialspace.*` (was top-level `itrialspace_mask_inserter`,
23
+ `nodulemap`, `retriever`, `site_trials`, `nodmaisi_synth`, `vlm_evaluation`).
24
+ - CADe/CADx evaluation moved to optional `itrialspace.evaluation` extra; external model
25
+ dependencies documented rather than bundled.
26
+
27
+ ### Removed
28
+ - Large artifacts excluded from source control (model weights, `paper_analysis/`, logs,
29
+ generated outputs) β€” see `docs/installation.md` and `docs/data.md` for how to obtain them.
30
+ - Experimental `agent` (`itrialagent`) orchestration layer β€” never run or integrated in
31
+ the research repo; the pipeline is driven directly via the CLI and SLURM scripts.
32
+
33
+ ## [0.1.0] β€” research snapshot
34
+ - Original research implementation (pre-public-release). Preserved at the source repo.
itrialspace/CODE_OF_CONDUCT.md ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and maintainers pledge to make participation in our
6
+ community a harassment-free experience for everyone, regardless of age, body size,
7
+ visible or invisible disability, ethnicity, sex characteristics, gender identity and
8
+ expression, level of experience, education, socio-economic status, nationality,
9
+ personal appearance, race, religion, or sexual identity and orientation.
10
+
11
+ ## Our Standards
12
+
13
+ Examples of behavior that contributes to a positive environment:
14
+
15
+ - Demonstrating empathy and kindness toward other people
16
+ - Being respectful of differing opinions, viewpoints, and experiences
17
+ - Giving and gracefully accepting constructive feedback
18
+ - Accepting responsibility and apologizing to those affected by our mistakes
19
+
20
+ Unacceptable behavior includes harassment, trolling, insulting or derogatory
21
+ comments, public or private harassment, and publishing others' private information
22
+ without explicit permission.
23
+
24
+ ## Enforcement
25
+
26
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported
27
+ to the project maintainers. All complaints will be reviewed and investigated promptly
28
+ and fairly.
29
+
30
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.1.
31
+
32
+ [homepage]: https://www.contributor-covenant.org
itrialspace/CONTRIBUTING.md ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Contributing to iTrialSpace
2
+
3
+ Thanks for your interest in improving iTrialSpace! This guide covers the development
4
+ workflow, coding standards, and how to extend the framework.
5
+
6
+ ## Development setup
7
+
8
+ ```bash
9
+ git clone <repo-url>
10
+ cd itrialspace
11
+
12
+ # Create the environment (conda recommended for the imaging/ML stack)
13
+ conda env create -f environment.yml
14
+ conda activate itrialspace
15
+
16
+ # Editable install with dev tooling
17
+ pip install -e ".[dev]"
18
+
19
+ # Configure paths (copy and edit)
20
+ cp .env.example .env
21
+
22
+ # Install git hooks
23
+ pre-commit install
24
+ ```
25
+
26
+ ## Project layout
27
+
28
+ The repo is a single installable package under `src/itrialspace/`. See
29
+ [docs/architecture.md](docs/architecture.md) for the full component map.
30
+
31
+ | Path | Purpose |
32
+ |------|---------|
33
+ | `src/itrialspace/{core,io,index,query,site}` | Nodule index, querying, trial specs |
34
+ | `src/itrialspace/trials` | Trial manifest runner (the 13 modes) |
35
+ | `src/itrialspace/mask_inserter` | Voxel-level nodule mask insertion |
36
+ | `src/itrialspace/synthesis` | NodMAISI CT synthesis (model weights external) |
37
+ | `src/itrialspace/apps/{nodulemap,retriever}` | Interactive web tools |
38
+ | `src/itrialspace/evaluation/vlm_eval` | Vision-language model evaluation |
39
+ | `src/itrialspace/evaluation/{cade,cadx}` | Optional CADe/CADx eval (external deps) |
40
+ | `infra/slurm` | HPC submission scripts (cluster-portable via `env.sh`) |
41
+ | `configs/` | Example configs (`*.example.yaml`) |
42
+ | `tests/` | Unit tests (run with no external data) |
43
+
44
+ ## Coding standards
45
+
46
+ - **Formatting/linting**: `black` + `ruff` (run automatically via pre-commit).
47
+ - **No hardcoded paths**: never write `/home/...` or `/scratch/...` in code, configs, or
48
+ scripts. Resolve paths through `itrialspace.config.settings` or env vars. CI enforces this
49
+ via `tools/check_portability.py`.
50
+ - **NIfTI orientation**: always canonicalize to RAS+ (`nib.as_closest_canonical()`).
51
+ - **Determinism**: seed with `42` and derive per-case seeds deterministically.
52
+
53
+ ## Running checks locally
54
+
55
+ ```bash
56
+ ruff check . && black --check .
57
+ pytest -m "not full_volume" # unit tests, no external data
58
+ python tools/check_portability.py # no stray absolute paths
59
+ pre-commit run --all-files
60
+ ```
61
+
62
+ ## Extending the framework
63
+
64
+ - **New dataset**: see [docs/data.md](docs/data.md) and `src/itrialspace/io/adapters/`.
65
+ - **New trial mode**: add a factory in `src/itrialspace/site/trial_modes.py` and wire it
66
+ into `src/itrialspace/trials/run_trial.py`.
67
+ - **New VLM**: add a wrapper in `src/itrialspace/evaluation/vlm_eval/models/`.
68
+
69
+ ## Pull requests
70
+
71
+ 1. Branch from `main`.
72
+ 2. Keep changes focused; update docs and tests.
73
+ 3. Ensure CI passes (lint + tests + portability gate).
74
+ 4. Describe the change and link any related issue.
itrialspace/LICENSE ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ LICENSE β€” PLACEHOLDER (TO BE CONFIRMED BEFORE PUBLIC RELEASE)
2
+ ============================================================
3
+
4
+ The license for iTrialSpace has not yet been finalized.
5
+
6
+ Until a license is chosen and this file is replaced, all rights are reserved by
7
+ the authors. Do not redistribute.
8
+
9
+ Recommended options under consideration:
10
+ - Apache-2.0 (permissive + explicit patent grant)
11
+ - MIT (simplest, most permissive)
12
+ - BSD-3-Clause (permissive + non-endorsement clause)
13
+
14
+ ACTION REQUIRED: Replace the entire contents of this file with the full text of
15
+ the chosen license, update `license` in pyproject.toml and CITATION.cff, and add
16
+ SPDX headers if desired.
17
+
18
+ Note on data: source CT datasets (DLCS24, LUNA16, LUNA25, LUNGx, LNDb, NSCLC-Radiomics,
19
+ etc.) carry their own licenses and are NOT redistributed by this repository. See
20
+ docs/data.md.
itrialspace/README.md ADDED
@@ -0,0 +1,336 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!-- BLINDED COPY for double-blind peer review β€” author, institution, and repository-identifying information removed. Do not use for attribution. -->
2
+
3
+ <!-- markdownlint-disable MD033 MD041 -->
4
+ <div align="center">
5
+
6
+ # iTrialSpace
7
+
8
+ **A Synthetic Imaging Clinical-Trial Engine for lung-CT AI evaluation.**
9
+
10
+ *Specify the cohort you need β€” then manufacture anatomically grounded synthetic CTs to match,
11
+ and evaluate detectors and vision-language models under controlled, one-variable-at-a-time conditions.*
12
+
13
+ </div>
14
+
15
+ > ⚠️ **License pending.** The license is being finalized β€” see [`LICENSE`](LICENSE). Please do
16
+ > not redistribute until it is confirmed. **Research use only β€” not for clinical use.**
17
+
18
+ ---
19
+
20
+ ## What it is
21
+
22
+ iTrialSpace turns medical-imaging AI evaluation from *"find more data"* into *"specify the data
23
+ you need."* It harmonizes **13,140 nodule profiles** from **7 public lung-CT datasets**, plans
24
+ virtual clinical-trial cohorts across **13 trial modes**, inserts donor nodule masks into real
25
+ host anatomy, synthesizes CT volumes with a ControlNet-conditioned diffusion model
26
+ (**NodMAISI**), and evaluates **vision-language models (VLMs)** under systematically controlled
27
+ conditions.
28
+
29
+ **Why it exists.** Public lung-screening datasets are each narrow in their own way β€” some are
30
+ enriched for heavy smokers, some lack malignancy labels, some contain only large cancers β€” so AI
31
+ models end up tested on data that under-represents where they fail. iTrialSpace lets you declare a
32
+ cohort by its *statistical properties* (prevalence, size distribution, lobe distribution,
33
+ demographics) and generates synthetic CTs to match, enabling controlled experiments that fixed
34
+ retrospective datasets cannot support.
35
+
36
+ **What this repository is.** A clean, installable, **code-only** monorepo. Source CT *images* and
37
+ trained model *weights* are not redistributed here (they carry their own licenses and are large);
38
+ the derived synthetic data is released separately as a dataset (see [Data & release](#7-data--release)).
39
+
40
+ ---
41
+
42
+ ## Track β€” how to read this README
43
+
44
+ A guided path from zero to a full evaluation. Each row is a section below; follow them in order,
45
+ or jump to what you need.
46
+
47
+ | # | Section | What you'll get |
48
+ |---|---------|-----------------|
49
+ | 1 | [Highlights](#1-highlights) | The capabilities at a glance |
50
+ | 2 | [Architecture](#2-architecture) | The five-stage engine and how the pieces connect |
51
+ | 3 | [Installation](#3-installation) | Environment, the package, and the extras matrix |
52
+ | 4 | [Configuration](#4-configuration) | The one env var that makes it run anywhere |
53
+ | 5 | [Quickstart](#5-quickstart) | Install β†’ configure β†’ smoke-test in five commands |
54
+ | 6 | [The end-to-end pipeline](#6-the-end-to-end-pipeline) | index β†’ trials β†’ masks β†’ synthesis β†’ evaluation |
55
+ | 7 | [Data & release](#7-data--release) | The 7 datasets, what is shared, how to assemble it |
56
+ | 8 | [Trial modes](#8-trial-modes) | The 13 cohort designs you can synthesize |
57
+ | 9 | [VLM evaluation (end to end)](#9-vlm-evaluation-end-to-end) | Build β†’ run β†’ analyze, locally or on SLURM |
58
+ | 10 | [Reproducibility](#10-reproducibility) | Frozen splits, the reporting convention, checksums |
59
+ | 11 | [Apps: NoduleMap & Retriever](#11-apps-nodulemap--retriever) | Explore and search the nodule space |
60
+ | 12 | [Command reference](#12-command-reference) | Console scripts and module entry points |
61
+ | 13 | [Project layout](#13-project-layout) | Where everything lives |
62
+ | 14 | [Citation, contributing, license](#14-citation-contributing-license) | How to cite and contribute |
63
+
64
+ ---
65
+
66
+ ## 1. Highlights
67
+
68
+ - **Cohort-by-specification.** Plan trials by prevalence, size, lobe, and demographics β€” not by
69
+ whatever a retrospective dataset happens to contain.
70
+ - **Anatomically grounded synthesis.** Donor nodule masks are pasted into real host lung anatomy
71
+ and rendered by **NodMAISI**, a ControlNet-conditioned diffusion model.
72
+ - **13 trial modes**, from controlled-prevalence and size/location sensitivity curves to digital
73
+ twins of real patients.
74
+ - **Zero-shot VLM evaluation** β€” BiomedCLIP, LLaVA-Med, and MedGemma across 3 clinical tasks Γ—
75
+ 4 spatial-guidance conditions, on synthetic and real CT.
76
+ - **Portable by construction.** All paths resolve from a single env var; the same code runs on a
77
+ laptop, a workstation, or an HPC cluster. A CI portability gate enforces it.
78
+ - **Reproducible reporting.** Frozen, checksummed evaluation splits and a documented reporting
79
+ convention keep every published number tied to an exact, verifiable case set.
80
+
81
+ ---
82
+
83
+ ## 2. Architecture
84
+
85
+ ```
86
+ itrialspace β†’ trials β†’ mask_inserter β†’ synthesis β†’ evaluation
87
+ (nodule index + (cohort (donor mask (NodMAISI (VLM
88
+ query + features) manifests) β†’ host anatomy) CT volumes) zero-shot)
89
+ β”‚
90
+ β”œβ”€ nodulemap β€” interactive embedding-graph explorer
91
+ └─ retriever β€” faceted search, similarity & donor matching + CT viewer
92
+ ```
93
+
94
+ One installable package, `itrialspace`, with sub-packages for each stage. Configuration, I/O, and
95
+ path resolution are centralized so nothing hardcodes a machine-specific path. Full component map:
96
+ [blinded_doc/architecture.md](blinded_doc/architecture.md).
97
+
98
+ ---
99
+
100
+ ## 3. Installation
101
+
102
+ ```bash
103
+ # 1) Environment (conda/mamba)
104
+ conda env create -f environment.yml && conda activate itrialspace
105
+
106
+ # 2) Install the package with the extras you need
107
+ pip install -e ".[all]" # or a subset β€” see the matrix
108
+ ```
109
+
110
+ **Extras matrix**
111
+
112
+ | Extra | Installs | For |
113
+ |-------|----------|-----|
114
+ | *(base)* | pandas, numpy, pyyaml | Index, query, trial planning |
115
+ | `imaging` | nibabel, scipy, SimpleITK | Mask insertion, NIfTI handling |
116
+ | `web` | fastapi, streamlit, faiss, umap | NoduleMap + Retriever UIs |
117
+ | `synthesis` | monai, (torch) | NodMAISI CT synthesis ΒΉ |
118
+ | `vlm` | transformers, accelerate, open_clip | VLM evaluation ΒΉ |
119
+ | `dev` | pytest, ruff, black, pre-commit | Development |
120
+ | `all` | imaging + web + vlm + dev | Everything bundled |
121
+
122
+ ΒΉ PyTorch is platform-specific β€” install it per [blinded_doc/installation.md](blinded_doc/installation.md).
123
+ A `docker/Dockerfile` is provided for a containerized setup.
124
+
125
+ ---
126
+
127
+ ## 4. Configuration
128
+
129
+ Everything is driven by environment variables (loaded from a gitignored `.env`); nothing is
130
+ hardcoded.
131
+
132
+ ```bash
133
+ cp .env.example .env # then edit:
134
+ # ITRIALSPACE_DATA_DIR β†’ the dataset root (raw_ct/ masks/ profiles/ …)
135
+ # ITRIALSPACE_OUTPUT_DIR β†’ where generated artifacts go (default: = data dir)
136
+ # HF_TOKEN β†’ HuggingFace token for gated VLMs (kept local; never committed)
137
+ ```
138
+
139
+ Any config YAML may reference these with `${VAR}` interpolation. `its config` prints the resolved
140
+ paths. Details: [blinded_doc/configuration.md](blinded_doc/configuration.md).
141
+
142
+ ---
143
+
144
+ ## 5. Quickstart
145
+
146
+ ```bash
147
+ conda activate itrialspace
148
+ pip install -e ".[all]"
149
+ cp .env.example .env # set ITRIALSPACE_DATA_DIR (+ HF_TOKEN for VLMs)
150
+
151
+ pytest -m "not full_volume" # unit tests β€” no external data needed
152
+ its config # verify resolved paths
153
+ its index stats # build the nodule index + print stats (needs profiles/)
154
+ ```
155
+
156
+ A guided first cohort is in [blinded_doc/walkthrough_mode1.md](blinded_doc/walkthrough_mode1.md).
157
+
158
+ ---
159
+
160
+ ## 6. The end-to-end pipeline
161
+
162
+ Five stages take you from a raw nodule index to evaluated models. Each stage is a CLI command and
163
+ a documented module.
164
+
165
+ | Stage | What it does | Entry point |
166
+ |-------|--------------|-------------|
167
+ | **1. Index** | Harmonize 7 datasets into one nodule index with reinsertion features | `its index` |
168
+ | **2. Trials** | Plan cohort **manifests** for the 13 trial modes (donor β†’ host, location, scale) | `its-trials` |
169
+ | **3. Mask insertion** | Paste donor nodule masks into host organ/lobe masks (nodule = label 23) | `its-insert` |
170
+ | **4. Synthesis** | Render CT volumes from the combined masks with **NodMAISI** | `its` (synthesis) |
171
+ | **5. Evaluation** | Score **VLMs** (zero-shot) under controlled conditions | `its-vlm` |
172
+
173
+ Full walkthrough: [blinded_doc/pipeline.md](blinded_doc/pipeline.md) and
174
+ [blinded_doc/running_the_pipeline.md](blinded_doc/running_the_pipeline.md). HPC orchestration scripts are under
175
+ [`infra/slurm/`](infra/slurm/).
176
+
177
+ ---
178
+
179
+ ## 7. Data & release
180
+
181
+ iTrialSpace harmonizes **7 public lung-CT datasets** (13,140 nodule profiles):
182
+
183
+ | Dataset | Nodule profiles | Dataset | Nodule profiles |
184
+ |---------|----------------:|---------|----------------:|
185
+ | LUNA25 | 6,163 | LUNA16 | 1,186 |
186
+ | DLCS24 | 2,487 | LNDbv4 | 768 |
187
+ | IMDCT | 2,032 | NSCLCR | 421 |
188
+ | LUNGx | 83 | **Total** | **13,140** |
189
+
190
+ **What the release ships** (derived artifacts): nodule `profiles/`, `masks/`, cohort
191
+ `manifests/`, combined `inserted_masks/`, the **synthetic CT volumes** (`generated_cts/` β€”
192
+ **44,174** volumes across all 13 modes), and the **VLM evaluation dataset** (`vlm_dataset/` β€”
193
+ **42,858** synthetic and **13,087** real evaluation cases).
194
+
195
+ **What it does not ship.** The real CT **images** are not redistributed β€” download them from each
196
+ provider under their own license and place them under `raw_ct/{DATASET}/`. The data contract,
197
+ counts, ground-truth definitions, and assembly instructions are in
198
+ [blinded_doc/dataset_card.md](blinded_doc/dataset_card.md) and [blinded_doc/data.md](blinded_doc/data.md).
199
+
200
+ ---
201
+
202
+ ## 8. Trial modes
203
+
204
+ Thirteen cohort designs, each producing a manifest you can synthesize and evaluate:
205
+
206
+ | # | Mode | Question it answers |
207
+ |---|------|---------------------|
208
+ | 1 | `controlled_prevalence` | How does performance change with cancer prevalence? |
209
+ | 2 | `size_detection_curve` | Detection sensitivity vs. nodule size (FROC) |
210
+ | 3 | `location_sensitivity` | Detection vs. anatomical lobe |
211
+ | 4 | `demographic_stratification` | Performance across demographic strata |
212
+ | 5 | `counterfactual` | The same patient, with vs. without a nodule |
213
+ | 6 | `cross_dataset` | Generalization across acquisition sources |
214
+ | 7 | `bootstrap_confidence` | Confidence intervals via resampled cohorts |
215
+ | 8 | `algorithm_comparison` | Standardized head-to-head model comparison |
216
+ | 9 | `screening_simulation` | Multi-round screening with prevalence decay |
217
+ | 10 | `multi_nodule_realism` | Impact of companion nodules in context |
218
+ | 11 | `digital_twin_isolation` | Each native nodule isolated within its host anatomy |
219
+ | 12 | `digital_twin_complete` | All native nodules of a scan, reconstructed |
220
+ | 13 | `digital_twin_cross` | Donor nodules placed in cross-patient host anatomy |
221
+
222
+ Details and per-mode parameters: [blinded_doc/trial_modes.md](blinded_doc/trial_modes.md).
223
+
224
+ ---
225
+
226
+ ## 9. VLM evaluation (end to end)
227
+
228
+ Evaluate **BiomedCLIP**, **LLaVA-Med**, and **MedGemma** on three zero-shot tasks β€”
229
+ **presence** (binary), **lobe** (5-class), **size** (4-class) β€” under four image **conditions**
230
+ (`plain`, `bbox`, `contour`, `bbox_contour`), on synthetic and real CT.
231
+
232
+ The whole workflow is **three steps**, identical for a small demo and the full dataset (only the
233
+ paths/env change):
234
+
235
+ ```bash
236
+ # 1) BUILD the 2-D eval dataset (slices + overlays + ground truth)
237
+ python -m itrialspace.evaluation.vlm_eval.build_dataset --manifest … --output-dir … --overlays
238
+ # (real CTs: itrialspace.evaluation.vlm_eval.build_real_dataset)
239
+
240
+ # 2) RUN a model across all conditions Γ— tasks
241
+ python -m itrialspace.evaluation.vlm_eval.runners.run_conditions \
242
+ --model biomedclip --run-all-conditions --dataset-csv …/eval_dataset.csv --output-dir …
243
+
244
+ # 3) ANALYZE β†’ tables, figures, statistics, report.md
245
+ python -m itrialspace.evaluation.vlm_eval.eval_analysis --results … --out analysis/
246
+ ```
247
+
248
+ On a cluster, the same three steps are env-driven SLURM jobs β€”
249
+ `build_dataset.sub β†’ run_vlm.sub β†’ analyze.sub` β€” see
250
+ [infra/slurm/vlm_eval/README.md](infra/slurm/vlm_eval/README.md).
251
+
252
+ The **analysis suite** (`eval_analysis`) auto-discovers whatever models/conditions/tasks are
253
+ present and emits accuracy and Ξ”-vs-baseline tables, per-mode / per-dataset / per-size / per-lobe
254
+ breakdowns, confusion matrices, per-class accuracy, **bootstrap confidence intervals**, **McNemar
255
+ significance**, publication-style figures, and an assembled `report.md`.
256
+
257
+ - User guide: [blinded_doc/vlm_eval.md](blinded_doc/vlm_eval.md)
258
+ - Architecture & module reference: [blinded_doc/vlm_eval_implementation.md](blinded_doc/vlm_eval_implementation.md)
259
+ - Headline results: [blinded_doc/vlm_results.md](blinded_doc/vlm_results.md)
260
+
261
+ ---
262
+
263
+ ## 10. Reproducibility
264
+
265
+ - **Frozen splits.** Each result is reported on a checksummed case list (`vlm_dataset/splits/`):
266
+ `release_v1` (the headline set) and `release_v1_full` (cases scored under all four conditions).
267
+ `splits.json` records counts, SHA-256, and provenance β€” regenerate and the hash must match.
268
+ - **One reporting N.** Accuracy is always computed on the cases scored in *every*
269
+ (model Γ— condition Γ— task), keyed by a stable canonical slice id (not a positional index), so
270
+ all reported numbers are directly comparable.
271
+ - **Determinism & audit trails.** Every synthesis case carries an audit record; see
272
+ [blinded_doc/reproducibility.md](blinded_doc/reproducibility.md).
273
+ - **Quality gates.** CI runs lint (`ruff`/`black`), unit tests, and a portability check that
274
+ fails on any hardcoded machine-specific path.
275
+
276
+ ---
277
+
278
+ ## 11. Apps: NoduleMap & Retriever
279
+
280
+ - **NoduleMap** (`its-nodulemap`) β€” an interactive embedding-graph explorer of the nodule space.
281
+ See [blinded_doc/nodulemap.md](blinded_doc/nodulemap.md).
282
+ - **Retriever** (`its-retriever`) β€” faceted search, similarity and donor matching, with an
283
+ integrated CT viewer. See [blinded_doc/retriever.md](blinded_doc/retriever.md).
284
+
285
+ ---
286
+
287
+ ## 12. Command reference
288
+
289
+ | Command | Purpose |
290
+ |---------|---------|
291
+ | `its` | Umbrella CLI β€” index, query, config, synthesis subcommands |
292
+ | `its-trials` | Generate cohort manifests for the 13 trial modes |
293
+ | `its-insert` | Insert donor nodule masks into host anatomy from a manifest |
294
+ | `its-vlm` | VLM evaluation utilities |
295
+ | `its-nodulemap` | Launch the NoduleMap server |
296
+ | `its-retriever` | Launch the Retriever API + UI |
297
+
298
+ VLM modules: `…vlm_eval.build_dataset` Β· `…build_real_dataset` Β· `…runners.run_conditions` Β·
299
+ `…make_split` Β· `…eval_analysis` Β· `…report`.
300
+
301
+ ---
302
+
303
+ ## 13. Project layout
304
+
305
+ ```
306
+ itrialspace/
307
+ β”œβ”€β”€ src/itrialspace/ # the package
308
+ β”‚ β”œβ”€β”€ core/ io/ index/ query/ site/ # nodule index, query, path resolution
309
+ β”‚ β”œβ”€β”€ config/ # env-driven settings + ${VAR} interpolation
310
+ β”‚ β”œβ”€β”€ trials/ # the 13 trial-mode cohort planners
311
+ β”‚ β”œβ”€β”€ mask_inserter/ # donor mask β†’ host anatomy
312
+ β”‚ β”œβ”€β”€ synthesis/ # NodMAISI CT synthesis (code; weights external)
313
+ β”‚ β”œβ”€β”€ nodulemap/ retriever/ # the two apps
314
+ β”‚ └── evaluation/
315
+ β”‚ └── vlm_eval/ # build β†’ run οΏ½οΏ½ analyze (incl. eval_analysis suite)
316
+ β”œβ”€β”€ configs/ # example, env-interpolated configs
317
+ β”œβ”€β”€ infra/slurm/ # cluster job scripts (env-driven)
318
+ β”œβ”€β”€ blinded_doc/ # full documentation set (blinded)
319
+ β”œβ”€β”€ tests/ docker/
320
+ └── pyproject.toml environment.yml .env.example
321
+ ```
322
+
323
+ ---
324
+
325
+ ## 14. Citation, contributing, license
326
+
327
+ - **Citation** β€” withheld for double-blind review. (Cite each underlying CT dataset you
328
+ download into `raw_ct/` per its own terms.)
329
+ - **Contribute** via [`CONTRIBUTING.md`](CONTRIBUTING.md) β€” all PRs run through CI (lint + tests +
330
+ portability gate).
331
+ - **License** β€” see [`LICENSE`](LICENSE) (being finalized). Research use only; not a medical
332
+ device and not for clinical use.
333
+
334
+ <div align="center">
335
+ <sub>iTrialSpace β€” specify the cohort, synthesize the data, evaluate with control.</sub>
336
+ </div>
itrialspace/blinded_doc/architecture.md ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!-- BLINDED COPY for double-blind peer review β€” author, institution, and repository-identifying information removed. Do not use for attribution. -->
2
+
3
+ # Architecture
4
+
5
+ iTrialSpace is one installable package, `itrialspace`, using a `src/` layout. Each former
6
+ top-level project is now a subpackage under a single namespace.
7
+
8
+ ```
9
+ src/itrialspace/
10
+ β”œβ”€β”€ config/ Portable path/settings resolution (settings.py)
11
+ β”œβ”€β”€ core/ Data model: NoduleProfile, LabelNormaliser, schema, enums
12
+ β”œβ”€β”€ io/ Dataset loading: DatasetLoader, DatasetRegistry, adapters
13
+ β”œβ”€β”€ index/ NoduleIndex β€” merged multi-dataset DataFrame
14
+ β”œβ”€β”€ query/ NoduleQuery (fluent filters), ReinsertionMatcher (k-NN)
15
+ β”œβ”€β”€ site/ Synthetic trial engine: specs, sampling, planner, cohort builder
16
+ β”œβ”€β”€ trials/ Trial manifest runner (the 13 modes)
17
+ β”œβ”€β”€ mask_inserter/ Voxel-level nodule mask insertion (label 23)
18
+ β”œβ”€β”€ synthesis/ NodMAISI CT synthesis (model weights external)
19
+ β”œβ”€β”€ apps/
20
+ β”‚ β”œβ”€β”€ nodulemap/ Embedding graph viz (FastAPI + sigma.js)
21
+ β”‚ └── retriever/ Faceted search + similarity UI (FastAPI + Streamlit)
22
+ β”œβ”€β”€ evaluation/ OPTIONAL evaluation extras
23
+ β”‚ β”œβ”€β”€ vlm_eval/ Vision-language model evaluation
24
+ β”œβ”€β”€ utils/ Shared helpers
25
+ └── cli.py Umbrella `its` CLI
26
+ ```
27
+
28
+ Supporting top-level directories:
29
+
30
+ ```
31
+ configs/ Example configs (*.example.yaml) + non-path configs (trials, features)
32
+ infra/slurm/ HPC submission scripts, cluster-portable via env.sh
33
+ docs/ This documentation
34
+ tests/ Unified pytest suite (runs with no external data)
35
+ docker/ Container build
36
+ ```
37
+
38
+ ## Component map (old β†’ new)
39
+
40
+ | Original top-level | New namespace | Console script |
41
+ |--------------------|---------------|----------------|
42
+ | `itrialspace/` (core) | `itrialspace.{core,io,index,query,site}` | `its` |
43
+ | `itrialspace_mask_inserter/` | `itrialspace.mask_inserter` | `its-insert` |
44
+ | `site_trials/` | `itrialspace.trials` | `its-trials` |
45
+ | `nodmaisi_synth/` (code) | `itrialspace.synthesis` | (subprocess) |
46
+ | `nodulemap/` | `itrialspace.apps.nodulemap` | `its-nodulemap` |
47
+ | `retriever/` | `itrialspace.apps.retriever` | `its-retriever` |
48
+ | `vlm_evaluation/` | `itrialspace.evaluation.vlm_eval` | (module/scripts)* |
49
+
50
+ \* VLM evaluation runs via its module scripts (`python -m itrialspace.evaluation.vlm_eval...`)
51
+ rather than a console entry point.
52
+
53
+ ## Data flow
54
+
55
+ ```
56
+ NoduleIndex ──▢ CohortBuilder ──▢ mask_inserter ──▢ synthesis ──▢ evaluation
57
+ (7 datasets) (TrialSpec β†’ (donor mask (NodMAISI (VLM eval)
58
+ manifest) @ label 23) CT volume)
59
+ β”‚
60
+ β”œβ”€β–Ά nodulemap (graph viz)
61
+ └─▢ retriever (search)
62
+ ```
63
+
64
+ See [pipeline.md](pipeline.md) for the full end-to-end flow and
65
+ [SKILL.md](../SKILL.md) for an exhaustive per-file reference.
itrialspace/blinded_doc/configuration.md ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!-- BLINDED COPY for double-blind peer review β€” author, institution, and repository-identifying information removed. Do not use for attribution. -->
2
+
3
+ # Configuration & path model
4
+
5
+ iTrialSpace resolves **every** filesystem path from environment variables (with sensible
6
+ defaults), so the same code and configs run unchanged on a laptop, a workstation, or an
7
+ HPC cluster. Nothing is hardcoded.
8
+
9
+ The single source of truth is [`itrialspace.config.settings`](../src/itrialspace/config/settings.py).
10
+
11
+ ## Environment variables
12
+
13
+ Copy `.env.example` β†’ `.env` and edit. (`infra/slurm/env.sh` and the synthesis
14
+ config loaders all read these.)
15
+
16
+ | Variable | Default | Meaning |
17
+ |----------|---------|---------|
18
+ | `ITRIALSPACE_DATA_DIR` | `~/.itrialspace/data` | Root of the unified data layout |
19
+ | `ITRIALSPACE_OUTPUT_DIR` | `=DATA_DIR` | Where generated artifacts are written |
20
+ | `ITRIALSPACE_ROOT` | auto-detected | Repo root (for resolving `configs/`) |
21
+ | `NODMAISI_MODELS_DIR` | β€” | NodMAISI model weights directory |
22
+ | `ITRIALSPACE_CONDA_ENV`, `SLURM_PARTITION_*` | `itrialspace`, … | HPC/SLURM only |
23
+
24
+ Check what resolved:
25
+
26
+ ```bash
27
+ its config
28
+ ```
29
+
30
+ ## YAML interpolation
31
+
32
+ Any string in a config YAML may reference these variables with `${VAR}` syntax. The
33
+ config loaders expand them (falling back to the documented defaults even when the variable
34
+ is not exported):
35
+
36
+ ```yaml
37
+ # configs/paths.yaml
38
+ base_dir: ${ITRIALSPACE_DATA_DIR}
39
+ ```
40
+
41
+ ## Config file resolution
42
+
43
+ Path-bearing configs ship as `configs/*.example.yaml`. Resolution order
44
+ (`settings.find_config`):
45
+
46
+ 1. `ITRIALSPACE_<NAME>_CONFIG` env override (e.g. `ITRIALSPACE_DATASETS_CONFIG`)
47
+ 2. `configs/<name>.yaml` (your local copy β€” gitignored)
48
+ 3. `configs/<name>.example.yaml` (shipped example)
49
+ 4. the default bundled inside the package
50
+
51
+ To customize, copy the example and edit:
52
+
53
+ ```bash
54
+ cp configs/paths.example.yaml configs/paths.yaml
55
+ ```
56
+
57
+ | Config | Example file | Used by |
58
+ |--------|--------------|---------|
59
+ | Dataset registry | `configs/datasets.example.yaml` | `DatasetRegistry.from_yaml()` |
60
+ | Data layout | `configs/paths.example.yaml` | `PathResolver` |
61
+ | NodMAISI integration | `configs/integration.example.yaml` | synthesis pipeline |
62
+ | Mask inserter | `configs/mask_inserter.example.yaml` | mask insertion |
63
+ | Trial templates | `configs/trials.yaml` | trial knowledge base (no paths) |
64
+ | Embedding features | `configs/features.yaml` | NoduleMap (no paths) |
65
+
66
+ ## Using the API directly
67
+
68
+ ```python
69
+ from itrialspace.config import settings
70
+ settings.data_dir() # Path to the data root
71
+ settings.load_yaml("configs/paths.example.yaml") # loads + expands ${VARS}
72
+ settings.find_config("datasets.yaml") # resolves a config path
73
+ ```
74
+
75
+ ## Portability guard
76
+
77
+ `tools/check_portability.py` (run by pre-commit and CI) fails the build if any tracked
78
+ file reintroduces a hardcoded absolute path. Always resolve paths through `settings` or
79
+ env vars.
itrialspace/blinded_doc/data.md ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!-- BLINDED COPY for double-blind peer review β€” author, institution, and repository-identifying information removed. Do not use for attribution. -->
2
+
3
+ # Data preparation
4
+
5
+ iTrialSpace ships **code only**. The source CT datasets and trained model weights are not
6
+ redistributed (they carry their own licenses and are large). This guide describes the
7
+ expected layout and how to obtain the data.
8
+
9
+ The repo bundles **no data** β€” point `ITRIALSPACE_DATA_DIR` at your real data root (set it
10
+ once in `.env`; see [configuration.md](configuration.md)). Examples and data-dependent
11
+ tests read from there and skip cleanly when it isn't present (e.g. in CI).
12
+
13
+ ## Unified data layout
14
+
15
+ Point `ITRIALSPACE_DATA_DIR` (in `.env`) at a directory with this structure:
16
+
17
+ ```
18
+ $ITRIALSPACE_DATA_DIR/
19
+ β”œβ”€β”€ raw_ct/{DATASET}/ CT scans (NIfTI, RAS+)
20
+ β”œβ”€β”€ masks/{DATASET}/
21
+ β”‚ β”œβ”€β”€ nodule_seg/ Individual nodule masks
22
+ β”‚ β”œβ”€β”€ combined_seg/ Combined per-patient masks
23
+ β”‚ β”œβ”€β”€ organ_seg/ VISTA3D organ segs (raw, deprecated)
24
+ β”‚ └── refined_seg/ Refined organ + body segs (default)
25
+ β”œβ”€β”€ profiles/ {DATASET}_nodule_profiles.csv (53-column schema)
26
+ β”œβ”€β”€ meta/ Original dataset metadata CSVs
27
+ β”œβ”€β”€ manifests/ Generated cohort manifests
28
+ β”œβ”€β”€ inserted_masks/ Mask-insertion outputs
29
+ └── generated_cts/ NodMAISI synthesis outputs
30
+ ```
31
+
32
+ `ct_path` values in the profile CSVs are **relative** to `raw_ct/`, e.g.
33
+ `DLCS24/DLCS_0001.nii.gz`. Verify resolution with `its config` and the `PathResolver`.
34
+
35
+ ## The 7 supported datasets
36
+
37
+ | Dataset | Source | Notes |
38
+ |---------|--------|-------|
39
+ | **DLCS24** | Institutional Lung Cancer Screening | Binary label, Lung-RADS, demographics |
40
+ | **LUNA25** | LUNA25 challenge | Largest; multi-nodule screening |
41
+ | **LUNA16** | LUNA16 / LIDC-IDRI | No malignancy label (anatomy only) |
42
+ | **LUNGx** | SPIE-AAPM LUNGx | Malignancy classification benchmark, ~49% malignant |
43
+ | **LNDbv4** | LNDb | Multi-radiologist ratings (float β†’ threshold) |
44
+ | **NSCLCR** | NSCLC-Radiomics (TCIA) | 100% malignant, staging/survival |
45
+ | **IMDCT** | Internal multi-modal diagnostic CT | PET, spiculation, benign/cancer |
46
+
47
+ > `NLST3D` was permanently removed from the core pipeline for data-quality reasons and is
48
+ > guarded against at multiple layers.
49
+
50
+ Each public dataset must be obtained from its original source under its own license. Once
51
+ downloaded, harmonize each into the 53-column `CORE_COLS` schema (see
52
+ `itrialspace.core.schema`) as `{DATASET}_nodule_profiles.csv` and place CTs/masks per the
53
+ layout above.
54
+
55
+ ## Adding a new dataset
56
+
57
+ 1. Produce `{DATASET}_nodule_profiles.csv` matching `CORE_COLS` (incl. the 12
58
+ `reinsertion_*` columns).
59
+ 2. Add an adapter in `src/itrialspace/io/adapters/adapters.py`.
60
+ 3. Register it in `core/schema.py` (`DATASET_NAMES`, `DATASET_FLAGS`), `core/label.py`,
61
+ and `configs/datasets.example.yaml` + `configs/paths.example.yaml`.
62
+ 4. Add tests.
itrialspace/blinded_doc/dataset_card.md ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!-- BLINDED COPY for double-blind peer review β€” author, institution, and repository-identifying information removed. Do not use for attribution. -->
2
+
3
+ # iTrialSpace β€” public dataset card
4
+
5
+ This card describes the iTrialSpace data release: what is included, how it is organised, what
6
+ is **not** redistributed (the real CT volumes), and how to obtain and assemble everything for
7
+ use. It accompanies the [iTrialSpace code](https://github.com/anonymous/itrialspace).
8
+
9
+ > **Research use only β€” not for clinical use.** The synthetic CTs are generated for method
10
+ > development and evaluation; they are not medical devices and must not be used for diagnosis.
11
+
12
+ ## What this release is
13
+
14
+ iTrialSpace harmonises lung-nodule data from **7 public CT datasets** and uses it to (a) plan
15
+ synthetic clinical-trial cohorts, (b) insert donor nodule masks into host anatomy, (c)
16
+ synthesise CT volumes (NodMAISI), and (d) build VLM evaluation datasets. This release ships the
17
+ **derived** artifacts (profiles, masks, manifests, inserted masks, synthetic CTs, VLM eval
18
+ sets). It does **not** redistribute the **real CT images** β€” you obtain those from the original
19
+ dataset providers under their own licenses (see [Β§ Obtaining `raw_ct/`](#obtaining-raw_ct)).
20
+
21
+ **NLST3D is excluded** from this release. It was permanently removed from the project; no
22
+ NLST3D profiles, masks, metadata, synthetic data, or VLM data are shared.
23
+
24
+ ## Directory layout (what is shared)
25
+
26
+ ```
27
+ iTrialSpace/
28
+ β”œβ”€β”€ profiles/ # per-dataset nodule profile CSVs ({DATASET}_nodule_profiles.csv) β€” 13,140 nodules, 7 datasets
29
+ β”œβ”€β”€ meta/ # per-dataset metadata CSVs (demographics, acquisition, labels)
30
+ β”œβ”€β”€ masks/ # segmentation masks per dataset (nodule_seg/, refined_seg/, ...)
31
+ β”œβ”€β”€ manifests/ # synthetic cohort manifests for the 13 trial modes
32
+ β”œβ”€β”€ inserted_masks/ # combined organ+nodule masks (nodule = label 23) used as synthesis input
33
+ β”œβ”€β”€ generated_cts/ # 3-D SYNTHETIC CT volumes (the headline synthetic data) β€” see below
34
+ β”œβ”€β”€ generated_cts_qc/ # (optional, may be withheld) QC montages β€” these embed real CT pixels
35
+ └── vlm_dataset/ # VLM evaluation dataset (2-D slices + ground truth + model results)
36
+ β”œβ”€β”€ synthetic/ # merged standard + digital-twin (modes 1–13): lung_axial/, lung_axial_medgemma/, cross_model_comparison/
37
+ β”œβ”€β”€ real/ # real-CT eval set (7 datasets): lung_axial/, lung_axial_medgemma/, cross_model_comparison/
38
+ └── splits/ # frozen, checksummed evaluation splits (the exact cases each result is reported on)
39
+
40
+ # NOT shared β€” you provide it:
41
+ └── raw_ct/ # the real CT volumes ({DATASET}/<id>.nii.gz) β€” obtain from sources below
42
+ ```
43
+
44
+ All paths inside the shipped CSVs/JSONs are **relative to the dataset root** (or basenames), so
45
+ the release is portable once `raw_ct/` is populated. Set `ITRIALSPACE_DATA_DIR` to this root.
46
+
47
+ ## Components
48
+
49
+ | Dir | Contents | Notes |
50
+ |-----|----------|-------|
51
+ | `profiles/` | One CSV per dataset: nodule coordinates, diameter, lobe/zone/side, distances, label, 12 reinsertion features | Derived metadata; 13,140 nodules |
52
+ | `meta/` | Per-dataset metadata (age/sex/smoking where available, acquisition, label source) | Derived from source datasets β€” see licensing |
53
+ | `masks/` | `{DATASET}/nodule_seg/` (per-nodule), `refined_seg/` (organ+body) NIfTI | Derived segmentations |
54
+ | `manifests/` | `mode{1..13}_*/…csv` cohort manifests (which donor β†’ which host, at what location/scale) | Synthetic specs; no real images |
55
+ | `inserted_masks/` | Combined organ+nodule masks (label 23) + `audit.json` | Synthesis input |
56
+ | `generated_cts/` | `mode*/<case>/{synthetic_ct.nii.gz, input_mask.nii.gz, input_mask_label.nii.gz, dataset.json, nodmaisi_audit.json}` | 44,174 synthetic CTs; ~3 TB |
57
+ | `generated_cts_qc/` | `mode*/<case>/qc/*.png` QC montages | **Embed real host-CT pixels** β€” withhold unless source licenses permit |
58
+ | `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) |
59
+
60
+ `generated_cts/` case dirs have been cleaned for release: real-CT symlinks removed, intermediate
61
+ temp files dropped, QC moved to `generated_cts_qc/`, and `nodmaisi_audit.json` scrubbed of
62
+ real-CT paths.
63
+
64
+ ## Dataset counts
65
+
66
+ **Nodules per dataset** (`profiles/`, `masks/`) β€” NLST3D excluded:
67
+
68
+ | Dataset | Nodule profiles | Nodule masks |
69
+ |---------|----------------:|-------------:|
70
+ | DLCS24 | 2,487 | 2,473 |
71
+ | LUNA25 | 6,163 | 6,156 |
72
+ | IMDCT | 2,032 | 2,032 |
73
+ | LUNA16 | 1,186 | 1,184 |
74
+ | LNDbv4 | 768 | 743 |
75
+ | NSCLCR | 421 | 421 |
76
+ | LUNGx | 83 | 83 |
77
+ | **Total** | **13,140** | **13,112** |
78
+
79
+ (Mask count is slightly lower where a per-nodule segmentation was unavailable.)
80
+
81
+ **Synthetic** β€” 3-D CTs in `generated_cts/`: **44,174** complete volumes (all 13 trial modes);
82
+ VLM eval cases in `vlm_dataset/synthetic/` (per profile): **42,858** (the slice-level subset
83
+ that passed extraction). Per mode:
84
+
85
+ | Mode | CTs | Mode | CTs | Mode | CTs |
86
+ |------|----:|------|----:|------|----:|
87
+ | 1 controlled_prevalence | 999 | 6 cross_dataset | 1,499 | 11 digital_twin_isolation | 12,448 |
88
+ | 2 size_detection | 598 | 7 bootstrap | 3,984 | 12 digital_twin_complete | 8,981 |
89
+ | 3 location | 500 | 8 algo_comparison | 499 | 13 digital_twin_cross | 9,378 |
90
+ | 4 demographic | 799 | 9 screening | 1,495 | | |
91
+ | 5 counterfactual | 2,496 | 10 multi_nodule | 498 | **Total** | **44,174** |
92
+
93
+ **Real** β€” VLM eval cases in `vlm_dataset/real/` (per profile): **13,087** (LUNA25 6,156 Β·
94
+ DLCS24 2,473 Β· IMDCT 2,032 Β· LUNA16 1,179 Β· LNDbv4 743 Β· NSCLCR 421 Β· LUNGx 83).
95
+
96
+ **Images per case (VLM)** β€” 4 conditions (`plain`, `bbox`, `contour`, `bbox_contour`) Γ— 3
97
+ z-slices (`z`, `z-1`, `z+1`) = up to **12 PNGs/case**. Total extracted slices β‰ˆ **502k** per
98
+ synthetic profile and β‰ˆ **157k** per real profile. Two profiles are provided per set:
99
+ `lung_axial` (BiomedCLIP/LLaVA-Med) and `lung_axial_medgemma` (MedGemma).
100
+
101
+ ## VLM ground truth
102
+
103
+ Each row of `vlm_dataset/**/eval_dataset.csv` is one nodule slice with the ground-truth labels
104
+ for **three zero-shot evaluation tasks** (columns in the CSV):
105
+
106
+ | Task | Column | Classes |
107
+ |------|--------|---------|
108
+ | **Presence** (binary) | `ground_truth_presence` | `present`, `absent` |
109
+ | **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` |
110
+ | **Size** (4-class) | `ground_truth_size_bucket` | `<5mm`, `5-10mm`, `10-20mm`, `>20mm` |
111
+
112
+ How the labels are derived:
113
+
114
+ - **Synthetic set** β€” ground truth is **known by construction**, not predicted: the nodule is
115
+ *inserted* at a chosen lobe and scaled to a chosen effective diameter, so `ground_truth_lobe`
116
+ comes from the insertion lobe and `ground_truth_size_bucket` from binning `effective_diam_mm`.
117
+ `ground_truth_presence` is `present` for inserted cases and `absent` for the deliberately
118
+ nodule-free cases (e.g. the counterfactual mode). This exactness β€” automatic, leakage-free
119
+ labels at a controlled lobe/size β€” is the point of the synthetic pipeline.
120
+ - **Real set** β€” ground truth comes from each source dataset's annotations: `ground_truth_lobe`
121
+ from the profile's lobe (normalised to the 5 canonical classes) and `ground_truth_size_bucket`
122
+ from binning `nodule_mean_diam_mm`; all real cases are `present`.
123
+
124
+ The models output a predicted label per task; `correct = (prediction == ground_truth)`, and
125
+ accuracy = mean(`correct`). Results are reported per image **condition** (`plain`, `bbox`,
126
+ `contour`, `bbox_contour`) so the effect of spatial guidance can be measured. Size buckets use
127
+ half-open bins (`<5`, `[5,10)`, `[10,20)`, `β‰₯20` mm); lobe accepts the standard `RUL/RML/RLL/
128
+ LUL/LLL` aliases on input.
129
+
130
+ ### Slices: stored vs used for evaluation
131
+
132
+ Each profile (`lung_axial`, `lung_axial_medgemma`) stores, per case, **3 z-slices** (`z`, `z-1`,
133
+ `z+1`) Γ— **4 conditions** = up to 12 PNGs. **Evaluation uses the center (middle-z) slice** β€” that
134
+ is what `eval_dataset.csv` references for each condition. The `zΒ±1` slices are stored as
135
+ multi-slice **context** (used by MedGemma, which loads center + neighbours; **BiomedCLIP and
136
+ LLaVA-Med use the center slice only**). The **3 tasks share the same slice** (only the text prompt
137
+ differs), so tasks do not multiply the slice count.
138
+
139
+ | | Synthetic (per profile) | Real (per profile) |
140
+ |---|---:|---:|
141
+ | Cases (nodes) | 42,858 | 13,087 |
142
+ | Conditions | 4 | 4 |
143
+ | z-slices per case | 3 (`z`, `z-1`, `z+1`) | 3 |
144
+ | **Slices stored** (all z Γ— conditions) | β‰ˆ 502,048 | β‰ˆ 156,678 |
145
+ | **Center slices = used for evaluation** (1 / case / condition) | 167,364 | 52,228 |
146
+ | ↳ per condition: `plain` | 42,858 | 13,087 |
147
+ | ↳ per condition: `bbox` / `contour` / `bbox_contour` (each) | 41,502 | 13,047 |
148
+
149
+ (The overlay conditions cover slightly fewer cases than `plain` β€” a small number of cases had no
150
+ overlay generated.) **Predictions per run** = one per case per (model Γ— condition Γ— task); e.g. a
151
+ single BiomedCLIP Γ— `plain` Γ— `presence` run scores 42,858 synthetic / 13,087 real center slices.
152
+
153
+ ### Reporting convention (evaluation N) β€” read before comparing to the paper
154
+
155
+ Accuracy is **reported on the set of cases that have a completed prediction in *every*
156
+ (task Γ— condition Γ— model)** so that all reported numbers share a single N β€” i.e. the same cases
157
+ are scored for presence, lobe, and size. In **this released dataset that set is the full case
158
+ count** (42,858 synthetic / 13,087 real): every row in `eval_dataset.csv` is complete for all
159
+ three tasks (verified β€” 0 rows missing presence/lobe/size).
160
+
161
+ The original paper analysis reported a **smaller synthetic N (42,382)** for exactly this reason:
162
+ at analysis time 334 mode-13 cases (and a few others) had slices extracted but **inference not yet
163
+ run**, so they were excluded to keep N consistent across all tasks β€” the same "score every case in
164
+ every task" rule, applied before inference was finished. The intermediate counts seen in the
165
+ frozen paper folder reconcile as:
166
+
167
+ | Count | Meaning |
168
+ |------:|---------|
169
+ | **42,382** | synthetic cases with **inference complete in all 3 tasks** β†’ the paper's accuracy tables |
170
+ | 42,716 | slices **extracted on disk** at paper time (= 42,382 + 334 mode-13 pending inference) |
171
+ | **42,858** | the **finished** release: inference complete for all extracted cases (after re-extraction: mode-7 +10, mode-11 +213, mode-13 βˆ’81) |
172
+
173
+ So the paper's 42,382 and the release's 42,858 are the *same convention* at two points in time, not
174
+ a conflicting count. Result-analysis scripts must apply this intersection so released numbers stay
175
+ self-consistent β€” see [vlm_eval.md Β§ Reporting convention](vlm_eval.md#4a-reporting-convention--keeping-released-numbers-aligned)
176
+ and `metrics.common_case_ids()`.
177
+
178
+ **Frozen splits β€” the exact cases reported on.** `vlm_dataset/splits/` ships the case lists so a
179
+ result can always be tied to (and reproduced on) its exact case set. Each `*.txt` holds one
180
+ **canonical uid** per line (`mode/case`, condition-independent); `splits.json` records the count, a
181
+ SHA-256 of the list, the source result files, and the code commit (verifiable β€” regenerate and the
182
+ hash must match). The case identity is the slice path, **not** the `case_id` column (which is a
183
+ non-unique positional index in the CSVs).
184
+
185
+ | Split | Synthetic | Real | Scope |
186
+ |-------|----------:|-----:|-------|
187
+ | `release_v1` | 42,858 | 13,087 | scored by all 3 models on `plain`, all 3 tasks (the headline counts) |
188
+ | `release_v1_full` | 41,502 | 13,047 | strict ∩ across all 3 models Γ— all 4 conditions Γ— 3 tasks (use for condition-comparison tables) |
189
+
190
+ Run on exactly a split with the runners' `--case-ids` flag, e.g.
191
+ `--case-ids vlm_dataset/splits/release_v1.synthetic.txt`. Details, verification, and regeneration:
192
+ `vlm_dataset/splits/README.md` and [vlm_eval.md Β§ Reporting convention](vlm_eval.md#4a-reporting-convention--keeping-released-numbers-aligned).
193
+
194
+ ## Obtaining `raw_ct/`
195
+
196
+ The real CT volumes are **not** redistributed. Download each dataset from its original provider
197
+ (honouring its license and citation requirements) and place the volumes under
198
+ `raw_ct/{DATASET}/` to match the `ct_path` values in `profiles/`.
199
+
200
+ > ⚠ **Action for maintainers:** verify each dataset's exact citation, license, and access URL
201
+ > before publishing, and replace the bracketed fields below with the official text.
202
+
203
+ | `{DATASET}` | Dataset | Source / access | Citation |
204
+ |-------------|---------|-----------------|----------|
205
+ | `DLCS24` | Institutional Lung Cancer Screening (2024) | [add access URL] | [add official citation] |
206
+ | `LUNA25` | LUNA25 challenge | [add access URL, e.g. luna25.grand-challenge.org] | [add citation] |
207
+ | `LUNA16` | LUNA16 challenge (LIDC-IDRI subset) | https://luna16.grand-challenge.org | Setio et al., *Med. Image Anal.* 2017 [verify] |
208
+ | `LUNGx` | SPIE-AAPM-NCI LUNGx Challenge | TCIA: SPIE-AAPM Lung CT Challenge | Armato et al. [verify] |
209
+ | `LNDbv4` | LNDb challenge (v4) | https://lndb.grand-challenge.org | Pedrosa et al. 2019 [verify] |
210
+ | `NSCLCR` | NSCLC-Radiomics | TCIA: NSCLC-Radiomics | Aerts et al., *Nat. Commun.* 2014 [verify] |
211
+ | `IMDCT` | [add full name] | [add access URL] | [add citation] |
212
+
213
+ Expected layout after download:
214
+ ```
215
+ raw_ct/
216
+ β”œβ”€β”€ DLCS24/<patient-id>.nii.gz
217
+ β”œβ”€β”€ LUNA25/<id>.nii.gz
218
+ β”œβ”€β”€ LUNA16/<series-uid>.nii.gz
219
+ β”œβ”€β”€ LUNGx/<id>.nii.gz
220
+ β”œβ”€β”€ LNDbv4/<id>.nii.gz
221
+ β”œβ”€β”€ NSCLCR/<id>.nii.gz
222
+ └── IMDCT/<id>.nii.gz
223
+ ```
224
+ The exact filenames are the ones referenced in `profiles/{DATASET}_nodule_profiles.csv`
225
+ (`ct_path` column). Convert DICOM→NIfTI (RAS+) if the source ships DICOM.
226
+
227
+ ## Licensing & governance
228
+
229
+ - **Synthetic data** (`generated_cts/`, `inserted_masks/`, synthetic `vlm_dataset/`) is generated
230
+ by iTrialSpace from public-dataset host anatomy; released under [LICENSE β€” to be finalised].
231
+ - **Derived annotations** (`profiles/`, `meta/`, `masks/`, real `vlm_dataset/`) are derived from
232
+ the source datasets. Redistribution of derived data is subject to each source's license β€”
233
+ confirm per dataset before publishing; remove any field a source disallows.
234
+ - **Real CT images** are never redistributed here.
235
+ - **NLST3D** is excluded entirely (purged from the project).
236
+
237
+ ## How to use
238
+
239
+ ```bash
240
+ export ITRIALSPACE_DATA_DIR=/path/to/iTrialSpace # this dataset root
241
+ # 1) populate raw_ct/ from the sources above
242
+ # 2) install the code (see the repo) and point at the data:
243
+ its config # verify resolved paths
244
+ ```
245
+ See the repo docs: [data.md](data.md), [vlm_eval.md](vlm_eval.md), [pipeline.md](pipeline.md).
246
+
247
+ ## Citation
248
+
249
+ If you use this dataset, cite each underlying CT dataset you downloaded into `raw_ct/`
250
+ (table above), honouring its license and citation requirements.
itrialspace/blinded_doc/index.md ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!-- BLINDED COPY for double-blind peer review β€” author, institution, and repository-identifying information removed. Do not use for attribution. -->
2
+
3
+ # iTrialSpace Documentation
4
+
5
+ **Synthetic Imaging Clinical Trial Engine for lung CT AI evaluation.**
6
+
7
+ iTrialSpace harmonizes 13,140 nodule profiles from 7 public lung CT datasets, builds
8
+ virtual clinical-trial cohorts across 13 trial modes, inserts donor nodule masks into
9
+ real host anatomy, synthesizes CT volumes with a ControlNet-conditioned diffusion model
10
+ (NodMAISI), and evaluates vision-language models.
11
+
12
+ ## Start here
13
+
14
+ | Guide | What it covers |
15
+ |-------|----------------|
16
+ | [Installation](installation.md) | Environments, extras, GPU/torch, Docker |
17
+ | [Quickstart](quickstart.md) | First commands; build the index; run a trial |
18
+ | [Walkthrough: Mode 1 end-to-end](walkthrough_mode1.md) | 200 cases: plan β†’ insert β†’ generate CTs |
19
+ | [Running the pipeline (runbook + smoke test)](running_the_pipeline.md) | All 13 modes via SLURM; copy-paste commands for every step |
20
+ | [Configuration](configuration.md) | The env-driven path model (runs anywhere) |
21
+ | [Data preparation](data.md) | Laying out the 7 datasets; sample fixtures |
22
+ | [Dataset card](dataset_card.md) | Public data release: shared dirs, `raw_ct` sources/citations, NLST3D exclusion |
23
+ | [Architecture](architecture.md) | Components and how they fit together |
24
+ | [Pipeline](pipeline.md) | End-to-end flow: index β†’ trials β†’ masks β†’ CT β†’ eval |
25
+ | [Trial modes](trial_modes.md) | The 13 trial modes |
26
+ | [NoduleMap](nodulemap.md) | Build + serve the embedding graph explorer (`its-nodulemap`) |
27
+ | [Retriever](retriever.md) | Faceted search, similarity & donor matching + CT viewer (`its-retriever`) |
28
+ | [VLM evaluation](vlm_eval.md) | Evaluate BiomedCLIP / LLaVA-Med / MedGemma on nodule CT (synthetic + real) |
29
+ | [VLM evaluation β€” implementation](vlm_eval_implementation.md) | Engineering/architecture reference for the VLM eval subsystem |
30
+ | [VLM results](vlm_results.md) | Headline accuracy tables on the fixed all-conditions split |
31
+ | [NoduleMap similarity design](nodulemap_similarity.md) | Donor-matching metric + optional appearance (radiomics/foundation) roadmap |
32
+ | [Reproducibility](reproducibility.md) | Determinism, audit trails, HPC orchestration |
itrialspace/blinded_doc/installation.md ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!-- BLINDED COPY for double-blind peer review β€” author, institution, and repository-identifying information removed. Do not use for attribution. -->
2
+
3
+ # Installation
4
+
5
+ iTrialSpace is a single installable package (`itrialspace`) with **optional-dependency
6
+ extras** so you install only what a given task needs. It runs on a workstation or an HPC
7
+ cluster β€” nothing is hardcoded to a specific machine.
8
+
9
+ ## 1. Get the code
10
+
11
+ ```bash
12
+ git clone <repo-url>
13
+ cd itrialspace
14
+ ```
15
+
16
+ ## 2. Create an environment
17
+
18
+ **Conda (recommended for the imaging/ML stack)** β€” versions pinned to the dev env (Python 3.10):
19
+
20
+ ```bash
21
+ conda env create -f environment.yml
22
+ conda activate itrialspace
23
+ ```
24
+
25
+ **Exact clone of the development environment** (Python 3.10.13,
26
+ torch 2.4.1+cu121, git-pinned MONAI, full pinned set) β€” the "give me exactly what worked"
27
+ option:
28
+
29
+ ```bash
30
+ conda env create -f environment.lock.yml # one command; uses requirements.lock.txt
31
+ conda activate itrialspace
32
+ # or into a plain venv:
33
+ # python3.10 -m venv .venv && . .venv/bin/activate
34
+ # pip install -r requirements.lock.txt && pip install -e .
35
+ ```
36
+
37
+ > The lock includes torch + MONAI and some packages from the original shared env; it
38
+ > targets linux-64 / CUDA 12.1. Trim `requirements.lock.txt` if you only need certain stages.
39
+
40
+ **Or a minimal plain venv:**
41
+
42
+ ```bash
43
+ python -m venv .venv && source .venv/bin/activate
44
+ pip install --upgrade pip
45
+ ```
46
+
47
+ ## 3. Install with the extras you need
48
+
49
+ ```bash
50
+ pip install -e ".[imaging,web]" # core pipeline + web tools
51
+ pip install -e ".[dev]" # + tests/lint/format
52
+ pip install -e ".[all]" # imaging + web + vlm + dev
53
+ ```
54
+
55
+ | Extra | Installs | Enables |
56
+ |-------|----------|---------|
57
+ | *(base)* | pandas, numpy, pyyaml | Index, query, trial planning |
58
+ | `imaging` | nibabel, scipy, SimpleITK | Mask insertion, NIfTI I/O |
59
+ | `web` | fastapi, streamlit, faiss, umap-learn, pyarrow | NoduleMap + Retriever |
60
+ | `synthesis` | monai | NodMAISI synthesis* |
61
+ | `vlm` | transformers, open_clip_torch | VLM evaluation* |
62
+ | `dev` | pytest, ruff, black, pre-commit | Development |
63
+
64
+ \* **PyTorch is not declared as a dependency** β€” install the build matching your CUDA:
65
+
66
+ ```bash
67
+ # match the dev env: CUDA 12.1
68
+ pip install torch==2.4.1 --index-url https://download.pytorch.org/whl/cu121
69
+ pip install -e ".[synthesis,vlm]"
70
+ ```
71
+
72
+ \*\* The `eval` extra also needs **external** models/repos that are not bundled β€” see
73
+ [evaluation_external_dependencies.md](evaluation_external_dependencies.md).
74
+
75
+ ## 4. Configure paths
76
+
77
+ ```bash
78
+ cp .env.example .env # then edit ITRIALSPACE_DATA_DIR etc.
79
+ its config # prints the resolved paths β€” verify them
80
+ ```
81
+
82
+ See [configuration.md](configuration.md) for the full path model.
83
+
84
+ ## 5. Verify
85
+
86
+ ```bash
87
+ pytest -m "not full_volume" # unit tests (no external data needed)
88
+ python tools/check_portability.py # no hardcoded paths
89
+ ```
90
+
91
+ ## Model weights (NodMAISI synthesis)
92
+
93
+ Synthesis model weights (`autoencoder.pt`, `diffusion_unet.pt`, the ControlNet
94
+ checkpoint) are **not** in the repo. Obtain them (see the NodMAISI release / Hugging Face)
95
+ and point to their directory:
96
+
97
+ ```bash
98
+ export NODMAISI_MODELS_DIR=/path/to/nodmaisi/models
99
+ ```
100
+
101
+ ## Containers
102
+
103
+ **Mental model:** the image ships **code only**. Data, model weights, and outputs are
104
+ **mounted at runtime** (`-v host:container`) and pointed to with env vars β€” they're never
105
+ baked into the image. There are three deployment routes:
106
+
107
+ | Target | Use |
108
+ |--------|-----|
109
+ | New HPC cluster | conda env (`environment.yml`) + SLURM (`infra/slurm/`) β€” Docker usually unavailable on compute nodes |
110
+ | Standalone server / cloud VM (CPU) | **Docker (CPU)** image |
111
+ | GPU server / synthesis & VLM | **Docker (GPU)** image, or **Apptainer** on HPC |
112
+
113
+ ### Docker β€” CPU image (core + imaging + web)
114
+
115
+ ```bash
116
+ docker build -t itrialspace -f docker/Dockerfile .
117
+
118
+ # verify resolved paths
119
+ docker run --rm -e ITRIALSPACE_DATA_DIR=/data -v /host/iTrialSpace:/data \
120
+ itrialspace its config
121
+
122
+ # generate a manifest (mount data + outputs)
123
+ docker run --rm \
124
+ -e ITRIALSPACE_DATA_DIR=/data -e ITRIALSPACE_OUTPUT_DIR=/out \
125
+ -v /host/iTrialSpace:/data -v /host/outputs:/out \
126
+ itrialspace its-trials --mode controlled_prevalence --n-cases 200 --output-dir /out/manifests/mode1
127
+
128
+ # launch a web tool (publish the port)
129
+ docker run --rm -p 8422:8422 -e ITRIALSPACE_DATA_DIR=/data -v /host/iTrialSpace:/data \
130
+ itrialspace its-nodulemap serve --port 8422
131
+ ```
132
+ The entrypoint is `its`, so the trailing args are the subcommand. For a shell:
133
+ `docker run --rm -it --entrypoint bash itrialspace`. This image has **no PyTorch/CUDA** β€”
134
+ it cannot run synthesis/VLM.
135
+
136
+ ### Docker β€” GPU image (synthesis + VLM)
137
+
138
+ ```bash
139
+ docker build -t itrialspace-gpu -f docker/Dockerfile.gpu .
140
+
141
+ # Step 3 synthesis β€” mount data, outputs, AND the NodMAISI weights
142
+ docker run --rm --gpus all \
143
+ -e ITRIALSPACE_DATA_DIR=/data -e ITRIALSPACE_OUTPUT_DIR=/out -e NODMAISI_MODELS_DIR=/models \
144
+ -v /host/iTrialSpace:/data -v /host/outputs:/out -v /host/nodmaisi/models:/models \
145
+ --entrypoint python itrialspace-gpu \
146
+ -m itrialspace.synthesis.tools.run_itrialspace_to_ct \
147
+ --audit /out/inserted_masks/mode1_controlled_prevalence/audit.json \
148
+ --config src/itrialspace/synthesis/tools/integration_config.yaml \
149
+ --outdir /out/generated_cts/mode1_controlled_prevalence
150
+ ```
151
+ Built on `nvidia/cuda:12.1.1-cudnn8-runtime` + torch 2.4.1 (cu121). Requires the NVIDIA Container
152
+ Toolkit on the host (`--gpus all`). Adjust the CUDA tag in `docker/Dockerfile.gpu` to match
153
+ your driver.
154
+
155
+ ### Apptainer / Singularity (HPC clusters)
156
+
157
+ Most clusters disallow Docker but support Apptainer (rootless, no daemon):
158
+
159
+ ```bash
160
+ # build from the recipe (run at repo root), or convert a built Docker image
161
+ apptainer build itrialspace.sif docker/itrialspace.def
162
+ # apptainer build itrialspace.sif docker-daemon://itrialspace-gpu:latest
163
+
164
+ # run the CLI (bind data/outputs/weights; --nv exposes GPUs)
165
+ apptainer run --nv \
166
+ --env ITRIALSPACE_DATA_DIR=/data,ITRIALSPACE_OUTPUT_DIR=/out,NODMAISI_MODELS_DIR=/models \
167
+ -B /scratch/.../iTrialSpace:/data,/scratch/.../outputs:/out,/path/models:/models \
168
+ itrialspace.sif config
169
+
170
+ # synthesis
171
+ apptainer exec --nv \
172
+ --env ITRIALSPACE_DATA_DIR=/data,ITRIALSPACE_OUTPUT_DIR=/out,NODMAISI_MODELS_DIR=/models \
173
+ -B /host/iTrialSpace:/data,/host/outputs:/out,/host/models:/models \
174
+ itrialspace.sif \
175
+ python -m itrialspace.synthesis.tools.run_itrialspace_to_ct \
176
+ --audit /out/inserted_masks/mode1_controlled_prevalence/audit.json \
177
+ --config /opt/itrialspace/src/itrialspace/synthesis/tools/integration_config.yaml \
178
+ --outdir /out/generated_cts/mode1_controlled_prevalence
179
+ ```
itrialspace/blinded_doc/nodulemap.md ADDED
@@ -0,0 +1,286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!-- BLINDED COPY for double-blind peer review β€” author, institution, and repository-identifying information removed. Do not use for attribution. -->
2
+
3
+ # NoduleMap β€” embedding graph explorer
4
+
5
+ NoduleMap is an interactive web tool for exploring the **13,140-nodule index** as a
6
+ similarity graph. Each nodule is a node placed by a 2-D embedding (PCA / UMAP / t-SNE) of its
7
+ anatomy-aware *reinsertion* features; edges connect each nodule to its k nearest neighbours.
8
+ You can filter by dataset / label / lobe / zone / side / size, recolour the graph, inspect a
9
+ node's full metadata and an axial CT thumbnail, and export a node's neighbours as a
10
+ candidate-donor list.
11
+
12
+ - **Backend**: FastAPI (default port **8422**), served by `uvicorn`.
13
+ - **Frontend**: single-page sigma.js app (no build step β€” loaded from CDN).
14
+ - **Engine**: FAISS `IndexFlatL2` k-NN (sklearn fallback).
15
+ - **Package**: `itrialspace.apps.nodulemap` Β· **CLI**: `its-nodulemap`.
16
+
17
+ The tool runs in two phases: you **build artifacts once** (embeddings + edges), then
18
+ **serve** them. Everything is path-portable through `itrialspace.config.settings`.
19
+
20
+ ---
21
+
22
+ ## 1. Prerequisites
23
+
24
+ ```bash
25
+ conda activate itrialspace
26
+ pip install -e ".[apps]" # fastapi, uvicorn, faiss-cpu, umap-learn, scikit-learn, pyarrow, …
27
+ cp .env.example .env # set ITRIALSPACE_DATA_DIR (where the 7 profile CSVs live)
28
+ its config # verify the resolved data/output dirs
29
+ ```
30
+
31
+ NoduleMap reads the nodule index from the dataset registry
32
+ (`configs/datasets.example.yaml` β†’ your local `configs/datasets.yaml` β†’ package default),
33
+ which points at `$ITRIALSPACE_DATA_DIR/profiles/{DATASET}_nodule_profiles.csv`. No CT volumes
34
+ are needed to build or browse the graph β€” they're only read on demand for the axial
35
+ thumbnails (step 5).
36
+
37
+ ### Where artifacts live (`$NODULEMAP_ARTIFACTS`)
38
+
39
+ Like the model-weights path, the artifact location is an env var. Set it once in `.env`:
40
+
41
+ ```bash
42
+ NODULEMAP_ARTIFACTS=/path/to/iTrialSpace/outputs/nodulemap_artifacts
43
+ ```
44
+
45
+ - **Default** (if unset): `$ITRIALSPACE_OUTPUT_DIR/nodulemap_artifacts`.
46
+ - Every `its-nodulemap` subcommand and both SLURM jobs read it, so once it's in `.env` you
47
+ can **omit `--outdir` / `--artifact-dir`** entirely.
48
+ - A `--outdir` / `--artifact-dir` flag always wins over the env var (handy for one-offs).
49
+ - To **serve pre-built artifacts** from elsewhere, just point `NODULEMAP_ARTIFACTS` (or the
50
+ flag) at that directory.
51
+
52
+ > **HPC note:** the build is CPU-only and quick (a couple of minutes). On SLURM, source
53
+ > `infra/slurm/env.sh` first so the env, `.env`, and `PYTHONNOUSERSITE=1` are set, then run
54
+ > the same commands below.
55
+
56
+ ---
57
+
58
+ ## 2. Build the artifacts
59
+
60
+ Pick a directory for the artifacts. Anything ending in `_artifacts/` is gitignored; here we
61
+ keep them next to the other outputs:
62
+
63
+ ```bash
64
+ export ART="$ITRIALSPACE_OUTPUT_DIR/nodulemap_artifacts"
65
+
66
+ # Build all three 2-D layouts (PCA + UMAP + t-SNE) on the default feature set
67
+ its-nodulemap build --all-2d --feature-set reinsertion_core --outdir "$ART"
68
+
69
+ # Build the k-NN edge lists for each layout (k = 3, 5, 10, 25)
70
+ for M in PCA_2D UMAP_2D TSNE_2D; do
71
+ its-nodulemap edges --model "$M" --feature-set reinsertion_core --all-k --outdir "$ART"
72
+ done
73
+ ```
74
+
75
+ What gets written (per `model`):
76
+
77
+ | File | Contents |
78
+ |------|----------|
79
+ | `embeddings_<featureset>__<model>.npy` | NΓ—D coordinate matrix |
80
+ | `metadata_<featureset>__<model>.parquet` | per-node metadata (dataset, label, lobe, diameter, …) |
81
+ | `preprocessor_<featureset>__<model>.pkl` | fitted scaler/encoder (for projecting new points) |
82
+ | `info_<featureset>__<model>.yaml` | build parameters + provenance |
83
+ | `edges_<featureset>__<model>__k<k>_<mode>_<scope>.parquet` | k-NN edge list |
84
+
85
+ **Models** (from `configs/features.yaml`): `PCA_2D`, `UMAP_2D`, `TSNE_2D` (layouts) and
86
+ `PCA_32`, `UMAP_16`, `UMAP_32` (higher-D, for search/neighbour quality).
87
+ **Feature sets**: `reinsertion_core` (12 reinsertion columns, **0 NaN β€” recommended**) or
88
+ `core_53` (all 53 columns, needs imputation).
89
+ **Edge options**: `--k`, `--mode {closest,farthest}`, `--scope {cross_dataset,within_dataset}`,
90
+ `--space {weighted,feature_l2,embedding}` (default **weighted** β€” the clinical donor-matching
91
+ metric; see Β§5). `build` also writes one `features_<featureset>.npy` (the standardized search
92
+ space, shared across models).
93
+
94
+ Single-model build instead of `--all-2d`:
95
+
96
+ ```bash
97
+ its-nodulemap build --model UMAP_2D --feature-set reinsertion_core --outdir "$ART"
98
+ its-nodulemap edges --model UMAP_2D --feature-set reinsertion_core --k 5 --outdir "$ART"
99
+ ```
100
+
101
+ ---
102
+
103
+ ## 3. Inspect what you built
104
+
105
+ ```bash
106
+ its-nodulemap info --artifact-dir "$ART"
107
+ ```
108
+
109
+ Lists every embedding (nodes Γ— dims), edge list (edge count), and metadata table
110
+ (nodes Γ— datasets). Use this to confirm a build before serving.
111
+
112
+ ---
113
+
114
+ ## 4. Serve the web app
115
+
116
+ ```bash
117
+ its-nodulemap serve --artifact-dir "$ART" --port 8422
118
+ # β†’ open http://localhost:8422
119
+ ```
120
+
121
+ On a remote/HPC node, forward the port over SSH from your laptop:
122
+
123
+ ```bash
124
+ ssh -N -L 8422:<compute-node>:8422 you@cluster # then browse http://localhost:8422
125
+ ```
126
+
127
+ In the browser: a top **app bar** (brand + version + GitHub + About); left sidebar = filters
128
+ (dataset, label, lobe, zone, side, size, diameter range); centre = the sigma.js graph; right =
129
+ node detail + neighbours; a footer with the research-use disclaimer. Recolour with the
130
+ **color-by** control (`dataset`, `label`, `lobe`, `size`, `zone`, `side`). Hover for a
131
+ tooltip, click a node for full metadata, its axial CT thumbnail, and ranked donor neighbours.
132
+
133
+ > **Use a real browser** (Chrome/Firefox) via the port forward β€” **not** an in-editor
134
+ > webview (e.g. VSCode Simple Browser). sigma.js uses WebGL for click/hover *picking*; in a
135
+ > webview the graph may render but clicking a node won't select it.
136
+
137
+ ### Branding / About
138
+
139
+ The header, favicon, About dialog, and footer disclaimer are baked into
140
+ `apps/nodulemap/frontend/static/index.html` (served live β€” edits show on browser refresh, no
141
+ restart). External links are driven by one `BRAND` config block near the bottom of that file:
142
+
143
+ ```js
144
+ var BRAND = { version: "0.1.0",
145
+ links: { GitHub: "https://github.com/anonymous/itrialspace", Docs: "", Paper: "" } };
146
+ ```
147
+
148
+ Empty links are hidden (no dead links); fill `Docs`/`Paper` to surface them in the bar. The
149
+ lab/institution wordmark and the β€œResearch use only β€” not for clinical use” disclaimer live in
150
+ the same file.
151
+
152
+ ### Axial thumbnails (rendered on the fly)
153
+
154
+ Thumbnails are **generated per request** from the source CT β€” nothing is pre-rendered or saved
155
+ to disk. `GET /api/node/{id}/axial_thumbnail` resolves the node's CT (+ nodule mask) under
156
+ `$ITRIALSPACE_DATA_DIR`, reorients to RAS+, windows the lung, overlays the mask + crosshair +
157
+ R/L/A/P labels, and returns PNG bytes. A small in-memory LRU (last **8** CT volumes) speeds
158
+ repeat clicks; there is **no on-disk PNG cache**. Implications: the viewer stores zero image
159
+ artifacts and always reflects current data, but a node's CT must be present (else the
160
+ thumbnail is omitted), and the first click into a new CT pays one NIfTI read.
161
+
162
+ ### HTTP API (also usable without the UI)
163
+
164
+ | Method | Endpoint | Purpose |
165
+ |--------|----------|---------|
166
+ | GET | `/health` | status + available models |
167
+ | GET | `/api/models` | per-model readiness (embeddings + edges present) |
168
+ | GET | `/api/filters?model=UMAP_2D` | unique filter values + diameter range |
169
+ | GET/POST | `/api/graph` | filtered nodes + edges (params: `vis_model`, `search_model`, `k`, `mode`, `scope`, `color_by`, `datasets`, `label`, `lobe`, …) |
170
+ | GET | `/api/node/{id}` | full node metadata |
171
+ | GET | `/api/node/{id}/axial_thumbnail` | CT slice PNG (needs `$ITRIALSPACE_DATA_DIR` CTs) |
172
+ | GET | `/api/node/{id}/neighbors?k=10&scope=cross_dataset` | ranked neighbours |
173
+ | POST | `/api/export` | export neighbours (csv / json / donors) |
174
+
175
+ ```bash
176
+ curl "http://localhost:8422/health"
177
+ curl "http://localhost:8422/api/graph?vis_model=UMAP_2D&color_by=lobe&datasets=DLCS24,LUNA25&k=5"
178
+ ```
179
+
180
+ ---
181
+
182
+ ## 5. Offline (no server): query & export neighbours
183
+
184
+ Handy for scripting candidate-donor selection straight from the artifacts:
185
+
186
+ ```bash
187
+ # Print the 10 nearest neighbours of a node
188
+ its-nodulemap query --node DLCS24_DLCS_0001_01 --model UMAP_2D --k 10 --artifact-dir "$ART"
189
+
190
+ # Export them β€” formats: csv | json | donors (a reinsertion candidate-donor manifest)
191
+ its-nodulemap export --node DLCS24_DLCS_0001_01 --model UMAP_2D --k 10 \
192
+ --format donors --artifact-dir "$ART" -o "$ITRIALSPACE_OUTPUT_DIR/nodulemap_exports"
193
+ ```
194
+
195
+ Node IDs are `{DATASET}_{annotation_id}`; copy one from the UI, from a metadata parquet, or
196
+ from `its-nodulemap query` output.
197
+
198
+ ### Search backend (`--search-backend`)
199
+
200
+ "Similar donors" / edges are ranked in a **search space**, decoupled from the 2D layout:
201
+
202
+ | backend | what | when |
203
+ |---------|------|------|
204
+ | `weighted` (default) | clinical `ReinsertionMatcher` metric (L1: lobe penalty + cc% + pleural + diameter) | donor matching for reinsertion |
205
+ | `feature_l2` | exact L2 on the standardized 22-D feature vector | neutral anatomy similarity |
206
+ | `embedding` | L2 on the reduced 2D/16D embedding | legacy / comparison only β€” not recommended |
207
+
208
+ ```bash
209
+ its-nodulemap query --node DLCS24_DLCS_0001_01 --search-backend weighted
210
+ its-nodulemap edges --model UMAP_2D --all-k --space weighted # graph edges
211
+ ```
212
+
213
+ Why this matters (measured, see [nodulemap_similarity.md](nodulemap_similarity.md)): searching
214
+ the 2D PCA embedding gives only **0.53** lobe concordance vs **1.00** for `weighted`. The 2D
215
+ embeddings are for *display*; retrieval runs on the full feature space. Run
216
+ `python -m itrialspace.apps.nodulemap.tools.similarity_report` to regenerate the numbers.
217
+
218
+ ---
219
+
220
+ ## 6. Rebuilding after the index changes
221
+
222
+ If you add a dataset or regenerate profiles, rebuild the artifacts (embeddings depend on the
223
+ full index):
224
+
225
+ ```bash
226
+ its-nodulemap build --all-2d --feature-set reinsertion_core --outdir "$ART"
227
+ for M in PCA_2D UMAP_2D TSNE_2D; do
228
+ its-nodulemap edges --model "$M" --feature-set reinsertion_core --all-k --outdir "$ART"; done
229
+ ```
230
+
231
+ The purge verifier and tests assert the removed NLST3D dataset never appears in any artifact:
232
+
233
+ ```bash
234
+ python -m itrialspace.apps.nodulemap.tools.verify_purge --artifact-dir "$ART"
235
+ pytest tests/nodulemap/ # 54 tests: model integrity + NLST3D purge
236
+ ```
237
+
238
+ (`rebuild_nodulemap.sub` runs both automatically after every rebuild.)
239
+
240
+ ---
241
+
242
+ ## 7. On HPC (SLURM): two separate jobs
243
+
244
+ Building is a one-time step (rerun only when the index changes); serving is a long-running
245
+ job. They are **two separate subs** under `infra/slurm/nodulemap/`:
246
+
247
+ ```bash
248
+ # 1) Build artifacts ONCE (CPU, ~minutes; cleans + rebuilds all models + edges, verifies NLST3D purge)
249
+ sbatch infra/slurm/nodulemap/rebuild_nodulemap.sub
250
+
251
+ # 2) Serve (long-running; does NOT rebuild β€” fails fast if artifacts are missing)
252
+ sbatch infra/slurm/nodulemap/nodulemap.sub
253
+ squeue -u $USER # find the NODE it landed on
254
+ tail -f logs/nodulemap-<JOBID>.out # prints node, port, and the SSH-tunnel line
255
+ scancel <JOBID> # stop the server when done
256
+ ```
257
+
258
+ Both default the artifact location to `$ITRIALSPACE_OUTPUT_DIR/nodulemap_artifacts`
259
+ (override with `NODULEMAP_ARTIFACTS=...`); the server port is `8422` (override with
260
+ `NODULEMAP_PORT=...`). Both source `infra/slurm/env.sh`, so the env, `.env` paths, and
261
+ `PYTHONNOUSERSITE` are handled automatically.
262
+
263
+ **Auto-publish:** `nodulemap.sub` reverse-tunnels its port back to `$SLURM_SUBMIT_HOST` (the
264
+ login node you submitted from), so you always open `http://localhost:8422` regardless of which
265
+ compute node it landed on β€” no manual `ssh -L`. With VS Code on the login node it just works.
266
+ Needs passwordless SSH compute→login; disable with `ITS_AUTOTUNNEL=0` (the log prints a manual
267
+ tunnel fallback).
268
+
269
+ ## 8. Troubleshooting
270
+
271
+ | Symptom | Fix |
272
+ |---------|-----|
273
+ | `No embeddings found` on `serve`/`info` | Point `--artifact-dir` at the dir you built into; run `build` first. |
274
+ | Index loads `~/.itrialspace/data` (empty) | `.env` not loaded β€” `set -a; . ./.env; set +a` (or source `infra/slurm/env.sh`), then check `its config`. |
275
+ | `FileNotFoundError: …profiles/*.csv` | `ITRIALSPACE_DATA_DIR` doesn't contain `profiles/{DATASET}_nodule_profiles.csv` β€” see [data.md](data.md). |
276
+ | Graph is empty in the browser | Filters too narrow, or the selected `vis_model` has no edge list β€” build edges for that model. |
277
+ | 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. |
278
+ | Axial thumbnail 404/blank | Raw CTs for that dataset aren't under `$ITRIALSPACE_DATA_DIR` (thumbnails are optional). |
279
+ | First thumbnail click feels slow | Normal β€” the CT is read/decoded once then cached (LRU of 8 volumes); repeats are instant. |
280
+ | `ModuleNotFoundError: faiss/umap/fastapi` | `pip install -e ".[apps]"`. |
281
+ | Port already in use | `--port <other>`; on HPC also change the SSH tunnel's local port. |
282
+
283
+ See also: [retriever.md](retriever.md) β€” the `its-retriever` faceted-search companion tool,
284
+ [architecture.md](architecture.md), and
285
+ [nodulemap_similarity.md](nodulemap_similarity.md) β€” the similarity/donor-matching design
286
+ and the optional appearance-based (radiomics / foundation-model) roadmap.
itrialspace/blinded_doc/pipeline.md ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!-- BLINDED COPY for double-blind peer review β€” author, institution, and repository-identifying information removed. Do not use for attribution. -->
2
+
3
+ # End-to-end pipeline
4
+
5
+ The full flow from raw datasets to evaluation results.
6
+
7
+ ```
8
+ 1. INDEX NoduleIndex loads 7 dataset CSVs β†’ unified DataFrame (13,140 Γ— 53 cols)
9
+ 2. PLAN CohortBuilder applies a TrialSpec (1 of 13 modes) β†’ CohortManifest CSV
10
+ 3. INSERT mask_inserter pastes donor nodule masks into host organ segs @ label 23
11
+ 4. SYNTHESIZE NodMAISI (ControlNet rectified-flow diffusion) β†’ synthetic CT volumes
12
+ 5. EVALUATE VLM zero-shot evaluation (presence / lobe / size)
13
+ 6. EXPLORE NoduleMap (graph) and Retriever (search) over the index
14
+ ```
15
+
16
+ ## Commands per stage
17
+
18
+ ```bash
19
+ # 2. Plan
20
+ its-trials --mode controlled_prevalence --n-cases 200 --output-dir "$ITRIALSPACE_OUTPUT_DIR/manifests/mode1"
21
+
22
+ # 3. Insert
23
+ its-insert run --manifest <manifest.csv> --output-dir "$ITRIALSPACE_OUTPUT_DIR/inserted_masks/mode1"
24
+
25
+ # 4. Synthesize (needs NODMAISI_MODELS_DIR)
26
+ python -m itrialspace.synthesis.tools.run_itrialspace_to_ct \
27
+ --mask-root "$ITRIALSPACE_OUTPUT_DIR/inserted_masks/mode1" \
28
+ --config configs/integration.example.yaml \
29
+ --outdir "$ITRIALSPACE_OUTPUT_DIR/generated_cts/mode1"
30
+
31
+ # 5. Evaluate (VLM)
32
+ python -m itrialspace.evaluation.vlm_eval.build_dataset --profile lung_axial ...
33
+ python -m itrialspace.evaluation.vlm_eval.run_all ...
34
+ ```
35
+
36
+ Each stage also has SLURM scripts under `infra/slurm/`.
itrialspace/blinded_doc/quickstart.md ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!-- BLINDED COPY for double-blind peer review β€” author, institution, and repository-identifying information removed. Do not use for attribution. -->
2
+
3
+ # Quickstart
4
+
5
+ Assumes you've [installed](installation.md) the package and run `cp .env.example .env`.
6
+
7
+ ## Verify your setup
8
+
9
+ ```bash
10
+ its config # prints resolved data dir, output dir, configs dir
11
+ its --help
12
+ ```
13
+
14
+ ## With your datasets
15
+
16
+ Point `ITRIALSPACE_DATA_DIR` at your data root (set in `.env`) so the 7 datasets are laid
17
+ out under `$ITRIALSPACE_DATA_DIR/profiles/` etc. (see [data.md](data.md)):
18
+
19
+ ```bash
20
+ # Build the unified index and print stats
21
+ its index stats
22
+
23
+ # List configured datasets
24
+ its info
25
+ ```
26
+
27
+ ```python
28
+ from itrialspace import NoduleIndex, DatasetRegistry
29
+
30
+ idx = NoduleIndex.from_registry(DatasetRegistry.from_yaml())
31
+ malignant_upper = (
32
+ idx.query()
33
+ .malignant()
34
+ .lobe(["right_upper", "left_upper"])
35
+ .diameter(8, 20)
36
+ .fetch()
37
+ )
38
+ print(len(malignant_upper))
39
+ ```
40
+
41
+ ## Generate a trial cohort manifest
42
+
43
+ ```bash
44
+ its-trials --mode controlled_prevalence --n-cases 200 --prevalence 0.05 \
45
+ --output-dir "$ITRIALSPACE_OUTPUT_DIR/manifests/mode1"
46
+ ```
47
+
48
+ See [trial_modes.md](trial_modes.md) for all 13 modes.
49
+
50
+ ## Insert nodule masks β†’ synthesize CTs
51
+
52
+ ```bash
53
+ # Insert donor masks into host organ segmentations (label 23)
54
+ its-insert run --manifest "$ITRIALSPACE_OUTPUT_DIR/manifests/mode1/<manifest>.csv" \
55
+ --output-dir "$ITRIALSPACE_OUTPUT_DIR/inserted_masks/mode1"
56
+
57
+ # Synthesize CTs (needs NODMAISI_MODELS_DIR; see installation.md)
58
+ python -m itrialspace.synthesis.tools.run_itrialspace_to_ct \
59
+ --mask-root "$ITRIALSPACE_OUTPUT_DIR/inserted_masks/mode1" \
60
+ --config configs/integration.example.yaml \
61
+ --outdir "$ITRIALSPACE_OUTPUT_DIR/generated_cts/mode1"
62
+ ```
63
+
64
+ ## Explore interactively
65
+
66
+ ```bash
67
+ its-nodulemap serve --port 8422 # graph visualization (needs built artifacts)
68
+ its-retriever serve # faceted search API + Streamlit UI
69
+ ```
70
+
71
+ ## On HPC
72
+
73
+ Every stage has SLURM scripts under `infra/slurm/` that are cluster-portable via
74
+ `infra/slurm/env.sh`. See [infra/slurm/README.md](../infra/slurm/README.md).
itrialspace/blinded_doc/reproducibility.md ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!-- BLINDED COPY for double-blind peer review β€” author, institution, and repository-identifying information removed. Do not use for attribution. -->
2
+
3
+ # Reproducibility
4
+
5
+ iTrialSpace is designed for exact reproduction.
6
+
7
+ - **Determinism**: `seed=42` throughout. Per-case placement seeds are derived as
8
+ `SHA-256(trial_name + case_id + nodule_idx + global_seed)` β€” identical inputs produce
9
+ identical outputs.
10
+ - **Audit trails**: mask insertion writes `audit.json` (24-field provenance per case);
11
+ synthesis writes `nodmaisi_audit.json` and a `pipeline_summary.json`.
12
+ - **NIfTI orientation**: all volumes are canonicalized to RAS+ (`nib.as_closest_canonical`)
13
+ before any voxel operation.
14
+ - **Config-pinned paths**: every path comes from `ITRIALSPACE_DATA_DIR` / configs, so a
15
+ run is fully described by its `.env` + config + seed.
16
+ - **HPC orchestration**: `infra/slurm/` scripts are cluster-portable via `env.sh`.
17
+
18
+ ## Reproducing a run
19
+
20
+ ```bash
21
+ cp .env.example .env # set ITRIALSPACE_DATA_DIR, seed defaults to 42
22
+ its-trials --mode <mode> --seed 42 --output-dir <out>
23
+ # inspect <out>/_run_config.json for the exact parameters used
24
+ ```
itrialspace/blinded_doc/retriever.md ADDED
@@ -0,0 +1,246 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!-- BLINDED COPY for double-blind peer review β€” author, institution, and repository-identifying information removed. Do not use for attribution. -->
2
+
3
+ # Retriever β€” browse, visualize & extract lung-nodule data
4
+
5
+ The Retriever is a query engine over the **13,140-nodule index**. Its two everyday uses:
6
+
7
+ 1. **Visualize the nodules** β€” filter the library, browse results as a table, and view each
8
+ nodule's **CT slice** (with mask overlay and radiology window presets); compare similar
9
+ nodules side by side.
10
+ 2. **Extract the data** β€” export the matching nodules (with all metadata **and resolved CT/mask
11
+ file paths**) to **CSV/JSON** for downstream work.
12
+
13
+ It also ranks reinsertion-donor candidates for a target anatomy. It complements
14
+ [NoduleMap](nodulemap.md) (similarity *graph*) with a **table + CT-viewer + export** interface.
15
+
16
+ - **No build step** β€” it loads the index live from the dataset registry; no precomputed artifacts.
17
+ - **Backend**: FastAPI (default **8421**). **UI**: Streamlit (default **8501**).
18
+ - **Package**: `itrialspace.apps.retriever` Β· **CLI**: `its-retriever`.
19
+ - Three modes: **UI** (Streamlit), **API** (HTTP), **CLI** (offline) β€” same engine underneath.
20
+
21
+ ## Three query types
22
+
23
+ | Query | What it does | Engine |
24
+ |-------|--------------|--------|
25
+ | **Faceted search** | filter by dataset, label, lobe, zone, side, position, diameter, pleural/airway distance, population, label source, reinsertion facets, … | `FacetedSearch` |
26
+ | **Similarity** (by example) | given a reference `annotation_id`, the k most similar nodules (weighted k-NN over the 12 reinsertion features) | `SimilarityEngine` |
27
+ | **Reinsertion matching** | given a target anatomy (lobe + cc% + pleural + diameter), the best donor nodules to place there | `ReinsertionMatcher` |
28
+
29
+ Reinsertion matching uses the **same clinical metric** as NoduleMap's `weighted` donor search.
30
+
31
+ ---
32
+
33
+ ## 1. Prerequisites
34
+
35
+ ```bash
36
+ conda activate itrialspace
37
+ pip install -e ".[apps]" # fastapi, uvicorn, streamlit, nibabel, pillow, …
38
+ cp .env.example .env # set ITRIALSPACE_DATA_DIR (the 7 profile CSVs)
39
+ its config # verify resolved paths
40
+ ```
41
+
42
+ The index is read from the dataset registry (`configs/datasets.example.yaml` β†’ local
43
+ `configs/datasets.yaml` β†’ package default) at `$ITRIALSPACE_DATA_DIR/profiles/`. CT volumes are
44
+ only needed for the **CT-slice viewer** and for `--include-paths` exports.
45
+
46
+ ---
47
+
48
+ ## 2. Launch the app (API + UI)
49
+
50
+ The simplest path on HPC is the "hit and run" sub, which starts **both** servers in one job:
51
+
52
+ ```bash
53
+ sbatch infra/slurm/retriever/app.sub
54
+ tail -f logs/retriever-app-<JOBID>.out # prints node, ports, and the SSH-tunnel line
55
+ ```
56
+
57
+ Or run locally:
58
+
59
+ ```bash
60
+ its-retriever serve --port 8421 & # FastAPI
61
+ streamlit run src/itrialspace/apps/retriever/ui/app.py -- --api-url http://localhost:8421
62
+ # β†’ open http://localhost:8501
63
+ ```
64
+
65
+ From your laptop, forward the **UI** port and open it in a real browser:
66
+
67
+ ```bash
68
+ ssh -N -L 8501:<node>:8501 you@<login-node> # β†’ http://localhost:8501
69
+ ```
70
+
71
+ You only need **8501**: the Streamlit server calls the API on the compute node itself
72
+ (`localhost:8421` *there*), so that hop never leaves the node. Forward **8421 too only if you
73
+ want the raw API / `/docs`** from your laptop (`-L 8421:<node>:8421`). The UI also runs in
74
+ **direct mode** β€” loads the index in-process, no API β€” if you omit `--api-url`.
75
+
76
+ ---
77
+
78
+ ## 3. Visualize the nodules (the UI)
79
+
80
+ The Streamlit UI has a left **Filters** sidebar and a **Mode** switch β€” Search / Similarity /
81
+ Matcher:
82
+
83
+ - **Search** β†’ set facets in the sidebar, hit **Search**, get a results **table**. Pick any row
84
+ in **Nodule detail** to render its **axial CT slice** (nodule mask overlaid), then export
85
+ (Β§4).
86
+ - **Similarity** β†’ enter a reference `annotation_id` β†’ top-k similar nodules as a table **plus a
87
+ side-by-side CT comparison** so you can eyeball how alike they are.
88
+ - **Matcher** β†’ choose a target lobe (+ optional cc% / pleural / diameter / label) β†’ ranked
89
+ donor candidates with CT views and full metadata.
90
+
91
+ All CT views share **window presets**: `lung` (default), `mediastinum`, `soft_tissue`, `bone`
92
+ (centre/width from `NIfTISlicer.WINDOW_PRESETS`). Volumes are read on demand from
93
+ `$ITRIALSPACE_DATA_DIR` and reoriented to RAS+; if a dataset's CTs aren't present the table and
94
+ metadata still work, only the image is omitted.
95
+
96
+ Headless / programmatic CT rendering is available via the API (`/ct/slice`, `/ct/nodule-view`,
97
+ `/ct/info`) or `engine.get_slice(...)` / `engine.get_nodule_view(...)`.
98
+
99
+ ---
100
+
101
+ ## 4. Extract the data (CSV / JSON)
102
+
103
+ Export the **matching nodules** β€” every column of the search result **plus**, when
104
+ `include_paths` is on (default), the **resolved absolute paths** `ct_path`,
105
+ `nodule_mask_path`, `organ_seg_path` (so the CSV is directly usable downstream). Columns
106
+ include identity (`annotation_id`, `dataset`, `patient_id`), label, anatomy (`lobe_name`,
107
+ `lung_side`, `lung_zone`, `central_peripheral`), `nodule_mean_diam_mm`, `pleural_distance_mm`,
108
+ and the `reinsertion_*` fields.
109
+
110
+ Three equivalent ways:
111
+
112
+ ```bash
113
+ # A) CLI β€” write a CSV (or --format json); --no-paths to omit resolved paths
114
+ its-retriever export --label 1 --lobe right_lung_upper_lobe --diam-min 8 \
115
+ --format csv -o "$ITRIALSPACE_OUTPUT_DIR/malignant_rul.csv"
116
+ ```
117
+
118
+ ```bash
119
+ # B) API β€” returns a downloadable file
120
+ curl -X POST localhost:8421/export -H 'Content-Type: application/json' \
121
+ -d '{"filters":{"label":1,"lobe":["right_lung_upper_lobe"]},"format":"csv","include_paths":true}' \
122
+ -o malignant_rul.csv
123
+ ```
124
+
125
+ **C) UI** β€” every result view (Search / Similarity / Matcher) has an **Export** panel with
126
+ one-click **Download CSV** / **Download JSON** buttons (the current result, downloaded straight
127
+ to your machine).
128
+
129
+ JSON exports also embed the `filters` used and a result count, so an export is self-describing
130
+ and reproducible.
131
+
132
+ ---
133
+
134
+ ## 5. CLI quickstart (offline, no server)
135
+
136
+ ```bash
137
+ its-retriever info # index summary + per-dataset stats
138
+ its-retriever search --label 1 --lobe right_lung_upper_lobe --diam-min 8 --limit 20
139
+ its-retriever similar --id DLCS_0007_01 --k 10
140
+ its-retriever match --lobe left_lung_lower_lobe --diameter 12 --cc-pct 60 --k 10
141
+ its-retriever detail --id DLCS_0007_01 # full record + resolved paths
142
+ ```
143
+
144
+ IDs are `annotation_id` values (e.g. `DLCS_0007_01`) β€” note this differs from NoduleMap's
145
+ `{DATASET}_{annotation_id}` node IDs.
146
+
147
+ > The CLI flags expose a **subset** of the facets. The full filter surface (`SearchFilters`) β€”
148
+ > `central_peripheral`, airway distance, every `reinsertion_*` facet, `n_nodules` range,
149
+ > sampling (`sample_n`/`sample_seed`), `offset`, and `sort_by` β€” is available via the API
150
+ > (`POST /search`) and the UI.
151
+
152
+ ---
153
+
154
+ ## 6. HTTP API
155
+
156
+ | Method | Endpoint | Purpose |
157
+ |--------|----------|---------|
158
+ | GET | `/health` | version, nodule count, datasets |
159
+ | GET | `/filters` | available facet values |
160
+ | POST | `/search` | faceted search (JSON `SearchFilters`) |
161
+ | POST | `/similar` | query-by-example similarity |
162
+ | POST | `/matcher` | reinsertion donor matching |
163
+ | GET | `/nodule/{annotation_id}` | full detail + resolved paths |
164
+ | GET | `/ct/slice`, `/ct/nodule-view`, `/ct/info` | CT slice PNG / nodule view / volume info |
165
+ | POST | `/export` | download results (csv/json, `include_paths`) |
166
+
167
+ Interactive docs at `http://localhost:8421/docs`.
168
+
169
+ ---
170
+
171
+ ## 7. Run it on SLURM (step by step)
172
+
173
+ There's **no build step** β€” `app.sub` starts the API + Streamlit UI in one job. Scripts live
174
+ under `infra/slurm/retriever/` and all source `infra/slurm/env.sh` (env, `.env`, conda). Ports
175
+ come from `$RETRIEVER_API_PORT` / `$RETRIEVER_UI_PORT` / `$RETRIEVER_JUPYTER_PORT`
176
+ (default **8421 / 8501 / 8888**).
177
+
178
+ ```bash
179
+ # 1) Launch (API on 8421 + Streamlit UI on 8501, in one job)
180
+ sbatch infra/slurm/retriever/app.sub
181
+
182
+ # 2) Open the UI β€” that's it
183
+ # The job auto-publishes its port back to the login node you submitted from, so it's
184
+ # always at the SAME address no matter which compute node it landed on. With VS Code on
185
+ # the login node, just open:
186
+ http://localhost:8501
187
+
188
+ # 3) Stop when done
189
+ scancel <JOBID>
190
+ ```
191
+
192
+ **Auto-publish (no manual tunnel):** `app.sub` reverse-tunnels its ports back to
193
+ `$SLURM_SUBMIT_HOST` (the login node you ran `sbatch` from). So you connect at
194
+ `login-node:8501` every time β€” the *"job moved to a new node"* problem is gone. It needs
195
+ passwordless SSH compute→login (standard on HPC); disable with `ITS_AUTOTUNNEL=0`.
196
+ `tail -f logs/retriever-app-<JOBID>.out` shows whether the auto-tunnel came up.
197
+
198
+ **Manual fallback** (if you set `ITS_AUTOTUNNEL=0`, or compute→login SSH is blocked) — forward
199
+ the UI port to the node from your laptop:
200
+
201
+ ```bash
202
+ squeue -u $USER # read the node, e.g. node004
203
+ ssh -N -L 8501:<node>:8501 you@<login-node> # β†’ http://localhost:8501
204
+ ```
205
+
206
+ **Why only one port:** 8501 is the Streamlit UI (what the browser talks to). The UI calls the
207
+ API on the compute node itself (`localhost:8421` *there*), so only **8501** is published/needed.
208
+ The API (8421) is also auto-published β€” use it only for the raw API / `http://localhost:8421/docs`.
209
+
210
+ Other scripts:
211
+
212
+ ```bash
213
+ sbatch infra/slurm/retriever/jupyter.sub # JupyterLab (8888) + API, for notebook use
214
+ sbatch infra/slurm/retriever/cli.sub # one-off batch CLI queries
215
+ ```
216
+
217
+ Notebook helper: `from itrialspace.apps.retriever.notebook import RetrieverClient`.
218
+
219
+ ---
220
+
221
+ ## 8. Retriever vs NoduleMap
222
+
223
+ | | **Retriever** | **NoduleMap** |
224
+ |--|---------------|---------------|
225
+ | Interface | table + CT viewer + export | interactive similarity graph |
226
+ | Strength | precise filtering, CT inspection, **data export** | visual structure of the whole library |
227
+ | Build step | none (live) | embeddings + edges (one-time) |
228
+ | Donor matching | `match` / `/matcher` | `weighted` search backend |
229
+
230
+ They share the index and the `ReinsertionMatcher` metric β€” Retriever to *query/inspect/export*,
231
+ NoduleMap to *see the landscape*.
232
+
233
+ ---
234
+
235
+ ## 9. Troubleshooting
236
+
237
+ | Symptom | Fix |
238
+ |---------|-----|
239
+ | Index loads `~/.itrialspace/data` (empty) | `.env` not loaded β€” `set -a; . ./.env; set +a` (or source `infra/slurm/env.sh`); check `its config`. |
240
+ | `FileNotFoundError: …profiles/*.csv` | `ITRIALSPACE_DATA_DIR` lacks `profiles/{DATASET}_nodule_profiles.csv` β€” see [data.md](data.md). |
241
+ | `ModuleNotFoundError: fastapi/streamlit` | `pip install -e ".[apps]"`. |
242
+ | 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). |
243
+ | Streamlit can't reach the API | start the API first; pass the matching `--api-url`; forward **both** ports. |
244
+ | Port already in use | change `--port` (and the matching env var / SSH tunnel). |
245
+
246
+ See also: [NoduleMap](nodulemap.md), [architecture.md](architecture.md).
itrialspace/blinded_doc/running_the_pipeline.md ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!-- BLINDED COPY for double-blind peer review β€” author, institution, and repository-identifying information removed. Do not use for attribution. -->
2
+
3
+ # Running the pipeline (runbook + smoke test)
4
+
5
+ A self-contained, copy-paste guide to run iTrialSpace end-to-end on an HPC cluster
6
+ (SLURM) β€” for **all 13 trial modes**, from a 5-case smoke test up to full runs. Every
7
+ command is here; you should not need to invent any.
8
+
9
+ > ⚠️ **The scripts ship as a QUICK DEMO run with deliberately small numbers** (β‰ˆ5 cases
10
+ > per mode) so the whole pipeline finishes in minutes for validation. These are **not**
11
+ > the paper/production sizes. To reproduce the real run, change the case counts as shown
12
+ > in **[Β§5](#5-run-size--demo-vs-paperproduction-run)** (which also lists the exact
13
+ > paper-run values and the file + line to edit for every mode).
14
+
15
+ **Pipeline:** `trials (manifest) β†’ insertion (label-23 masks + audit) β†’ synthesis (CT)`
16
+ β†’ optional evaluation (VLM).
17
+
18
+ ---
19
+
20
+ ## 0. One-time setup
21
+
22
+ ```bash
23
+ git clone <repo-url> && cd itrialspace # always run commands from the repo root
24
+
25
+ # Create the environment (matches the verified dev versions). One of:
26
+ conda env create -f environment.yml # curated, pinned
27
+ # or an exact clone:
28
+ # conda env create -f environment.lock.yml
29
+
30
+ # Configure paths/env for this machine
31
+ cp .env.example .env
32
+ ```
33
+
34
+ Edit `.env` (read automatically by every SLURM job via `infra/slurm/env.sh`):
35
+
36
+ ```bash
37
+ ITRIALSPACE_DATA_DIR=/scratch/.../iTrialSpace # INPUTS: raw_ct/ masks/ profiles/ meta/
38
+ ITRIALSPACE_OUTPUT_DIR=/scratch/.../my_outputs # OUTPUTS: manifests/ inserted_masks/ generated_cts/
39
+ ITRIALSPACE_CONDA_ENV=itrialspace # the conda env to activate
40
+ NODMAISI_MODELS_DIR=/path/to/nodmaisi/models # synthesis weights (Step 3 only)
41
+ SLURM_PARTITION_GPU=vram48 # your GPU partition
42
+ SLURM_PARTITION_CPU=defq # your CPU partition
43
+ ```
44
+
45
+ Verify resolution:
46
+
47
+ ```bash
48
+ its config # prints the resolved data/output dirs and config locations
49
+ ```
50
+
51
+ > **Cluster notes baked in** (no action needed): jobs run with `PYTHONNOUSERSITE=1`
52
+ > (isolated from `~/.local`) and put the env's CUDA libs on `LD_LIBRARY_PATH` (so cuDNN
53
+ > initializes). `#SBATCH --partition/--account/--time` are in each `.sub` β€” edit them for
54
+ > your cluster. **Always `sbatch` from the repo root** so `env.sh` is found.
55
+
56
+ ---
57
+
58
+ ## 1. The easy way β€” one command per mode
59
+
60
+ `infra/slurm/run_pipeline.sh` chains all three stages with SLURM dependencies and builds
61
+ the manifest/case lists the array jobs need.
62
+
63
+ ```bash
64
+ # Full pipeline for one mode (trials β†’ insertion β†’ synthesis):
65
+ infra/slurm/run_pipeline.sh 1
66
+
67
+ # All 13 modes:
68
+ for m in $(seq 1 13); do infra/slurm/run_pipeline.sh $m; done
69
+
70
+ # Just one stage:
71
+ infra/slurm/run_pipeline.sh 2 trials # manifests only
72
+ infra/slurm/run_pipeline.sh 2 insert # insertion (after trials done)
73
+ infra/slurm/run_pipeline.sh 2 synth # synthesis (after insertion done)
74
+ ```
75
+
76
+ Run size comes from each mode's `.sub` (see Β§5). To understand or customize the stages,
77
+ read Β§2–§4 β€” they are exactly what the helper runs.
78
+
79
+ ---
80
+
81
+ ## 2. Step 1 β€” Trials (generate cohort manifests)
82
+
83
+ One `sbatch` per mode. Each writes manifest CSV/JSON to
84
+ `$ITRIALSPACE_OUTPUT_DIR/manifests/mode<N>_*/`.
85
+
86
+ ```bash
87
+ sbatch infra/slurm/trials/mode1_controlled_prevalence.sub
88
+ sbatch infra/slurm/trials/mode2_size_detection_curve.sub
89
+ # ... mode3 … mode13 (filenames below)
90
+ ```
91
+
92
+ | Mode | Script | Produces |
93
+ |------|--------|----------|
94
+ | 1 | `mode1_controlled_prevalence.sub` | 1 manifest |
95
+ | 2 | `mode2_size_detection_curve.sub` | per size bucket |
96
+ | 3 | `mode3_location_sensitivity.sub` | per lobe |
97
+ | 4 | `mode4_demographic_stratification.sub` | per stratum |
98
+ | 5 | `mode5_counterfactual.sub` | per varied value |
99
+ | 6 | `mode6_cross_dataset.sub` | per dataset |
100
+ | 7 | `mode7_bootstrap_confidence.sub` | per replicate |
101
+ | 8 | `mode8_algorithm_comparison.sub` | 1 manifest |
102
+ | 9 | `mode9_screening_simulation.sub` | per round |
103
+ | 10 | `mode10_multi_nodule_realism.sub` | 2 (single + multi sub-cohorts) |
104
+ | 11 | `mode11_digital_twin_isolation.sub` | per dataset |
105
+ | 12 | `mode12_digital_twin_complete.sub` | per dataset |
106
+ | 13 | `mode13_digital_twin_cross.sub` | per hostΓ—donor pair |
107
+
108
+ Verify:
109
+
110
+ ```bash
111
+ ls $ITRIALSPACE_OUTPUT_DIR/manifests/mode1_controlled_prevalence/ # NLST_cohort.csv …
112
+ ```
113
+
114
+ ---
115
+
116
+ ## 3. Step 2 β€” Insertion (paste nodule masks)
117
+
118
+ Reads a mode's manifests and writes a combined label-23 mask per case plus an
119
+ `audit.json` per manifest. Uses the **array** script (one task per manifest):
120
+
121
+ ```bash
122
+ source infra/slurm/env.sh # defines $ITRIALSPACE_OUTPUT_DIR etc.
123
+ M=1 # mode number
124
+ DIR=$(ls -d $ITRIALSPACE_OUTPUT_DIR/manifests/mode${M}_* | head -1)
125
+ ML=$ITRIALSPACE_OUTPUT_DIR/manifest_lists/mode${M}.txt
126
+ mkdir -p "$(dirname "$ML")"; ls "$DIR"/*.csv | sort > "$ML"
127
+
128
+ sbatch --array=0-$(( $(wc -l < "$ML") - 1 )) \
129
+ --export=ALL,MANIFEST_LIST="$ML" \
130
+ infra/slurm/mask_inserter/mode${M}_insert_masks_array.sub
131
+ ```
132
+
133
+ Preview without writing files: append `,DRY_RUN=true` to `--export`.
134
+
135
+ Verify:
136
+
137
+ ```bash
138
+ find $ITRIALSPACE_OUTPUT_DIR/inserted_masks/mode${M}_*/ -name audit.json
139
+ find $ITRIALSPACE_OUTPUT_DIR/inserted_masks/mode${M}_*/ -name '*_mask.nii.gz' | wc -l
140
+ ```
141
+
142
+ ---
143
+
144
+ ## 4. Step 3 β€” Synthesis (generate CTs) β€” **GPU + model weights**
145
+
146
+ Needs `NODMAISI_MODELS_DIR` set and the `synthesis` extra installed. One array job per
147
+ manifest's `audit.json`, one task per case. Case IDs must be the **mask-filename stems**
148
+ (`infra/slurm/_gen_caselist.py` does this):
149
+
150
+ ```bash
151
+ source infra/slurm/env.sh
152
+ M=1
153
+ audit=$(find $ITRIALSPACE_OUTPUT_DIR/inserted_masks/mode${M}_*/ -name audit.json | sort | head -1)
154
+ cl=$ITRIALSPACE_OUTPUT_DIR/nodmaisi_case_lists/mode${M}.txt
155
+ n=$(python infra/slurm/_gen_caselist.py "$audit" "$cl") # prints N cases
156
+
157
+ sbatch --array=0-$((n-1)) \
158
+ --export=ALL,AUDIT_PATH="$audit",CASE_LIST="$cl",OUT_DIR="$ITRIALSPACE_OUTPUT_DIR/generated_cts/mode${M}" \
159
+ infra/slurm/synthesis/mode1_nodmaisi_array.sub
160
+ ```
161
+
162
+ (`mode1_nodmaisi_array.sub` is generic β€” driven by the `AUDIT_PATH`/`CASE_LIST`/`OUT_DIR`
163
+ env vars, so it works for any mode. For modes with multiple manifests, repeat per
164
+ `audit.json`.) Validate inputs without a GPU first by running the bridge with `--dry-run`
165
+ (see [walkthrough_mode1.md](walkthrough_mode1.md)).
166
+
167
+ Verify, per case directory:
168
+
169
+ ```bash
170
+ ls $ITRIALSPACE_OUTPUT_DIR/generated_cts/mode${M}/*/
171
+ # synthetic_ct.nii.gz input_mask.nii.gz host_ct.nii.gz qc/*.png nodmaisi_audit.json
172
+ find $ITRIALSPACE_OUTPUT_DIR/generated_cts/mode${M} -name synthetic_ct.nii.gz | wc -l
173
+ ```
174
+
175
+ ---
176
+
177
+ ## 5. Run size β€” demo vs paper/production run
178
+
179
+ **What ships is a quick demo (small numbers), not the paper run.** Run size lives in each
180
+ mode's **trials `.sub`** (`infra/slurm/trials/mode<N>_*.sub`). The paper value is commented
181
+ right above the active demo value, e.g.:
182
+
183
+ ```bash
184
+ # infra/slurm/trials/mode1_controlled_prevalence.sub
185
+ # N_CASES=1000 # paper run (commented for 5-case demo) ← restore this
186
+ N_CASES=5 # demo
187
+ ```
188
+
189
+ ### Demo vs paper values, and exactly what to edit
190
+
191
+ For modes 1–10, edit the variable in the named file. The "paper run" column is the
192
+ original production configuration.
193
+
194
+ | Mode | File (`infra/slurm/trials/…`) | Variable(s) | Demo | **Paper run** |
195
+ |------|------------------------------|-------------|------|---------------|
196
+ | 1 Controlled prevalence | `mode1_controlled_prevalence.sub` | `N_CASES` | 5 | **1000** |
197
+ | 2 Size detection curve | `mode2_size_detection_curve.sub` | `N_PER_BUCKET` | 5 | **100** (Γ—6 buckets) |
198
+ | 3 Location sensitivity | `mode3_location_sensitivity.sub` | `N_PER_LOBE` | 5 | **100** (Γ—5 lobes) |
199
+ | 4 Demographic strat. | `mode4_demographic_stratification.sub` | `N_PER_STRATUM` | 5 | **200** (Γ—~4 strata) |
200
+ | 5 Counterfactual | `mode5_counterfactual.sub` | `N_CASES` (per variant) | 5 | **500** |
201
+ | 6 Cross-dataset | `mode6_cross_dataset.sub` | `N_CASES` (per dataset) | 5 | **300** |
202
+ | 7 Bootstrap confidence | `mode7_bootstrap_confidence.sub` | `N_CASES`, `N_BOOTSTRAP` | 5, 3 | **200, 20** |
203
+ | 8 Algorithm comparison | `mode8_algorithm_comparison.sub` | `N_CASES` | 5 | **500** |
204
+ | 9 Screening simulation | `mode9_screening_simulation.sub` | `N_CASES_PER_ROUND` (`N_ROUNDS`=3) | 5 | **500** |
205
+ | 10 Multi-nodule realism | `mode10_multi_nodule_realism.sub` | `N_CASES` (`MULTI_NODULE_FRACTION`=0.25) | 5 | **500** |
206
+
207
+ For the digital-twin modes 11–13, the demo restricts datasets and caps patients/nodules;
208
+ the paper run enumerates **all 7 datasets** with no caps:
209
+
210
+ | Mode | File | Demo | **Paper run** (restore) |
211
+ |------|------|------|--------------------------|
212
+ | 11 Isolation | `mode11_digital_twin_isolation.sub` | `DATASETS=("DLCS24")`; `--max-patients 5 --max-nodules-per-patient 1` | `DATASETS=(all 7)`; `--all-patients` (β‰ˆ13k cases) |
213
+ | 12 Complete | `mode12_digital_twin_complete.sub` | `DATASETS=("DLCS24")`; `--max-patients 5` | `DATASETS=(all 7)`; `--all-patients` (β‰ˆ8k cases) |
214
+ | 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) |
215
+
216
+ In each `.sub` the paper values are present as commented lines (`# … # paper run`) /
217
+ the full `DATASETS=(…)` arrays β€” uncomment them and comment out the demo lines.
218
+
219
+ ### Quicker: override without editing files (optional)
220
+
221
+ If the count variables are exposed as `${VAR:-default}` (ask the maintainers / see the
222
+ `.sub`), you can override per submission instead of editing:
223
+
224
+ ```bash
225
+ N_CASES=1000 infra/slurm/run_pipeline.sh 1 trials
226
+ N_PER_BUCKET=100 infra/slurm/run_pipeline.sh 2 trials
227
+ MAX_DONOR_NODULES=250 infra/slurm/run_pipeline.sh 13 trials
228
+ ```
229
+
230
+ > **Heads-up:** the paper run is large (mode 13 alone β‰ˆ 79k cases) and the synthesis stage
231
+ > is GPU-bound (~1.5–3 min/case). Scale up deliberately and use the array/chunking in the
232
+ > SLURM scripts.
233
+
234
+ ---
235
+
236
+ ## 6. Monitoring
237
+
238
+ ```bash
239
+ squeue -u $USER # queue
240
+ sacct -u $USER -S today --format=JobID,JobName%22,State,Elapsed,ExitCode
241
+ tail -f logs/<jobname>_<jobid>.out # live log
242
+ ```
243
+ Logs are written to `logs/` in the repo (gitignored; kept via `.gitkeep`).
244
+
245
+ ---
246
+
247
+ ## 7. Verified smoke-test result (reference)
248
+
249
+ All 13 modes were run end-to-end at the smoke size in the `itrialspace` env on an A6000:
250
+
251
+ | Stage | Modes 1–10 | Modes 11/12/13 |
252
+ |-------|-----------|----------------|
253
+ | Trials | 10/10 manifests | 5 / 7 / 5 rows |
254
+ | Insertion | 35/35 tasks, masks + audits | 5 masks each |
255
+ | Synthesis | 50 synthetic CTs (5/mode) | 5 CTs each |
256
+
257
+ > **Mode 10 note:** it is the only mode that creates **two sub-cohorts** (75%
258
+ > single-nodule + 25% multi-nodule). At 5 cases that's 4 single + 1 multi, so it has two
259
+ > `audit.json` files; synthesize **both** to get all 5 CTs (the helper in Β§1 and the loop
260
+ > in Β§4 do this automatically).
261
+
262
+ ---
263
+
264
+ ## 8. Troubleshooting
265
+
266
+ | Symptom | Cause / fix |
267
+ |---------|-------------|
268
+ | Job "COMPLETED" in 0s but no output | Submitted from outside the repo root, or `logs/` missing β†’ `env.sh` not found. Submit from repo root. |
269
+ | `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). |
270
+ | `ModuleNotFoundError` (torch/pytest/…) | The env is shadowed by `~/.local`. Jobs set `PYTHONNOUSERSITE=1` automatically; for manual runs, prefix `PYTHONNOUSERSITE=1`. |
271
+ | `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`). |
272
+ | 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`. |
273
+ | Wrong env activated | Set `ITRIALSPACE_CONDA_ENV` in `.env`. |
274
+
275
+ See also: [walkthrough_mode1.md](walkthrough_mode1.md) (narrated single-mode walkthrough),
276
+ [configuration.md](configuration.md), [installation.md](installation.md),
277
+ [infra/slurm/README.md](../infra/slurm/README.md).
itrialspace/blinded_doc/trial_modes.md ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!-- BLINDED COPY for double-blind peer review β€” author, institution, and repository-identifying information removed. Do not use for attribution. -->
2
+
3
+ # Trial modes
4
+
5
+ `its-trials --mode <name>` generates cohort manifests. The 13 modes:
6
+
7
+ | # | Mode name | Purpose |
8
+ |---|-----------|---------|
9
+ | 1 | `controlled_prevalence` | Vary cancer prevalence |
10
+ | 2 | `size_detection_curve` | Detection sensitivity by nodule size (FROC) |
11
+ | 3 | `location_sensitivity` | Detection by anatomical location (lobe) |
12
+ | 4 | `demographic_stratification` | Performance across demographics |
13
+ | 5 | `counterfactual` | Same patient Β± nodule |
14
+ | 6 | `cross_dataset` | Cross-dataset generalization |
15
+ | 7 | `bootstrap_confidence` | Statistical confidence intervals |
16
+ | 8 | `algorithm_comparison` | Standardized model comparison |
17
+ | 9 | `screening_simulation` | Multi-round with prevalence decay |
18
+ | 10 | `multi_nodule` | Multi-nodule context impact (companions) |
19
+ | 11 | `digital_twin_isolation` | Per-nodule isolation within host anatomy |
20
+ | 12 | `digital_twin_complete` | All native nodules per CT scan |
21
+ | 13 | `digital_twin_cross` | Cross-patient host anatomy + donor nodules |
22
+
23
+ Modes 11–13 (digital twins) match at the **CT-scan level** (`host_ct_path ==
24
+ donor_ct_path`), enabling task-level fidelity comparison of AI on real vs. synthetic
25
+ versions of the same anatomy.
26
+
27
+ ```bash
28
+ its-trials --mode size_detection_curve --n-per-bucket 100 \
29
+ --output-dir "$ITRIALSPACE_OUTPUT_DIR/manifests/mode2"
30
+ its-trials --help # all per-mode options
31
+ ```
itrialspace/blinded_doc/vlm_eval.md ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!-- BLINDED COPY for double-blind peer review β€” author, institution, and repository-identifying information removed. Do not use for attribution. -->
2
+
3
+ # VLM evaluation β€” vision-language models on lung-nodule CT
4
+
5
+ `itrialspace.evaluation.vlm_eval` evaluates **vision-language models (VLMs)** on lung-nodule
6
+ CT slices β€” zero-shot, on **synthetic** (iTrialSpace-generated) and **real** CTs.
7
+
8
+ - **Models (3):** **BiomedCLIP** (contrastive, `open_clip`), **LLaVA-Med** (7B generative),
9
+ **MedGemma** (4B generative). BiomedCLIP is light; the two generative models are heavy.
10
+ - **Tasks (3):** **presence** (binary), **lobe** (5-class localisation), **size** (4-class bucket).
11
+ - **Image conditions (4):** `plain`, `bbox`, `contour`, `bbox_contour` β€” "spatial-guidance"
12
+ overlays that test whether marking the lesion changes VLM accuracy.
13
+ - **Optional extra**, GPU-backed. Module-driven (no console script).
14
+
15
+ ## Pipeline
16
+
17
+ ```
18
+ manifests + generated CTs ─┐ β”Œβ”€ run_biomedclip ─┐
19
+ (synthetic) β”œβ”€ build_dataset ────── run_llava_med β”œβ”€ metrics ─ cross_model
20
+ profiles + raw CTs β”€β”€β”€β”€β”€β”€β”€β”€β”˜ build_real_dataset └─ run_medgemma β”€β”˜ + plots _comparison
21
+ β†’ eval_dataset.csv
22
+ + slices/ (+ overlays via --overlays)
23
+ ```
24
+
25
+ `runners/run_conditions.py` wraps a model across all 4 image conditions; `run_all.py` chains
26
+ build β†’ infer β†’ metrics β†’ plots.
27
+
28
+ > **Implementation reference.** For the architecture, data model, module responsibilities, and
29
+ > extension points of this subsystem, see [vlm_eval_implementation.md](vlm_eval_implementation.md).
30
+
31
+ ### Ground truth
32
+
33
+ `eval_dataset.csv` carries the label for each task: `ground_truth_presence`
34
+ (`present`/`absent`), `ground_truth_lobe` (5 classes: `right_lung_{upper,middle,lower}_lobe`,
35
+ `left_lung_{upper,lower}_lobe`), and `ground_truth_size_bucket` (`<5mm`, `5-10mm`, `10-20mm`,
36
+ `>20mm`). For **synthetic** cases the labels are **known by construction** (insertion lobe +
37
+ chosen effective diameter; `absent` for the nodule-free counterfactual cases); for **real**
38
+ cases they come from the source-dataset annotations (lobe normalised, diameter binned, all
39
+ `present`). Scoring: `correct = (prediction == ground_truth)`, accuracy = mean, per condition.
40
+ Full details in the [dataset card](dataset_card.md#vlm-ground-truth).
41
+
42
+ ---
43
+
44
+ ## 1. Prerequisites
45
+
46
+ ```bash
47
+ conda activate itrialspace
48
+ pip install -e ".[vlm]" # transformers, open_clip_torch, nibabel, pillow, matplotlib, seaborn
49
+ # PyTorch (CUDA build) is separate β€” see docs/installation.md
50
+ cp .env.example .env # ITRIALSPACE_DATA_DIR / _OUTPUT_DIR
51
+ ```
52
+
53
+ - **GPU** required for LLaVA-Med / MedGemma; BiomedCLIP runs on GPU or (slowly) CPU.
54
+ - **Model weights** load from **Hugging Face** by default (`google/medgemma-…`, the BiomedCLIP
55
+ open_clip id, the LLaVA-Med id) β€” no bundled weights dir. Ensure HF access / a warm
56
+ `~/.cache/huggingface` (or pass `--cache-dir`); pass a **local checkpoint** via each model's
57
+ `model_id` if you have one offline.
58
+ - **MedGemma** needs cuDNN 9 on `LD_LIBRARY_PATH` β€” handled automatically by `infra/slurm/env.sh`.
59
+
60
+ ---
61
+
62
+ ## 2. End-to-end demo (extract slices β†’ run a VLM)
63
+
64
+ This demo runs the whole VLM workflow on the **demo pipeline outputs** in
65
+ `$ITRIALSPACE_OUTPUT_DIR` (e.g. `/scratch/.../outputs_iTrialSpace/`), which holds the 5-case-per-mode
66
+ `generated_cts/`, `manifests/`, and `inserted_masks/` from a demo pipeline run (see
67
+ [running_the_pipeline.md](running_the_pipeline.md)). It's a **small smoke run**, not the paper run
68
+ (Β§4 scales it up).
69
+
70
+ ### SLURM jobs β€” build β†’ run β†’ analyze
71
+
72
+ The whole workflow is three env-driven jobs in
73
+ [`infra/slurm/vlm_eval/`](../infra/slurm/vlm_eval/) (full guide: its
74
+ [README](../infra/slurm/vlm_eval/README.md)). Defaults = this small demo.
75
+
76
+ ```bash
77
+ # 1) BUILD demo eval sets (synthetic modes 1–3, + a small real set)
78
+ sbatch infra/slurm/vlm_eval/build_dataset.sub # synthetic Β· lung_axial
79
+ VLM_SET=real sbatch infra/slurm/vlm_eval/build_dataset.sub # real Β· lung_axial
80
+ # (add PROFILE=lung_axial_medgemma to also build the MedGemma profile)
81
+
82
+ # 2) RUN a model across all 4 conditions Γ— 3 tasks
83
+ B=$ITRIALSPACE_OUTPUT_DIR/vlm_eval_demo
84
+ MODEL=biomedclip EVAL_DIR=$B/lung_axial sbatch infra/slurm/vlm_eval/run_vlm.sub
85
+ # MODEL=llava_med | medgemma (MedGemma β†’ EVAL_DIR=$B/lung_axial_medgemma)
86
+
87
+ # 3) ANALYZE (tables, figures, stats, report.md)
88
+ sbatch infra/slurm/vlm_eval/analyze.sub # β†’ $B/eval_analysis/report.md
89
+ ```
90
+
91
+ Build/analyze run on CPU (`defq`); `run_vlm` on GPU (`vram48`) β€” override with `sbatch -p <part>`.
92
+ Chain with `--dependency=afterok:<jobid>` for one-shot submission (see the README).
93
+
94
+ ### The two steps it runs (do them by hand to learn the flow)
95
+
96
+ ```bash
97
+ conda activate itrialspace
98
+ set -a; . ./.env; set +a # ITRIALSPACE_OUTPUT_DIR = outputs_iTrialSpace
99
+
100
+ # STEP 1 β€” EXTRACT VLM SLICES from the demo synthetic CTs
101
+ # reads manifests + locates each case's synthetic_ct under --ct-base, extracts a
102
+ # lesion-centred axial slice (+ bbox/contour/bbox_contour overlays via --overlays)
103
+ python -m itrialspace.evaluation.vlm_eval.build_dataset \
104
+ -m "$ITRIALSPACE_OUTPUT_DIR"/manifests/mode1_*/*.csv \
105
+ "$ITRIALSPACE_OUTPUT_DIR"/manifests/mode2_*/*.csv \
106
+ --ct-base "$ITRIALSPACE_OUTPUT_DIR/generated_cts" \
107
+ --mask-base "$ITRIALSPACE_OUTPUT_DIR/inserted_masks" \
108
+ --output-dir "$ITRIALSPACE_OUTPUT_DIR/vlm_eval_demo/lung_axial" \
109
+ --profile lung_axial --overlays --workers 4
110
+ # β†’ writes eval_dataset.csv + slices/ (+ overlay variants)
111
+
112
+ # STEP 2 β€” RUN A VLM on the extracted slices (BiomedCLIP = lightest)
113
+ python -m itrialspace.evaluation.vlm_eval.run_biomedclip \
114
+ --dataset-csv "$ITRIALSPACE_OUTPUT_DIR/vlm_eval_demo/lung_axial/eval_dataset.csv" \
115
+ --output-dir "$ITRIALSPACE_OUTPUT_DIR/vlm_eval_demo/lung_axial/biomedclip" \
116
+ --tasks presence lobe size
117
+ # β†’ presence/lobe/size_results.csv per condition
118
+
119
+ # (other models: runners.run_llava_med / runners.run_medgemma; all 4 conditions at once:
120
+ # python -m itrialspace.evaluation.vlm_eval.runners.run_conditions --model biomedclip ...)
121
+ ```
122
+
123
+ ### Scale it to the larger / full dataset
124
+
125
+ The **same three jobs** scale to the full study β€” only the env vars change. On the released data
126
+ the eval sets and frozen splits already ship under `$ITRIALSPACE_DATA_DIR/vlm_dataset/`, so you
127
+ usually **skip the build** and score a fixed split:
128
+
129
+ ```bash
130
+ B=$ITRIALSPACE_DATA_DIR/vlm_dataset/synthetic
131
+ S=$ITRIALSPACE_DATA_DIR/vlm_dataset/splits/release_v1_full.synthetic.txt
132
+ MODEL=biomedclip CASE_IDS=$S EVAL_DIR=$B/lung_axial sbatch infra/slurm/vlm_eval/run_vlm.sub
133
+ MODEL=llava_med CASE_IDS=$S EVAL_DIR=$B/lung_axial sbatch infra/slurm/vlm_eval/run_vlm.sub
134
+ MODEL=medgemma CASE_IDS=$S EVAL_DIR=$B/lung_axial_medgemma sbatch infra/slurm/vlm_eval/run_vlm.sub
135
+ RESULTS=$ITRIALSPACE_DATA_DIR/vlm_dataset SPLIT=release_v1_full sbatch infra/slurm/vlm_eval/analyze.sub
136
+ ```
137
+
138
+ To **regenerate** the full eval sets from scratch, point `build_dataset.sub` at all 13 modes /
139
+ all 7 datasets and both profiles (`VLM_MODES`, `VLM_SET=real VLM_MAX="" VLM_DATASETS=…`,
140
+ `PROFILE=lung_axial_medgemma`, `EVAL_DIR=$ITRIALSPACE_DATA_DIR/vlm_dataset/<set>/<profile>`). The
141
+ demo→full mapping is one knob per axis — see the
142
+ [SLURM README](../infra/slurm/vlm_eval/README.md#scaling-to-the-full--curated-dataset).
143
+
144
+ ---
145
+
146
+ ## 3. Dataset layout (public release)
147
+
148
+ The released VLM dataset lives under `$ITRIALSPACE_DATA_DIR/vlm_dataset/`, split into
149
+ **synthetic** (modes 1–13, standard + digital-twin merged) and **real** (7 datasets):
150
+
151
+ ```
152
+ vlm_dataset/
153
+ β”œβ”€β”€ synthetic/ # 42,858 cases
154
+ β”‚ β”œβ”€β”€ lung_axial/ # BiomedCLIP + LLaVA-Med
155
+ β”‚ β”‚ β”œβ”€β”€ eval_dataset.csv # one row per case: paths + ground-truth columns
156
+ β”‚ β”‚ β”œβ”€β”€ slices/<mode>/… # lesion-centred slices: center + zΒ±1, Γ— plain/bbox/contour/bbox_contour
157
+ β”‚ β”‚ β”œβ”€β”€ biomedclip/ llava_med/ # per-condition {presence,lobe,size}_results.csv + comparison/
158
+ β”‚ β”œβ”€β”€ lung_axial_medgemma/ # MedGemma (3-channel windowing) β€” same structure + medgemma/
159
+ β”‚ └── cross_model_comparison/ # cross-model accuracy/deltas/summary
160
+ └── real/ # 13,087 cases (7 datasets, no NLST3D) β€” same structure
161
+ ```
162
+
163
+ (The demo in Β§2 writes to `$ITRIALSPACE_OUTPUT_DIR/vlm_eval_demo[_real]/` instead, to keep it
164
+ separate from the released set.)
165
+
166
+ Profiles (`--profile`): `lung_axial` (default, BiomedCLIP/LLaVA), **`lung_axial_medgemma`**
167
+ (MedGemma's 3-channel windowing), plus `mediastinal_axial`, `bone_axial`, `lung_coronal`,
168
+ `lung_sagittal`, `lung_axial_npy`.
169
+
170
+ ---
171
+
172
+ ## 4. Reproduce the full (paper) run
173
+
174
+ The demo is intentionally tiny. The published study evaluates **all 3 models** under **all 4
175
+ conditions** on **all 13 synthetic trial modes** and the **real-CT** datasets. To reproduce:
176
+
177
+ 1. **Generate the full synthetic data first** (production case counts, not the 5-case demo) β€”
178
+ see [running_the_pipeline.md](running_the_pipeline.md) Β§5; this fills
179
+ `$ITRIALSPACE_OUTPUT_DIR/{manifests,generated_cts,inserted_masks}` for all modes.
180
+ 2. **Build the full eval datasets** β€” `build_dataset.sub` for each set Γ— profile (all 13 modes /
181
+ all 7 datasets), into the public layout `vlm_dataset/{synthetic,real}/<profile>/`. See the
182
+ [SLURM README](../infra/slurm/vlm_eval/README.md#scaling-to-the-full--curated-dataset).
183
+ 3. **Run every model Γ— condition** β€” `run_vlm.sub` per model (BiomedCLIP + LLaVA-Med on
184
+ `lung_axial`; MedGemma on `lung_axial_medgemma`), optionally on a frozen split via `CASE_IDS`.
185
+ 4. **Analyse** β€” one command produces every table, figure, and statistic:
186
+
187
+ ```bash
188
+ python -m itrialspace.evaluation.vlm_eval.eval_analysis \
189
+ --results $ITRIALSPACE_DATA_DIR/vlm_dataset --split release_v1_full --out analysis/
190
+ ```
191
+
192
+ The **`eval_analysis`** suite auto-discovers whatever models/conditions/tasks are present
193
+ (so it works on the full dataset *and* a tiny demo run) and writes `analysis/`:
194
+ - `tables/` β€” accuracy, Ξ”-vs-plain, per-mode / per-dataset / per-size / per-lobe breakdowns,
195
+ confusion matrices, per-class accuracy, bootstrap CIs, McNemar significance (CSV).
196
+ - `figures/` β€” accuracy-by-condition, Ξ” bars, confusion heatmaps, breakdown bars (PNG + PDF).
197
+ - `report.md` β€” the assembled report.
198
+
199
+ (`comparison.py` / `cross_model_comparison.py` remain for quick per-run condition deltas.)
200
+
201
+ > **SLURM jobs:** the whole flow is three env-driven jobs β€”
202
+ > [`build_dataset.sub` β†’ `run_vlm.sub` β†’ `analyze.sub`](../infra/slurm/vlm_eval/README.md) β€” the
203
+ > same ones used for the demo (Β§2), pointed at the full data. (The old per-shard
204
+ > `vlm_*_ext`/`postfix`/`overlay_build` scripts for the pre-release split layout have been
205
+ > removed in favour of these.)
206
+
207
+ > **The released VLM dataset** ships as `vlm_dataset/{synthetic,real}/` (the layout in Β§3) β€”
208
+ > see the [dataset card](dataset_card.md). Drop it under `$ITRIALSPACE_DATA_DIR/vlm_dataset/`
209
+ > and the runners pick it up, or regenerate it from the raw CTs with the steps above.
210
+
211
+ ---
212
+
213
+ ## 4a. Reporting convention β€” keeping released numbers aligned
214
+
215
+ When you aggregate results for a paper/report, **score the same set of cases in every task** so all
216
+ reported accuracies share one N. The rule:
217
+
218
+ > **Report accuracy on the cases that have a completed prediction in *every* (task Γ— condition Γ—
219
+ > model).** Take the intersection of `case_id` across all the result CSVs you are comparing; drop
220
+ > any case that is missing from one of them; report that single N everywhere.
221
+
222
+ For the **released dataset this is the full case count** (42,858 synthetic / 13,087 real) β€” every
223
+ `eval_dataset.csv` row is complete for presence, lobe, and size. You only get a *smaller* N if some
224
+ runs are unfinished (a model/condition still missing predictions), in which case the intersection
225
+ keeps the comparison honest instead of silently averaging different case sets per task.
226
+
227
+ > **Why the paper says 42,382, not 42,858.** Same rule, earlier snapshot: at paper time 334 mode-13
228
+ > cases (plus a few re-extracted later) had slices on disk but **inference not yet run**, so they
229
+ > were excluded to keep N equal across tasks. Reconciliation: **42,382** = inference-complete (paper
230
+ > tables) Β· 42,716 = slices extracted on disk then Β· **42,858** = the finished release (inference
231
+ > complete for all cases). See the [dataset card Β§ Reporting convention](dataset_card.md#reporting-convention-evaluation-n--read-before-comparing-to-the-paper).
232
+
233
+ Helper (use it in any aggregation script so the convention is enforced, not assumed):
234
+
235
+ ```python
236
+ import pandas as pd
237
+ from itrialspace.evaluation.vlm_eval.metrics import common_case_ids
238
+
239
+ # one result frame per (task Γ— condition Γ— model) you want to compare
240
+ frames = [pd.read_csv(p) for p in result_csvs]
241
+ keep = common_case_ids(frames) # cases scored in *all* of them
242
+ frames = [df[df["case_id"].isin(keep)] for df in frames]
243
+ print("reported N =", len(keep)) # the single N for every table
244
+ ```
245
+
246
+ `comparison.py` and `cross_model_comparison.py` print this `reported N` so it lands in the logs and
247
+ summary JSON alongside the accuracies.
248
+
249
+ ### Frozen splits β€” the exact cases reported on
250
+
251
+ The release ships the case sets as immutable, checksummed files under
252
+ `vlm_dataset/splits/` (one **canonical uid** per line β€” `mode/case`, condition-independent β€”
253
+ plus `splits.json` with counts + SHA-256 + provenance + code commit):
254
+
255
+ | Split | Synthetic | Real | Scope |
256
+ |-------|----------:|-----:|-------|
257
+ | `release_v1` | 42,858 | 13,087 | all 3 models Γ— `plain` Γ— 3 tasks (headline numbers) |
258
+ | `release_v1_full` | 41,502 | 13,047 | all 3 models Γ— all 4 conditions Γ— 3 tasks (condition tables) |
259
+
260
+ **Run on exactly a split** β€” every runner takes `--case-ids`:
261
+
262
+ ```bash
263
+ python -m itrialspace.evaluation.vlm_eval.runners.run_conditions \
264
+ --model biomedclip --run-all-conditions \
265
+ --dataset-csv $ITRIALSPACE_DATA_DIR/vlm_dataset/synthetic/lung_axial/eval_dataset.csv \
266
+ --output-dir out/biomedclip \
267
+ --case-ids $ITRIALSPACE_DATA_DIR/vlm_dataset/splits/release_v1.synthetic.txt
268
+ ```
269
+
270
+ **(Re)generate a split** (reproducible β€” the `sha256` must match):
271
+
272
+ ```bash
273
+ python -m itrialspace.evaluation.vlm_eval.make_split \
274
+ --name release_v1 --set synthetic \
275
+ --out-dir $ITRIALSPACE_DATA_DIR/vlm_dataset/splits \
276
+ --results-glob "$ITRIALSPACE_DATA_DIR/vlm_dataset/synthetic/lung_axial/*/plain/*_results.csv" \
277
+ "$ITRIALSPACE_DATA_DIR/vlm_dataset/synthetic/lung_axial_medgemma/medgemma/plain/*_results.csv"
278
+ ```
279
+
280
+ Full details and verification: `vlm_dataset/splits/README.md`.
281
+
282
+ ---
283
+
284
+ ## 5. Troubleshooting
285
+
286
+ | Symptom | Fix |
287
+ |---------|-----|
288
+ | `ModuleNotFoundError: open_clip/transformers` | `pip install -e ".[vlm]"`. |
289
+ | Model download fails / offline | warm `~/.cache/huggingface` or pass `--cache-dir`; or set each model's `model_id` to a local checkpoint. |
290
+ | MedGemma cuDNN / `libcudnn.so.9` errors | run via `infra/slurm/*` (env.sh puts cuDNN on `LD_LIBRARY_PATH`); use the `lung_axial_medgemma` profile. |
291
+ | CUDA OOM on generative models | use a 48 GB GPU (`vram48`); reduce batch/cases; BiomedCLIP needs far less. |
292
+ | Empty / skipped cases at build | the case's CT/mask isn't under `--ct-base`/`--mask-base` (synthetic) or `$ITRIALSPACE_DATA_DIR` (real). |
293
+ | Slow CPU run | BiomedCLIP works on CPU but is slow; generative models effectively require GPU. |
294
+
295
+ See also: [running_the_pipeline.md](running_the_pipeline.md),
296
+ [evaluation_external_dependencies.md](evaluation_external_dependencies.md).
itrialspace/blinded_doc/vlm_eval_implementation.md ADDED
@@ -0,0 +1,265 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!-- BLINDED COPY for double-blind peer review β€” author, institution, and repository-identifying information removed. Do not use for attribution. -->
2
+
3
+ # VLM evaluation β€” implementation reference
4
+
5
+ This is the **engineering/architecture reference** for the vision-language-model (VLM)
6
+ evaluation subsystem (`itrialspace.evaluation.vlm_eval`). It documents the design, the
7
+ data model, every module's responsibility, and the extension points.
8
+
9
+ For task-oriented instructions (how to run a demo, reproduce the study, troubleshoot)
10
+ see the user guide [vlm_eval.md](vlm_eval.md); for the released numbers see
11
+ [vlm_results.md](vlm_results.md); for the data contract see
12
+ [dataset_card.md](dataset_card.md).
13
+
14
+ ---
15
+
16
+ ## 1. Scope and design goals
17
+
18
+ The subsystem evaluates three zero-shot VLMs β€” **BiomedCLIP**, **LLaVA-Med**, and
19
+ **MedGemma** β€” on three clinical tasks (**presence**, **lobe**, **size**) over four image
20
+ **conditions** (`plain`, `bbox`, `contour`, `bbox_contour`), on both **synthetic** and
21
+ **real** lung-nodule CT. It is built around five principles:
22
+
23
+ 1. **Single tidy data contract.** Every model run emits the same row schema; every analysis
24
+ is a group-by over one long table. No bespoke per-model parsing downstream.
25
+ 2. **Stable identity.** A case is identified by a **canonical uid** derived from its slice
26
+ path β€” never the non-unique `case_id` index in the CSVs (Β§4).
27
+ 3. **Reproducible, fixed reporting sets.** Accuracy is reported on a frozen, checksummed
28
+ **split** so reruns and re-reports score the same cases (Β§7).
29
+ 4. **Auto-discovery.** Tools infer which models/conditions/tasks are present, so the *same*
30
+ code serves the full released dataset and a tiny demo run.
31
+ 5. **Portable & secret-free.** All paths come from `ITRIALSPACE_DATA_DIR`/`settings`; the
32
+ HuggingFace token comes from `.env` (`HF_TOKEN`), never from code (Β§9).
33
+
34
+ ---
35
+
36
+ ## 2. Architecture at a glance
37
+
38
+ ```
39
+ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ Stage 1: dataset construction ────────────────────────┐
40
+ manifests / profiles ──▢│ build_dataset (synthetic) Β· build_real_dataset (real) β”‚
41
+ generated_cts / masks β”‚ └─ slice_extractor (centre-slice + zΒ±1) Β· overlay (bbox/contour) │──▢ eval_dataset.csv
42
+ raw_ct / nodule_seg β”‚ └─ preprocess_profiles (lung_axial / lung_axial_medgemma) β”‚ + slices/*.png
43
+ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
44
+ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ Stage 2: inference ──────────────────────────────────┐
45
+ eval_dataset.csv ──────▢│ runners/run_conditions ─▢ run_biomedclip Β· runners/run_llava_med Β· run_medgemma│──▢ <model>/<cond>/<task>_results.csv
46
+ β”‚ models/{biomedclip,llava_med,medgemma} Β· prompt_templates Β· parsers β”‚
47
+ β”‚ inference_cache (resume) β”‚
48
+ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
49
+ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ Stage 3: scoring & reporting ────────────────────────┐
50
+ *_results.csv ─────────▢│ splits / make_split (frozen sets) Β· metrics Β· comparison / cross_model │──▢ accuracy / deltas / splits.json
51
+ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
52
+ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ Stage 4: analysis suite ─────────────────────────────┐
53
+ *_results.csv + split ─▢│ eval_analysis: load ─▢ tables Β· stats Β· plots ─▢ report │──▢ tables/ + figures/ + report.md
54
+ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
55
+ ```
56
+
57
+ | Layer | Modules | Responsibility |
58
+ |-------|---------|----------------|
59
+ | 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 |
60
+ | Model adapters | `models/biomedclip_model`*, `models/llava_med`, `models/medgemma` | Uniform `predict`/`predict_batch` over each backbone |
61
+ | 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 |
62
+ | Prompting & parsing | `prompt_templates`, `parsers` | Task prompts + robust free-text β†’ label parsing |
63
+ | Scoring | `metrics`, `comparison`, `cross_model_comparison`, `inference_cache` | Accuracy/F1, condition deltas, resume |
64
+ | Reporting sets | `splits`, `make_split` | Canonical uid, frozen checksummed splits, `--case-ids` |
65
+ | Analysis suite | `eval_analysis/{load,tables,stats,plots,report}` | Full tables, figures, statistics, markdown report |
66
+
67
+ \* `biomedclip_model.py` lives at the package root; the generative adapters live under
68
+ `models/`.
69
+
70
+ ---
71
+
72
+ ## 3. The two stages of data, and what "results" mean
73
+
74
+ - A **case** is one nodule on one CT. Synthetic cases come from a trial-mode manifest (an
75
+ inserted donor nodule on a host CT); real cases come from a dataset's nodule profile.
76
+ - Each case yields, per **preprocessing profile**, **3 z-slices** (`z`, `z-1`, `z+1`) Γ—
77
+ **4 conditions** = up to 12 PNGs. **Evaluation uses the centre (`z`) slice**; `zΒ±1` are
78
+ context that MedGemma may stack (BiomedCLIP/LLaVA-Med use the centre slice only).
79
+ - A **run** scores one `(model Γ— condition Γ— task)` and writes one
80
+ `<model>/<condition>/<task>_results.csv`, one row per case, with `prediction`,
81
+ `ground_truth`, `correct`, and the slice `image_path`.
82
+
83
+ ---
84
+
85
+ ## 4. Data model
86
+
87
+ ### 4.1 `eval_dataset.csv` (Stage 1 output)
88
+ One row per case (per profile). Key columns:
89
+
90
+ | Column | Meaning |
91
+ |--------|---------|
92
+ | `png_path`, `png_bbox_path`, `png_contour_path`, `png_bbox_contour_path` | centre-slice PNG per condition |
93
+ | `slice_z`, `slice_method`, `preprocess_profile` | extraction provenance |
94
+ | `ground_truth_presence` | `present` / `absent` |
95
+ | `ground_truth_lobe` | 5 classes (`right_lung_upper_lobe` … `left_lung_lower_lobe`) |
96
+ | `ground_truth_size_bucket` | `<5mm`, `5-10mm`, `10-20mm`, `>20mm` |
97
+ | `mode` / `dataset`, `effective_diam_mm`/`nodule_mean_diam_mm`, `insertion_lobe`, `population_type` | metadata for breakdowns |
98
+
99
+ **Ground-truth derivation.** Synthetic labels are **known by construction** (insertion lobe;
100
+ `effective_diam_mm` binned to a size bucket; `present` unless a deliberately nodule-free
101
+ case). Real labels come from the source dataset's annotations (lobe normalised to the 5
102
+ canonical classes via `prompt_templates.normalise_lobe`; diameter binned via
103
+ `diameter_to_size_bucket`; all `present`).
104
+
105
+ ### 4.2 Canonical uid β€” the only stable key
106
+ The `case_id` column in both `eval_dataset.csv` and the result CSVs is a **non-unique
107
+ positional index** (it restarts per shard). The stable identity is the slice path with the
108
+ condition sub-dir and extension stripped, computed by
109
+ [`splits.canonical_uid`](../src/itrialspace/evaluation/vlm_eval/splits.py):
110
+
111
+ ```
112
+ …/slices/mode1_controlled_prevalence/NLST_cohort__C0000.png ┐
113
+ …/slices/mode1_controlled_prevalence/bbox/NLST_cohort__C0000.png β”˜ β†’ mode1_controlled_prevalence/NLST_cohort__C0000
114
+ ```
115
+
116
+ so one case maps to one uid across all four conditions, and results join cleanly to
117
+ `eval_dataset.csv`. **All joins, intersections, and de-duplication use the uid, never
118
+ `case_id`.**
119
+
120
+ ---
121
+
122
+ ## 5. Stage 1 β€” dataset construction
123
+
124
+ - **`slice_extractor`** locates the nodule centroid (from the inserted/nodule mask), extracts
125
+ the axial centre slice and `zΒ±1`, converts to radiological orientation, applies the HU
126
+ window, and drops artefact slices. `preprocess_profiles` defines the windows:
127
+ `lung_axial` (BiomedCLIP/LLaVA-Med) and `lung_axial_medgemma` (3-channel z-stack).
128
+ - **`overlay`** renders the spatial-guidance variants from the mask: `bbox` (bounding box),
129
+ `contour` (segmentation outline), `bbox_contour` (both). `VALID_CONDITIONS` is the single
130
+ source of truth for the condition set.
131
+ - **`build_dataset`** (synthetic) resolves each manifest case's `synthetic_ct` + mask,
132
+ extracts slices, draws overlays (`--overlays`), and writes `eval_dataset.csv`
133
+ (multiprocessing via `--workers`). **`build_real_dataset`** does the same from real
134
+ profiles + `raw_ct/` + `nodule_seg/`. **`build_negative_dataset`** samples nodule-free lung
135
+ slices for presence negatives.
136
+
137
+ Output: `vlm_dataset/{synthetic,real}/<profile>/{eval_dataset.csv, slices/…}`.
138
+
139
+ ---
140
+
141
+ ## 6. Stage 2 β€” inference
142
+
143
+ - **Model adapters** (`models/…`) present a uniform interface (lazy weight loading; batched
144
+ `predict`). BiomedCLIP is contrastive (open_clip; scores label prompts); LLaVA-Med and
145
+ MedGemma are generative (`transformers`), prompted via `prompt_templates.get_generative_prompt`.
146
+ - **`parsers`** turns free-text generative answers into a label + a `ParseResult` status
147
+ (handles synonyms, negation, partial matches) so scoring is robust.
148
+ - **`runners/run_conditions`** is the orchestrator: it remaps `png_path` to the chosen
149
+ condition column, optionally restricts to a split (`--case-ids`, Β§7), and dispatches to the
150
+ per-model runner for each condition. `run_all` chains the full matrix.
151
+ - **`inference_cache`** lets a run resume by reusing prior rows for unchanged cases
152
+ (`--skip-existing`).
153
+
154
+ Output: `<model>/<condition>/<task>_results.csv` (+ per-mode and `aggregate/` copies).
155
+
156
+ ---
157
+
158
+ ## 7. Stage 3 β€” reporting sets and the reporting-N convention
159
+
160
+ > **Convention.** Report accuracy on the cases scored in *every* `(model Γ— condition Γ—
161
+ > task)` you compare β€” the canonical-uid **intersection** β€” so every number shares one N.
162
+
163
+ - **`metrics.common_case_ids`** computes that intersection (keyed on the uid).
164
+ - **`splits` / `make_split`** freeze it as a checksummed artifact under `vlm_dataset/splits/`:
165
+ a sorted uid list per set plus `splits.json` (count, SHA-256, source globs, git commit).
166
+ Two ship with the release:
167
+
168
+ | Split | Synthetic | Real | Scope |
169
+ |-------|----------:|-----:|-------|
170
+ | `release_v1` | 42,858 | 13,087 | all models Γ— `plain` Γ— 3 tasks |
171
+ | `release_v1_full` | 41,502 | 13,047 | all models Γ— **4 conditions** Γ— 3 tasks |
172
+
173
+ - Every runner accepts **`--case-ids <split.txt>`** to score exactly that set.
174
+ - `comparison` / `cross_model_comparison` produce per-condition deltas for a single run.
175
+
176
+ This is also the reconciliation point for the paper: the submission's synthetic N = 42,382
177
+ is the *same rule* at a pre-inference snapshot; the release completes inference, so
178
+ `release_v1` = 42,858. See [dataset_card.md](dataset_card.md#reporting-convention-evaluation-n--read-before-comparing-to-the-paper).
179
+
180
+ ---
181
+
182
+ ## 8. Stage 4 β€” the `eval_analysis` suite
183
+
184
+ A reusable engine that turns result CSVs into a full report:
185
+
186
+ - **`load`** β€” auto-discovers condition-level `*_results.csv` under any root, joins each row
187
+ to its `eval_dataset.csv` metadata, applies a split, and returns **one tidy long
188
+ DataFrame** (`set, model, condition, task, uid, prediction, ground_truth, correct,
189
+ mode, source_dataset, lobe, size_bucket, diam_mm, population`).
190
+ - **`tables`** β€” accuracy, Ξ”-vs-baseline, breakdowns (mode / dataset / size / lobe),
191
+ confusion, per-class.
192
+ - **`stats`** β€” percentile **bootstrap CIs** and paired **McNemar** significance of each
193
+ condition vs the baseline.
194
+ - **`plots`** β€” publication-style figures (top/right spines removed, shared y-axis with
195
+ labels on the first panel, blue-shade palette, 300-dpi PNG + vector PDF).
196
+ - **`report`** β€” orchestrates everything into `out/{tables/*.csv, figures/*, report.md}`.
197
+
198
+ ```bash
199
+ python -m itrialspace.evaluation.vlm_eval.eval_analysis \
200
+ --results $ITRIALSPACE_DATA_DIR/vlm_dataset --split release_v1_full --out analysis/
201
+ # demo: --results out/demo (omit --split; auto-discovers what's present)
202
+ ```
203
+
204
+ ---
205
+
206
+ ## 9. Configuration, portability, and secrets
207
+
208
+ - **Paths** are never hardcoded. `itrialspace.config.settings` resolves everything from
209
+ `ITRIALSPACE_DATA_DIR` / `ITRIALSPACE_OUTPUT_DIR` (with `.env` loaded once at import; real
210
+ environment variables win). `tools/check_portability.py` gates against stray absolute paths.
211
+ - **HuggingFace token.** Gated models (MedGemma; some LLaVA-Med checkpoints) read the token
212
+ from the environment via `settings.hf_token()` (`.env` β†’ `HF_TOKEN`, or the legacy
213
+ `HUGGING_FACE_HUB_TOKEN`) and pass it to `from_pretrained`. **No token is ever committed**;
214
+ `.env` is gitignored. To share, clear the value β€” each user supplies their own. BiomedCLIP
215
+ is public and needs none.
216
+ - **Weights** are not bundled; models load from the HuggingFace cache (or a local
217
+ `--model-id`).
218
+
219
+ ---
220
+
221
+ ## 10. Extension points
222
+
223
+ | To add… | Do this |
224
+ |---------|---------|
225
+ | **a model** | Add an adapter under `models/` with `predict`/`predict_batch`; register a dispatch branch in `runners/run_conditions._run_model`. |
226
+ | **a task** | Add a `TaskDefinition` to `prompt_templates.ALL_TASKS` (+ generative prompt) and a parser in `parsers`. |
227
+ | **a condition** | Extend `overlay.VALID_CONDITIONS` + the draw function and the `_CONDITION_COLUMNS` map in `run_conditions`. |
228
+ | **a preprocessing profile** | Add a `PreprocessProfile` in `preprocess_profiles`. |
229
+ | **an analysis breakdown** | Add the column to `eval_analysis.load` metadata and a `breakdown_table(by=…)` call in `report`. |
230
+
231
+ ---
232
+
233
+ ## 11. Quality gates
234
+
235
+ - **Lint/format:** `ruff` + `black` (CI; repo standard).
236
+ - **Portability:** `tools/check_portability.py`.
237
+ - **Reproducibility:** split SHA-256 in `splits.json` β€” regenerate with `make_split` and the
238
+ hash must match.
239
+ - **Tests:** unit tests run under `pytest -m "not full_volume"`; full-volume/model tests are
240
+ env-gated (need data/GPU).
241
+
242
+ ---
243
+
244
+ ## 12. Module reference
245
+
246
+ | Module | One-line role |
247
+ |--------|---------------|
248
+ | `build_dataset.py` | Build synthetic eval dataset from trial manifests |
249
+ | `build_real_dataset.py` | Build real-CT eval dataset from nodule profiles |
250
+ | `build_negative_dataset.py` | Sample nodule-free slices (presence negatives) |
251
+ | `slice_extractor.py` | Centroid-centred axial slice extraction + HU windowing |
252
+ | `overlay.py` | bbox / contour / bbox_contour spatial-guidance overlays |
253
+ | `preprocess_profiles.py` | Named preprocessing profiles (windows, z-stack) |
254
+ | `prompt_templates.py` | Task definitions, prompts, lobe/size normalisation |
255
+ | `parsers.py` | Free-text answer β†’ label (robust) |
256
+ | `biomedclip_model.py`, `models/llava_med.py`, `models/medgemma.py` | Model adapters |
257
+ | `run_biomedclip.py`, `runners/run_llava_med.py`, `runners/run_medgemma.py` | Per-model runners |
258
+ | `runners/run_conditions.py`, `run_all.py` | Condition/matrix orchestration |
259
+ | `inference_cache.py` | Resume support |
260
+ | `metrics.py` | Accuracy/F1/confusion + `common_case_ids` |
261
+ | `comparison.py`, `cross_model_comparison.py` | Per-condition / cross-model deltas |
262
+ | `splits.py`, `make_split.py` | Canonical uid + frozen checksummed splits |
263
+ | `report.py` | Quick single-table headline report |
264
+ | `eval_analysis/` | Full analysis suite (tables, stats, figures, report) |
265
+ ```
itrialspace/blinded_doc/walkthrough_mode1.md ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!-- BLINDED COPY for double-blind peer review β€” author, institution, and repository-identifying information removed. Do not use for attribution. -->
2
+
3
+ # Walkthrough: 200 cases through Mode 1 (end-to-end)
4
+
5
+ This tutorial takes **Mode 1 (`controlled_prevalence`)** from a cohort specification all
6
+ the way to synthetic CT volumes, for **200 cases**:
7
+
8
+ ```
9
+ its-trials ──▢ manifest CSV ──▢ its-insert ──▢ inserted masks + audit.json ──▢ synthesis ──▢ synthetic CTs
10
+ (1) plan (cohort) (2) insert (label-23 combined masks) (3) generate (+ QC)
11
+ ```
12
+
13
+ ## 0. One-time setup
14
+
15
+ ```bash
16
+ cd /path/to/itrialspace
17
+ conda activate itrialspace # or your env with the deps installed
18
+ pip install -e ".[imaging]" # core + NIfTI/scipy/SimpleITK
19
+
20
+ # Tell iTrialSpace where the data lives (the 7 datasets, host CTs, organ segs)
21
+ export ITRIALSPACE_DATA_DIR=/scratch/railabs/ft42/VLST_Project/Data/iTrialSpace
22
+ # Where outputs go (defaults to ITRIALSPACE_DATA_DIR if unset)
23
+ export ITRIALSPACE_OUTPUT_DIR=$ITRIALSPACE_DATA_DIR
24
+
25
+ its config # sanity-check the resolved paths
26
+ ```
27
+
28
+ > Tip: put these in a `.env` (copy `.env.example`); the SLURM scripts and config
29
+ > loaders pick it up automatically.
30
+
31
+ ---
32
+
33
+ ## Step 1 β€” Plan the cohort (itrialspace β†’ manifest)
34
+
35
+ `its-trials` runs the trial-mode factory, builds the cohort with `CohortBuilder`, and
36
+ writes a manifest (CSV + JSON).
37
+
38
+ ```bash
39
+ its-trials \
40
+ --mode controlled_prevalence \
41
+ --n-cases 200 \
42
+ --prevalence 0.05 \
43
+ --template NLST \
44
+ --seed 42 \
45
+ --output-dir $ITRIALSPACE_OUTPUT_DIR/manifests/mode1_controlled_prevalence
46
+ ```
47
+
48
+ **Produces** (filename derives from the template, e.g. `NLST_cohort.csv`):
49
+
50
+ ```
51
+ $ITRIALSPACE_OUTPUT_DIR/manifests/mode1_controlled_prevalence/
52
+ β”œβ”€β”€ NLST_cohort.csv # 200 rows β€” one per case (host CT + donor nodule + placement)
53
+ β”œβ”€β”€ NLST_cohort.json # same content, structured
54
+ └── _run_config.json # exact parameters used (reproducibility)
55
+ ```
56
+
57
+ Each manifest row carries the host CT path, host organ segmentation, the donor nodule, and
58
+ the target placement (lobe / percentile / scale). Verify:
59
+
60
+ ```bash
61
+ 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())"
62
+ ```
63
+
64
+ Useful options: `--no-verify-paths` (skip on-disk path checks for a quick dry plan),
65
+ `--n-cases`, `--prevalence`. See `its-trials --help`.
66
+
67
+ ---
68
+
69
+ ## Step 2 β€” Insert nodule masks (manifest β†’ inserted masks)
70
+
71
+ `its-insert run` reads the manifest, resolves host organ-segmentation volumes, and pastes
72
+ each donor nodule mask at **VISTA3D label 23** using the 5-stage placement pipeline (lobe
73
+ targeting → percentile→voxel → snap-to-mask → pleural safety → collision avoidance).
74
+ **Mask-only β€” no CT intensities are touched here.**
75
+
76
+ ```bash
77
+ its-insert run \
78
+ --manifest $ITRIALSPACE_OUTPUT_DIR/manifests/mode1_controlled_prevalence/NLST_cohort.csv \
79
+ --output-dir $ITRIALSPACE_OUTPUT_DIR/inserted_masks/mode1_controlled_prevalence \
80
+ --trial-name mode1_controlled_prevalence \
81
+ --seed 42 \
82
+ --n-jobs 8
83
+ ```
84
+
85
+ **Produces:**
86
+
87
+ ```
88
+ $ITRIALSPACE_OUTPUT_DIR/inserted_masks/mode1_controlled_prevalence/
89
+ β”œβ”€β”€ iTS--mode1...--C0000--host-...--src-...--nod-..._mask.nii.gz # combined label map per case
90
+ β”œβ”€β”€ ... (200 masks)
91
+ └── audit.json # per-case provenance (placement, snap, pleural dist, overlap) β€” KEY for step 3
92
+ ```
93
+
94
+ - **Dry run first** (placement decisions only, nothing written):
95
+ `its-insert run --manifest ... --output-dir ... --dry-run`
96
+ - Verify a finished run: `its-insert verify --output-dir $ITRIALSPACE_OUTPUT_DIR/inserted_masks/mode1_controlled_prevalence`
97
+
98
+ ---
99
+
100
+ ## Step 3 β€” Generate CTs (inserted masks β†’ synthetic CT)
101
+
102
+ This runs **NodMAISI** (ControlNet-conditioned rectified-flow diffusion). It **needs a
103
+ GPU**, the `synthesis` extra, and the model weights.
104
+
105
+ ```bash
106
+ pip install -e ".[synthesis]"
107
+ # torch matching your CUDA (example: cu124) β€” see docs/installation.md
108
+ pip install torch --index-url https://download.pytorch.org/whl/cu124
109
+
110
+ # Point at the NodMAISI weights (autoencoder.pt, diffusion_unet.pt, controlnet *.pt)
111
+ export NODMAISI_MODELS_DIR=/path/to/nodmaisi/models
112
+ ```
113
+
114
+ Run the integration bridge. The `audit.json` from Step 2 is the preferred input (it links
115
+ each mask back to its host CT for the QC overlay):
116
+
117
+ ```bash
118
+ python -m itrialspace.synthesis.tools.run_itrialspace_to_ct \
119
+ --audit $ITRIALSPACE_OUTPUT_DIR/inserted_masks/mode1_controlled_prevalence/audit.json \
120
+ --config configs/integration.example.yaml \
121
+ --outdir $ITRIALSPACE_OUTPUT_DIR/generated_cts/mode1_controlled_prevalence \
122
+ --jobs 1
123
+ ```
124
+
125
+ (If you don't have the audit, use `--mask-root $ITRIALSPACE_OUTPUT_DIR/inserted_masks/mode1_controlled_prevalence` instead.)
126
+
127
+ **Produces, per case:**
128
+
129
+ ```
130
+ $ITRIALSPACE_OUTPUT_DIR/generated_cts/mode1_controlled_prevalence/<case_id>/
131
+ β”œβ”€β”€ synthetic_ct.nii.gz # generated CT volume
132
+ β”œβ”€β”€ input_mask.nii.gz # mask fed to the model (snapped to a valid grid)
133
+ β”œβ”€β”€ host_ct.nii.gz # symlink to host CT (for comparison)
134
+ β”œβ”€β”€ qc/qc_slice_*.png # 3-panel QC (host | synthetic+overlay | synthetic)
135
+ └── nodmaisi_audit.json # params, geometry, sanity checks, timing
136
+ ```
137
+
138
+ Validate without a GPU first: add `--dry-run` (checks inputs/geometry, skips inference).
139
+
140
+ ---
141
+
142
+ ## Running it on HPC (recommended for 200 cases)
143
+
144
+ Each stage has SLURM scripts under `infra/slurm/`, cluster-portable via `infra/slurm/env.sh`
145
+ (set `ITRIALSPACE_DATA_DIR`, `ITRIALSPACE_CONDA_ENV`, partitions in your `.env`):
146
+
147
+ ```bash
148
+ # 1. plan
149
+ sbatch infra/slurm/trials/mode1_controlled_prevalence.sub
150
+ # 2. insert (CPU array job)
151
+ sbatch infra/slurm/mask_inserter/mode1_insert_masks.sub
152
+ # 3. synthesize (GPU array job; chunks automatically if >1000 cases)
153
+ infra/slurm/synthesis/submit_array_jobs.sh 1
154
+ ```
155
+
156
+ > Edit the `#SBATCH --partition/--account` lines for your cluster (see
157
+ > [infra/slurm/README.md](../infra/slurm/README.md)).
158
+
159
+ ---
160
+
161
+ ## What "200 cases" means at each stage
162
+
163
+ | Stage | Input | Output | Needs |
164
+ |-------|-------|--------|-------|
165
+ | 1. Plan | dataset index | 200-row manifest CSV/JSON | CPU, profile CSVs |
166
+ | 2. Insert | manifest + host organ segs | 200 label-23 masks + `audit.json` | CPU, host CTs/segs |
167
+ | 3. Generate | masks (+ audit) | 200 synthetic CTs + QC | **GPU + NodMAISI weights** |
168
+
169
+ After Step 3 you can feed the synthetic CTs into evaluation β€” VLM
170
+ (`itrialspace.evaluation.vlm_eval`).
itrialspace/configs/datasets.example.yaml ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # iTrialSpace Dataset Registry β€” maps dataset name β†’ nodule-profile CSV path.
2
+ #
3
+ # Copy to `configs/datasets.yaml` and adjust if your layout differs. Paths use the
4
+ # ${ITRIALSPACE_DATA_DIR} placeholder, which is expanded by itrialspace.config.settings
5
+ # (default: ~/.itrialspace/data). You usually only need to set ITRIALSPACE_DATA_DIR in .env.
6
+
7
+ datasets:
8
+
9
+ DLCS24:
10
+ csv_path: ${ITRIALSPACE_DATA_DIR}/profiles/DLCS24_nodule_profiles.csv
11
+ notes: "Binary label. Lung-RADS scores, smoking, age/sex. 2,487 nodules."
12
+
13
+ LUNA25:
14
+ csv_path: ${ITRIALSPACE_DATA_DIR}/profiles/LUNA25_nodule_profiles.csv
15
+ notes: "Binary label. Largest dataset (6,163 nodules). Multi-nodule screening."
16
+
17
+ LUNA16:
18
+ csv_path: ${ITRIALSPACE_DATA_DIR}/profiles/LUNA16_nodule_profiles.csv
19
+ notes: "No malignancy label. Use for reinsertion/anatomy analysis only."
20
+
21
+ LUNGx:
22
+ csv_path: ${ITRIALSPACE_DATA_DIR}/profiles/LUNGx_nodule_profiles.csv
23
+ notes: "Benchmark challenge. 49.4% malignant."
24
+
25
+ LNDbv4:
26
+ csv_path: ${ITRIALSPACE_DATA_DIR}/profiles/LNDbv4_nodule_profiles.csv
27
+ notes: "Malignancy is continuous float (radiologist avg 1-5). Threshold 3.0 used."
28
+
29
+ NSCLCR:
30
+ csv_path: ${ITRIALSPACE_DATA_DIR}/profiles/NSCLCR_nodule_profiles.csv
31
+ notes: "All malignant (100%). Large tumours (median 52mm). Has staging/survival."
32
+
33
+ IMDCT:
34
+ csv_path: ${ITRIALSPACE_DATA_DIR}/profiles/IMDCT_nodule_profiles.csv
35
+ notes: "Label is string benign/cancer. Has nodule type, PET, spiculation."
itrialspace/configs/features.yaml ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Feature-set definitions for NoduleMap embeddings.
2
+ # Each feature set defines the columns used, their types, and preprocessing.
3
+
4
+ feature_sets:
5
+
6
+ # ── reinsertion_core ──────────────────────────────────────────────────────
7
+ # Safe default: uses only reinsertion_* columns (100% complete, no NaNs).
8
+ reinsertion_core:
9
+ description: "Reinsertion-only features β€” no NaNs, 12 columns"
10
+ numeric:
11
+ - reinsertion_lobe_cc_pct
12
+ - reinsertion_lobe_ml_pct
13
+ - reinsertion_lobe_ap_pct
14
+ - reinsertion_lung_cc_pct
15
+ - reinsertion_lung_ml_pct
16
+ - reinsertion_lung_ap_pct
17
+ - reinsertion_pleural_dist_mm
18
+ - reinsertion_airway_dist_mm
19
+ - reinsertion_nodule_diam_mm
20
+ categorical:
21
+ - reinsertion_lobe
22
+ - reinsertion_lung_side
23
+ - reinsertion_lung_zone
24
+ scaler: standard # standard | robust
25
+ imputer: none # none | median | mean
26
+
27
+ # ── core_53 ───────────────────────────────────────────────────────────────
28
+ # Full 53-column profile: anatomy, distances, inter-nodule, reinsertion.
29
+ # May contain NaNs in non-reinsertion columns.
30
+ core_53:
31
+ description: "All 53 core pipeline features β€” requires imputation"
32
+ numeric:
33
+ - nodule_mean_diam_mm
34
+ - nodule_vol_mm3
35
+ - cranio_caudal_pct
36
+ - mediolateral_pct
37
+ - anteroposterior_pct
38
+ - lobe_cc_pct
39
+ - lobe_ml_pct
40
+ - lobe_ap_pct
41
+ - dist_to_trachea_mm
42
+ - dist_to_aorta_mm
43
+ - dist_to_heart_mm
44
+ - dist_to_esophagus_mm
45
+ - dist_to_pulmonary_vein_mm
46
+ - dist_to_superior_vena_cava_mm
47
+ - pleural_distance_mm
48
+ - airway_distance_mm
49
+ - n_nodules_in_patient
50
+ - nearest_nodule_dist_mm
51
+ - nearest_dx_mm
52
+ - nearest_dy_mm
53
+ - nearest_dz_mm
54
+ - reinsertion_lobe_cc_pct
55
+ - reinsertion_lobe_ml_pct
56
+ - reinsertion_lobe_ap_pct
57
+ - reinsertion_lung_cc_pct
58
+ - reinsertion_lung_ml_pct
59
+ - reinsertion_lung_ap_pct
60
+ - reinsertion_pleural_dist_mm
61
+ - reinsertion_airway_dist_mm
62
+ - reinsertion_nodule_diam_mm
63
+ categorical:
64
+ - lobe_name
65
+ - lung_side
66
+ - lung_zone
67
+ - central_peripheral
68
+ - reinsertion_lobe
69
+ - reinsertion_lung_side
70
+ - reinsertion_lung_zone
71
+ scaler: robust
72
+ imputer: median
73
+
74
+ # ── Embedding model presets ────────────────────────────────────────────────
75
+ models:
76
+
77
+ PCA_2D:
78
+ algorithm: pca
79
+ n_components: 2
80
+
81
+ PCA_32:
82
+ algorithm: pca
83
+ n_components: 32
84
+
85
+ UMAP_2D:
86
+ algorithm: umap
87
+ n_components: 2
88
+ n_neighbors: 30
89
+ min_dist: 0.3
90
+ metric: euclidean
91
+
92
+ UMAP_16:
93
+ algorithm: umap
94
+ n_components: 16
95
+ n_neighbors: 30
96
+ min_dist: 0.1
97
+ metric: euclidean
98
+
99
+ UMAP_32:
100
+ algorithm: umap
101
+ n_components: 32
102
+ n_neighbors: 30
103
+ min_dist: 0.1
104
+ metric: euclidean
105
+
106
+ TSNE_2D:
107
+ algorithm: tsne
108
+ n_components: 2
109
+ perplexity: 30
110
+ learning_rate: auto
111
+ n_iter: 1000
itrialspace/configs/integration.example.yaml ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ============================================================================
2
+ # iTrialSpace -> NodMAISI Integration Pipeline β€” Configuration
3
+ # ============================================================================
4
+
5
+ # -- Paths to NodMAISI model components -----------------------------------
6
+ # Paths use ${VAR} placeholders expanded by itrialspace.config.settings.
7
+ # Model weights are NOT bundled β€” set NODMAISI_MODELS_DIR to the directory holding
8
+ # autoencoder.pt / diffusion_unet.pt / controlnet *.pt (see docs/installation.md).
9
+ nodmaisi:
10
+ project_dir: ${ITRIALSPACE_ROOT}/src/itrialspace/synthesis
11
+ model_config: configs/config_maisi3d-rflow.json
12
+ controlnet_config: configs/infr_config_NoMAISI_controlnet.json
13
+ env_config: configs/infr_env_NoMAISI_DLCSD24_demo.json
14
+ # Model checkpoints (absolute via NODMAISI_MODELS_DIR, or relative to project_dir)
15
+ autoencoder_path: ${NODMAISI_MODELS_DIR}/autoencoder.pt
16
+ diffusion_unet_path: ${NODMAISI_MODELS_DIR}/diffusion_unet.pt
17
+ controlnet_path: ${NODMAISI_MODELS_DIR}/Experiments_NoMAISI_512xy_256z_771p25m_finetune_500epoch_best.pt
18
+
19
+ # -- Inference parameters -------------------------------------------------
20
+ inference:
21
+ num_inference_steps: 30
22
+ autoencoder_sliding_window_infer_size: [80, 80, 64]
23
+ autoencoder_sliding_window_infer_overlap: 0.25
24
+ noise_factor: 1.0
25
+ modality: 1 # 1 = CT
26
+ seed: 42
27
+ device: "cuda:0"
28
+
29
+ # -- iTrialSpace mask parameters ------------------------------------------
30
+ itrialspace:
31
+ nodule_label_value: 23 # Label value used by iTrialSpace for inserted nodules
32
+ # Base directory for resolving relative paths in iTrialSpace manifests/audits
33
+ base_dir: ${ITRIALSPACE_DATA_DIR}
34
+ # Root of iTrialSpace trial manifests (JSON/CSV with host_ct_path per case)
35
+ manifest_root: ${ITRIALSPACE_DATA_DIR}/manifests
36
+
37
+ # -- Output structure -----------------------------------------------------
38
+ output:
39
+ # Root for generated CTs. {trial_name} is substituted at runtime.
40
+ root: ${ITRIALSPACE_OUTPUT_DIR}/generated_cts
41
+ # Per-case subdirectory template
42
+ case_dir_template: "case_{case_id}"
43
+ # Filenames inside each case directory
44
+ synthetic_ct_name: synthetic_ct.nii.gz
45
+ input_mask_name: input_mask.nii.gz
46
+ host_ct_link_name: host_ct.nii.gz
47
+ qc_dir_name: qc
48
+ audit_name: nodmaisi_audit.json
49
+
50
+ # -- QC settings ----------------------------------------------------------
51
+ qc:
52
+ enabled: true
53
+ # Number of axial slices to render (evenly spaced through the nodule region)
54
+ num_slices: 3
55
+ # Window level / width for CT display (HU)
56
+ window_center: -600
57
+ window_width: 1500
58
+ # PNG DPI
59
+ dpi: 150
60
+
61
+ # -- Geometry constraints (from NodMAISI check_input) ---------------------
62
+ geometry:
63
+ # Valid XY sizes for NodMAISI (first two dims must be equal)
64
+ valid_xy_sizes: [256, 384, 512]
65
+ # Valid Z sizes
66
+ valid_z_sizes: [128, 256, 384, 512, 640, 768]
67
+ # Target spacing for resampling if needed (null = use mask's native spacing)
68
+ target_spacing: null
69
+ # If true, resample mask to nearest valid size; if false, skip cases that don't fit
70
+ auto_resize: true
71
+
72
+ # -- Conda / environment (for SLURM scripts) -----------------------------
73
+ environment:
74
+ conda_module: ""
75
+ conda_env: ${ITRIALSPACE_CONDA_ENV}
76
+ monai_data_directory: ${ITRIALSPACE_ROOT}/src/itrialspace/synthesis
itrialspace/configs/mask_inserter.example.yaml ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # iTrialSpace Mask Insertion Engine β€” defaults
2
+ # Override per-site via --config flag or INSERTER_CONFIG env var.
3
+
4
+ # ── Lobe label mapping (VISTA3D integer labels) ─────────────────────────────
5
+ lobe_labels:
6
+ left_lung_upper_lobe: 28
7
+ left_lung_lower_lobe: 29
8
+ right_lung_upper_lobe: 30
9
+ right_lung_middle_lobe: 31
10
+ right_lung_lower_lobe: 32
11
+
12
+ # String ↔ integer aliases accepted in manifest ``insertion_lobe`` column.
13
+ # Keys are normalised lowercased names; values map to the canonical key above.
14
+ lobe_aliases:
15
+ lul: left_lung_upper_lobe
16
+ lll: left_lung_lower_lobe
17
+ rul: right_lung_upper_lobe
18
+ rml: right_lung_middle_lobe
19
+ rll: right_lung_lower_lobe
20
+ left_upper: left_lung_upper_lobe
21
+ left_lower: left_lung_lower_lobe
22
+ right_upper: right_lung_upper_lobe
23
+ right_middle: right_lung_middle_lobe
24
+ right_lower: right_lung_lower_lobe
25
+
26
+ # Labels treated as "whole lung" for fallback placement.
27
+ lung_labels: [28, 29, 30, 31, 32]
28
+
29
+ # ── Nodule output label ─────────────────────────────────────────────────────
30
+ # Integer value written into the host output mask for inserted nodule voxels.
31
+ # The intermediate binary mask (0/1) is converted to this label before writing.
32
+ # Default 23; change without code edits by overriding this value.
33
+ nodule_label_value: 23
34
+
35
+ # Future extension: per-nodule-type label mapping (unused for now).
36
+ # When populated, keys are nodule type strings and values are integer labels.
37
+ # Example: {"malignant": 23, "benign": 24}
38
+ nodule_type_to_label: {}
39
+
40
+ # ── Placement parameters ────────────────────────────────────────────────────
41
+ placement:
42
+ # Maximum search radius (voxels) when snapping an out-of-mask candidate to
43
+ # the nearest valid voxel inside the target mask.
44
+ max_snap_radius_vox: 25
45
+
46
+ # Minimum distance (mm) from the lung boundary that an insertion centre must
47
+ # satisfy. Set to 0 to disable.
48
+ min_pleural_dist_mm: 2.0
49
+
50
+ # If True, check for overlap with existing nodules in the combined mask and
51
+ # attempt to shift the placement to avoid it.
52
+ check_overlap: true
53
+
54
+ # Maximum fraction of donor mask voxels allowed to overlap with an existing
55
+ # nodule mask before the placement is declared infeasible.
56
+ max_overlap_fraction: 0.05
57
+
58
+ # Maximum additional shift (voxels) attempted to resolve overlap collisions.
59
+ max_collision_shift_vox: 15
60
+
61
+ # ── Resampling parameters ───────────────────────────────────────────────────
62
+ resample:
63
+ # Interpolation for binary masks: "nearest" (default) or "linear" then
64
+ # threshold.
65
+ interpolation: nearest
66
+
67
+ # After resampling, voxels with value >= this threshold are set to 1.
68
+ binary_threshold: 0.5
69
+
70
+ # Remove connected components smaller than this (voxels) after resampling.
71
+ min_component_size_vox: 3
72
+
73
+ # Fill holes in the binary mask after resampling.
74
+ fill_holes: true
75
+
76
+ # ── Output naming ───────────────────────────────────────────────────────────
77
+ output:
78
+ # Flat directory β€” all combined masks in one folder, no subdirectories.
79
+ use_case_subdirs: false
80
+
81
+ # Combined mask template.
82
+ # Delimiter convention: '--' separates fields, '-' separates key from value.
83
+ # Parsing: dict(f.split('-', 1) for f in stem.split('--')[1:] if '-' in f)
84
+ # Available placeholders: {trial_name}, {case_id}, {host_id}, {host_dataset}, {donor_id}.
85
+ # case_id is zero-padded to 4 digits. host_id is SHA-256[:8] when >20 chars.
86
+ combined_mask_template: "iTS--{trial_name}--C{case_id}--host-{host_id}--src-{host_dataset}--nod-{donor_id}_mask.nii.gz"
87
+
88
+ # Whether to save individual per-nodule binary masks (in addition to the combined mask).
89
+ save_per_nodule_mask: false
90
+
91
+ # Per-nodule mask template (only used when save_per_nodule_mask is true).
92
+ nodule_mask_template: "case_{case_id}_nodule_{nodule_idx}_mask.nii.gz"
93
+
94
+ # Audit log filename.
95
+ audit_name: audit.json
96
+
97
+ # Compress NIfTI outputs.
98
+ compress: true
99
+
100
+ # ── Optional CT intensity insertion (experimental, off by default) ──────────
101
+ ct_insertion:
102
+ enabled: false
103
+ blending_mode: poisson # poisson | direct | alpha
104
+ boundary_width_mm: 2.0
105
+
106
+ # ── Parallelism ─────────────────────────────────────────────────────────────
107
+ parallel:
108
+ backend: loky # loky | threading | sequential
109
+ n_jobs: 1
110
+ verbose: 10
111
+
112
+ # ── Reproducibility ─────────────────────────────────────────────────────────
113
+ seed: 42
itrialspace/configs/paths.example.yaml ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # iTrialSpace path layout β€” unified data directory.
2
+ #
3
+ # Copy to `configs/paths.yaml` and adjust if your layout differs. ${ITRIALSPACE_DATA_DIR}
4
+ # is expanded by itrialspace.config.settings (default: ~/.itrialspace/data).
5
+ #
6
+ # ${ITRIALSPACE_DATA_DIR}/
7
+ # β”œβ”€β”€ raw_ct/{DATASET}/ CT scans (resampled NIfTI)
8
+ # β”œβ”€β”€ masks/{DATASET}/
9
+ # β”‚ β”œβ”€β”€ nodule_seg/ Individual nodule masks
10
+ # β”‚ β”œβ”€β”€ combined_seg/ Combined patient masks
11
+ # β”‚ β”œβ”€β”€ organ_seg/ VISTA3D organ segmentations (raw, deprecated)
12
+ # β”‚ └── refined_seg/ Refined organ + body segmentations (used by default)
13
+ # β”œβ”€β”€ profiles/ Nodule profile CSVs
14
+ # └── meta/ Original dataset metadata CSVs
15
+ #
16
+ # ct_path values in profile CSVs are relative to raw_ct/, e.g.
17
+ # "DLCS24/DLCS_0001.nii.gz" β†’ ${ITRIALSPACE_DATA_DIR}/raw_ct/DLCS24/DLCS_0001.nii.gz
18
+
19
+ # ── Global base directory ──────────────────────────────────────────────────
20
+ base_dir: ${ITRIALSPACE_DATA_DIR}
21
+
22
+ # ── Per-dataset configuration ──────────────────────────────────────────────
23
+ # Only override patterns/flags when they differ from the defaults:
24
+ # organ_seg_pattern: "{ct_id}_seg.nii.gz"
25
+ # nodule_seg_pattern: "{annotation_id}.nii.gz"
26
+ # combined_mask_pattern: "{ct_id}_mask.nii.gz"
27
+
28
+ datasets:
29
+
30
+ DLCS24:
31
+ profile_csv: DLCS24_nodule_profiles.csv
32
+ meta_csv: DLCS24_BMdataset_FEB192026_FIT_v1.csv
33
+
34
+ LUNA25:
35
+ profile_csv: LUNA25_nodule_profiles.csv
36
+ meta_csv: LUNA25_dataset_FEB192026_FIT_v1.csv
37
+
38
+ LUNA16:
39
+ profile_csv: LUNA16_nodule_profiles.csv
40
+ meta_csv: LUNA16_dataset_FEB192026_FIT_v1.csv
41
+
42
+ LUNGx:
43
+ profile_csv: LUNGx_nodule_profiles.csv
44
+ meta_csv: LUNGx_dataset_FEB192026_FIT_v1.csv
45
+
46
+ LNDbv4:
47
+ profile_csv: LNDbv4_nodule_profiles.csv
48
+ meta_csv: LNDBv4_dataset_FEB192026_FIT_v1.csv
49
+
50
+ NSCLCR:
51
+ profile_csv: NSCLCR_nodule_profiles.csv
52
+ meta_csv: NSCLCR_dataset_FEB192026_FIT_v1.csv
53
+ nodule_seg_pattern: "{annotation_id}.nii.gz"
54
+ combined_mask_pattern: "{ct_id}.nii.gz"
55
+
56
+ IMDCT:
57
+ profile_csv: IMDCT_nodule_profiles.csv
58
+ meta_csv: IMDCT_dataset_FEB192026_FIT_v1.csv
59
+ nodule_seg_use_ct_id: true
60
+ nodule_seg_pattern: "{ct_id}_seg.nii.gz"
61
+ combined_mask_pattern: "{ct_id}_seg.nii.gz"
itrialspace/configs/trials.yaml ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Published lung cancer screening trial parameters.
2
+ # Used by TrialKnowledgeBase to instantiate TrialSpec objects.
3
+ #
4
+ # Sources:
5
+ # NLST: Aberle et al. NEJM 2011; 365:395-409
6
+ # NELSON: de Koning et al. NEJM 2020; 382:503-513
7
+ # UKLS: Field et al. Lancet Respir Med 2016; 4:699-709
8
+ # DANTE: Infante et al. AJRCCM 2009; 180:445-453
9
+ # MILD: Pastorino et al. ERJ 2012; 39:1354-1362
10
+
11
+ trials:
12
+
13
+ NLST:
14
+ full_name: "National Lung Screening Trial"
15
+ publication: "Aberle et al. NEJM 2011"
16
+ population: screening
17
+ n_participants: 26722
18
+ demographics:
19
+ age_range: [55, 74]
20
+ age_mean: 61.4
21
+ age_std: 5.0
22
+ sex_ratio_male: 0.59
23
+ smoking_status: ["Current", "Former"]
24
+ pack_years_min: 30
25
+ nodule_prevalence:
26
+ any_nodule: 0.245
27
+ malignancy_rate: 0.04
28
+ size_distribution:
29
+ bucket_weights:
30
+ "<5mm": 0.42
31
+ "5-10mm": 0.38
32
+ "10-15mm": 0.11
33
+ "15-20mm": 0.05
34
+ "20-30mm": 0.03
35
+ ">30mm": 0.01
36
+ malignancy_rate_by_size:
37
+ "<5mm": 0.01
38
+ "5-10mm": 0.024
39
+ "10-15mm": 0.094
40
+ "15-20mm": 0.178
41
+ "20-30mm": 0.222
42
+ ">30mm": 0.362
43
+ lobe_distribution:
44
+ right_lung_upper_lobe: 0.30
45
+ right_lung_middle_lobe: 0.08
46
+ right_lung_lower_lobe: 0.18
47
+ left_lung_upper_lobe: 0.28
48
+ left_lung_lower_lobe: 0.16
49
+ applicable_source_datasets: ["DLCS24", "LUNA25", "LUNA16", "LNDbv4"]
50
+
51
+ NELSON:
52
+ full_name: "Nederlands-Leuvens Longkanker Screenings Onderzoek"
53
+ publication: "de Koning et al. NEJM 2020"
54
+ population: screening
55
+ n_participants: 7557
56
+ demographics:
57
+ age_range: [50, 75]
58
+ age_mean: 58.0
59
+ age_std: 5.5
60
+ sex_ratio_male: 0.84
61
+ smoking_status: ["Current", "Former"]
62
+ pack_years_min: 15
63
+ nodule_prevalence:
64
+ any_nodule: 0.50
65
+ malignancy_rate: 0.022
66
+ size_distribution:
67
+ bucket_weights:
68
+ "<5mm": 0.55
69
+ "5-10mm": 0.30
70
+ "10-15mm": 0.09
71
+ "15-20mm": 0.04
72
+ ">20mm": 0.02
73
+ malignancy_rate_by_size:
74
+ "<5mm": 0.005
75
+ "5-10mm": 0.014
76
+ "10-15mm": 0.063
77
+ "15-20mm": 0.156
78
+ ">20mm": 0.308
79
+ lobe_distribution:
80
+ right_lung_upper_lobe: 0.30
81
+ right_lung_middle_lobe: 0.08
82
+ right_lung_lower_lobe: 0.18
83
+ left_lung_upper_lobe: 0.28
84
+ left_lung_lower_lobe: 0.16
85
+ applicable_source_datasets: ["DLCS24", "LUNA25", "LUNA16", "LNDbv4"]
86
+
87
+ UKLS:
88
+ full_name: "UK Lung Cancer Screening Trial"
89
+ publication: "Field et al. Lancet Respir Med 2016"
90
+ population: screening
91
+ n_participants: 1994
92
+ demographics:
93
+ age_range: [50, 75]
94
+ sex_ratio_male: 0.52
95
+ smoking_status: ["Current", "Former"]
96
+ pack_years_min: 20
97
+ nodule_prevalence:
98
+ any_nodule: 0.34
99
+ malignancy_rate: 0.017
100
+ size_distribution:
101
+ bucket_weights:
102
+ "<5mm": 0.48
103
+ "5-10mm": 0.35
104
+ "10-15mm": 0.10
105
+ "15-20mm": 0.04
106
+ ">20mm": 0.03
107
+ lobe_distribution:
108
+ right_lung_upper_lobe: 0.30
109
+ right_lung_middle_lobe: 0.08
110
+ right_lung_lower_lobe: 0.18
111
+ left_lung_upper_lobe: 0.28
112
+ left_lung_lower_lobe: 0.16
113
+ applicable_source_datasets: ["DLCS24", "LUNA25", "LUNA16"]
114
+
115
+ DANTE:
116
+ full_name: "Detection And screening of early lung Neoplasm with LDCT"
117
+ publication: "Infante et al. AJRCCM 2009"
118
+ population: screening
119
+ n_participants: 1276
120
+ demographics:
121
+ age_range: [60, 75]
122
+ sex_ratio_male: 1.0
123
+ smoking_status: ["Current", "Former"]
124
+ pack_years_min: 20
125
+ nodule_prevalence:
126
+ any_nodule: 0.31
127
+ malignancy_rate: 0.028
128
+ size_distribution:
129
+ bucket_weights:
130
+ "<5mm": 0.40
131
+ "5-10mm": 0.37
132
+ "10-15mm": 0.13
133
+ "15-20mm": 0.06
134
+ ">20mm": 0.04
135
+ applicable_source_datasets: ["DLCS24", "LUNA25"]
136
+
137
+ MILD:
138
+ full_name: "Multicentric Italian Lung Detection Trial"
139
+ publication: "Pastorino et al. ERJ 2012"
140
+ population: screening
141
+ n_participants: 2376
142
+ demographics:
143
+ age_range: [49, 75]
144
+ sex_ratio_male: 0.66
145
+ smoking_status: ["Current", "Former"]
146
+ pack_years_min: 20
147
+ nodule_prevalence:
148
+ any_nodule: 0.28
149
+ malignancy_rate: 0.012
150
+ size_distribution:
151
+ bucket_weights:
152
+ "<5mm": 0.52
153
+ "5-10mm": 0.33
154
+ "10-15mm": 0.09
155
+ "15-20mm": 0.04
156
+ ">20mm": 0.02
157
+ applicable_source_datasets: ["DLCS24", "LUNA25", "LUNA16"]
itrialspace/docker/Dockerfile ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # iTrialSpace β€” lightweight image for the core pipeline + web tools.
2
+ #
3
+ # docker build -t itrialspace -f docker/Dockerfile .
4
+ # docker run --rm -e ITRIALSPACE_DATA_DIR=/data -v /host/data:/data itrialspace its config
5
+ #
6
+ # GPU stages (synthesis, VLM) need a CUDA base image + torch; this image covers the
7
+ # core/imaging/web extras. See docs/installation.md for the GPU setup.
8
+ FROM python:3.11-slim
9
+
10
+ ENV PYTHONUNBUFFERED=1 \
11
+ PIP_NO_CACHE_DIR=1 \
12
+ ITRIALSPACE_DATA_DIR=/data
13
+
14
+ # System libs needed by nibabel/SimpleITK/matplotlib/faiss
15
+ RUN apt-get update && apt-get install -y --no-install-recommends \
16
+ build-essential libgl1 libglib2.0-0 git \
17
+ && rm -rf /var/lib/apt/lists/*
18
+
19
+ WORKDIR /app
20
+
21
+ # Install dependencies first (better layer caching), then the package.
22
+ COPY pyproject.toml README.md ./
23
+ COPY src ./src
24
+ COPY configs ./configs
25
+ RUN pip install --upgrade pip && pip install ".[imaging,web]"
26
+
27
+ # Bring in the rest (docs, tests, infra, sample data)
28
+ COPY . .
29
+
30
+ # Non-root user
31
+ RUN useradd -m -u 1000 its && mkdir -p /data && chown -R its:its /app /data
32
+ USER its
33
+
34
+ ENTRYPOINT ["its"]
35
+ CMD ["config"]
itrialspace/docker/Dockerfile.gpu ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # iTrialSpace β€” GPU image for synthesis (NodMAISI) and VLM evaluation.
2
+ # Pinned to the development environment: CUDA 12.1, torch 2.4.1, git-pinned MONAI.
3
+ #
4
+ # docker build -t itrialspace-gpu -f docker/Dockerfile.gpu .
5
+ #
6
+ # # Step 3 synthesis (mount data, outputs, and the NodMAISI weights):
7
+ # docker run --rm --gpus all \
8
+ # -e ITRIALSPACE_DATA_DIR=/data -e ITRIALSPACE_OUTPUT_DIR=/out \
9
+ # -e NODMAISI_MODELS_DIR=/models \
10
+ # -v /host/iTrialSpace:/data -v /host/outputs:/out -v /host/nodmaisi/models:/models \
11
+ # --entrypoint python itrialspace-gpu \
12
+ # -m itrialspace.synthesis.tools.run_itrialspace_to_ct \
13
+ # --audit /out/inserted_masks/mode1_controlled_prevalence/audit.json \
14
+ # --config src/itrialspace/synthesis/tools/integration_config.yaml \
15
+ # --outdir /out/generated_cts/mode1_controlled_prevalence
16
+ #
17
+ # For a byte-for-byte clone of the dev env instead, build from requirements.lock.txt
18
+ # (see docs/installation.md). Base matches torch 2.4.1+cu121.
19
+ FROM nvidia/cuda:12.1.1-cudnn8-runtime-ubuntu22.04
20
+
21
+ ENV DEBIAN_FRONTEND=noninteractive \
22
+ PYTHONUNBUFFERED=1 \
23
+ PIP_NO_CACHE_DIR=1 \
24
+ ITRIALSPACE_DATA_DIR=/data \
25
+ ITRIALSPACE_OUTPUT_DIR=/out \
26
+ NODMAISI_MODELS_DIR=/models
27
+
28
+ # System Python (3.10 on 22.04; package requires >=3.10) + libs for nibabel/SimpleITK/matplotlib
29
+ RUN apt-get update && apt-get install -y --no-install-recommends \
30
+ python3 python3-pip python3-dev build-essential git \
31
+ libgl1 libglib2.0-0 \
32
+ && ln -sf /usr/bin/python3 /usr/bin/python \
33
+ && rm -rf /var/lib/apt/lists/*
34
+
35
+ WORKDIR /app
36
+ COPY . .
37
+
38
+ # Match the dev env: torch 2.4.1 (cu121) and the git-pinned MONAI build, then the
39
+ # package (editable so the synthesis subprocess path model resolves like dev).
40
+ RUN pip install --upgrade pip \
41
+ && pip install torch==2.4.1 --index-url https://download.pytorch.org/whl/cu121 \
42
+ && pip install "monai @ git+https://github.com/Project-MONAI/MONAI.git@c3a317d2bcb486199f40bda0d722a41e3869712a" \
43
+ && pip install -e ".[imaging,synthesis,vlm]"
44
+
45
+ # Non-root user; create the runtime mount points
46
+ RUN useradd -m -u 1000 its && mkdir -p /data /out /models && chown -R its:its /app /data /out /models
47
+ USER its
48
+
49
+ # Default to the umbrella CLI; override --entrypoint for synthesis/VLM module runs.
50
+ ENTRYPOINT ["its"]
51
+ CMD ["config"]
itrialspace/docker/itrialspace.def ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Apptainer/Singularity recipe for iTrialSpace (GPU) β€” for HPC clusters that use
2
+ # Apptainer instead of Docker. Builds rootless, no Docker daemon required.
3
+ #
4
+ # # Build the image (.sif) β€” run from the repo root:
5
+ # apptainer build itrialspace.sif docker/itrialspace.def
6
+ #
7
+ # # Or convert the already-built Docker image:
8
+ # apptainer build itrialspace.sif docker-daemon://itrialspace-gpu:latest
9
+ #
10
+ # # Run the umbrella CLI (Apptainer bind-mounts $HOME and $PWD by default; add others):
11
+ # apptainer run --nv \
12
+ # --env ITRIALSPACE_DATA_DIR=/data,ITRIALSPACE_OUTPUT_DIR=/out,NODMAISI_MODELS_DIR=/models \
13
+ # -B /scratch/.../iTrialSpace:/data,/scratch/.../outputs:/out,/path/nodmaisi/models:/models \
14
+ # itrialspace.sif config
15
+ #
16
+ # # Step 3 synthesis:
17
+ # apptainer exec --nv \
18
+ # --env ITRIALSPACE_DATA_DIR=/data,ITRIALSPACE_OUTPUT_DIR=/out,NODMAISI_MODELS_DIR=/models \
19
+ # -B /host/iTrialSpace:/data,/host/outputs:/out,/host/nodmaisi/models:/models \
20
+ # itrialspace.sif \
21
+ # python -m itrialspace.synthesis.tools.run_itrialspace_to_ct \
22
+ # --audit /out/inserted_masks/mode1_controlled_prevalence/audit.json \
23
+ # --config /opt/itrialspace/src/itrialspace/synthesis/tools/integration_config.yaml \
24
+ # --outdir /out/generated_cts/mode1_controlled_prevalence
25
+ #
26
+ # NOTE: build from the repo root so %files can copy the source tree.
27
+
28
+ Bootstrap: docker
29
+ From: nvidia/cuda:12.1.1-cudnn8-runtime-ubuntu22.04
30
+
31
+ %files
32
+ . /opt/itrialspace
33
+
34
+ %post
35
+ export DEBIAN_FRONTEND=noninteractive
36
+ apt-get update && apt-get install -y --no-install-recommends \
37
+ python3 python3-pip python3-dev build-essential git \
38
+ libgl1 libglib2.0-0
39
+ ln -sf /usr/bin/python3 /usr/bin/python
40
+ rm -rf /var/lib/apt/lists/*
41
+
42
+ cd /opt/itrialspace
43
+ # Drop any host-local state copied in via %files
44
+ rm -rf .git .env logs/* **/__pycache__ 2>/dev/null || true
45
+ pip install --upgrade pip
46
+ pip install torch==2.4.1 --index-url https://download.pytorch.org/whl/cu121
47
+ pip install "monai @ git+https://github.com/Project-MONAI/MONAI.git@c3a317d2bcb486199f40bda0d722a41e3869712a"
48
+ pip install -e ".[imaging,synthesis,vlm]"
49
+
50
+ %environment
51
+ export ITRIALSPACE_ROOT=/opt/itrialspace
52
+ export ITRIALSPACE_DATA_DIR=${ITRIALSPACE_DATA_DIR:-/data}
53
+ export ITRIALSPACE_OUTPUT_DIR=${ITRIALSPACE_OUTPUT_DIR:-/out}
54
+ export NODMAISI_MODELS_DIR=${NODMAISI_MODELS_DIR:-/models}
55
+ export PYTHONUNBUFFERED=1
56
+
57
+ %runscript
58
+ exec its "$@"
59
+
60
+ %labels
61
+ Name iTrialSpace
62
+ Description Synthetic Imaging Clinical Trial Engine (GPU)
63
+
64
+ %help
65
+ iTrialSpace container. Bind your data/outputs/weights and set the matching
66
+ ITRIALSPACE_DATA_DIR / ITRIALSPACE_OUTPUT_DIR / NODMAISI_MODELS_DIR env vars.
67
+ Use `apptainer run` for the `its` CLI, or `apptainer exec ... python -m ...`
68
+ for synthesis/VLM module runs. See docs/installation.md.
itrialspace/environment.lock.yml ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Exact clone of the original development environment.
2
+ # Reproduces Python 3.10.13 + the full pinned package set (linux-64, CUDA 12.1),
3
+ # including torch 2.4.1+cu121 and the git-pinned MONAI build.
4
+ #
5
+ # conda env create -f environment.lock.yml
6
+ # conda activate itrialspace
7
+ #
8
+ # This is the "give me exactly what worked" option. For a lighter, less pinned
9
+ # setup use environment.yml instead. See docs/installation.md.
10
+ name: itrialspace
11
+ channels:
12
+ - conda-forge
13
+ dependencies:
14
+ - python=3.10.13
15
+ - pip
16
+ - pip:
17
+ - -r requirements.lock.txt
18
+ - -e .
itrialspace/environment.yml ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Conda environment for iTrialSpace β€” matches the development environment versions.
2
+ #
3
+ # conda env create -f environment.yml
4
+ # conda activate itrialspace
5
+ #
6
+ # IMPORTANT: install everything in ONE pip resolution (this file does). Do NOT follow
7
+ # up with extra unpinned `pip install`s β€” the `>=` extras would drift to latest and
8
+ # bump torch/transformers/monai. For an exact freeze, see requirements.lock.txt.
9
+ #
10
+ # Verified versions: Python 3.10, torch 2.4.1+cu121, torchvision 0.19.1+cu121,
11
+ # transformers 4.51.3, open_clip 2.32.0, MONAI (git dev commit), numpy 1.26.4.
12
+ # CUDA 12.1 build of torch β€” adjust the index URL to match your driver if needed.
13
+ name: itrialspace
14
+ channels:
15
+ - conda-forge
16
+ dependencies:
17
+ - python=3.10
18
+ - pip>=23
19
+ - pip:
20
+ - --extra-index-url https://download.pytorch.org/whl/cu121
21
+ # Behavior-critical pins (match the dev env exactly)
22
+ - numpy==1.26.4
23
+ - torch==2.4.1
24
+ - torchvision==0.19.1
25
+ - transformers==4.51.3
26
+ - open_clip_torch==2.32.0
27
+ - seaborn>=0.12
28
+ - monai @ git+https://github.com/Project-MONAI/MONAI.git@c3a317d2bcb486199f40bda0d722a41e3869712a
29
+ # The package with all in-repo extras (deps resolve around the pins above)
30
+ - -e .[imaging,apps,synthesis,vlm,dev]
itrialspace/infra/slurm/README.md ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SLURM job scripts
2
+
3
+ HPC submission scripts for every stage of the iTrialSpace pipeline. They are
4
+ **cluster-portable**: paths, the conda environment, and partitions come from
5
+ environment variables (with sane defaults) rather than being hardcoded.
6
+
7
+ ## How portability works
8
+
9
+ Every script sources [`env.sh`](env.sh) near the top:
10
+
11
+ ```bash
12
+ source "$(dirname "$0")/../env.sh" # sets PROJ_DIR, ITRIALSPACE_DATA_DIR, CONDA_ENV, ...
13
+ itrialspace_activate_conda # activates the conda env portably
14
+ ```
15
+
16
+ `env.sh` resolves (overridable via your shell or a repo-root `.env`):
17
+
18
+ | Variable | Default | Meaning |
19
+ |----------|---------|---------|
20
+ | `PROJ_DIR` | auto (repo root) | iTrialSpace checkout |
21
+ | `ITRIALSPACE_DATA_DIR` | `~/.itrialspace/data` | unified data layout |
22
+ | `ITRIALSPACE_OUTPUT_DIR` | `=DATA_DIR` | generated artifacts |
23
+ | `ITRIALSPACE_CONDA_ENV` | `itrialspace` | conda env name |
24
+ | `CONDA_PROFILE` | auto-detected | path to `conda.sh` |
25
+ | `SLURM_PARTITION_GPU` / `SLURM_PARTITION_CPU` | `gpu` / `cpu` | partitions |
26
+
27
+ ## Adapting to a new cluster
28
+
29
+ 1. Set the variables above in your `.env` (copy `.env.example`) or shell profile.
30
+ 2. **Edit the `#SBATCH` directives** in the scripts you use β€” partition names
31
+ (`--partition`), account (`--account`), GPU type, walltime, and memory are
32
+ cluster-specific and cannot be set from environment variables (SLURM parses
33
+ `#SBATCH` lines before the shell runs). Search-and-replace the partition names
34
+ for your site.
35
+ 3. Submit from the repo root, e.g. `sbatch infra/slurm/nodulemap/nodulemap.sub`.
36
+
37
+ ## Layout
38
+
39
+ | Directory | Stage |
40
+ |-----------|-------|
41
+ | `trials/` | Generate cohort manifests (13 modes) |
42
+ | `mask_inserter/` | Insert nodule masks into host CTs |
43
+ | `synthesis/` | NodMAISI CT synthesis (needs model weights β€” see docs) |
44
+ | `nodulemap/` Β· `retriever/` | Launch interactive web tools |
45
+ | `vlm_eval/` | Vision-language model evaluation |
46
+
47
+ > Logs are written to `logs/` (gitignored). Create it first or let the scripts `mkdir -p logs`.
itrialspace/infra/slurm/_gen_caselist.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Write a synthesis case list (mask-filename stems) from an insertion audit.json.
3
+
4
+ The synthesis runner matches --case-ids against the mask-filename stem (NOT the
5
+ audit's integer case_id), so the case list must contain those stems.
6
+
7
+ Usage: python _gen_caselist.py <audit.json> <out_caselist.txt> # prints N cases
8
+ """
9
+ import json
10
+ import os
11
+ import sys
12
+
13
+
14
+ def stem(path: str) -> str:
15
+ name = os.path.basename(path)
16
+ for suffix in ("_mask.nii.gz", ".nii.gz"):
17
+ if name.endswith(suffix):
18
+ return name[: -len(suffix)]
19
+ return name
20
+
21
+
22
+ def main() -> None:
23
+ audit, out = sys.argv[1], sys.argv[2]
24
+ data = json.load(open(audit))
25
+ recs = data.get("records", data.get("cases", []))
26
+ cases = sorted(
27
+ {stem(r["output_combined_path"]) for r in recs
28
+ if r.get("status") == "success" and r.get("output_combined_path")}
29
+ )
30
+ os.makedirs(os.path.dirname(out) or ".", exist_ok=True)
31
+ with open(out, "w") as f:
32
+ f.write("\n".join(cases) + "\n")
33
+ print(len(cases))
34
+
35
+
36
+ if __name__ == "__main__":
37
+ main()
itrialspace/infra/slurm/env.sh ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Shared environment for all iTrialSpace SLURM scripts.
3
+ #
4
+ # Every .sub script sources this file instead of hardcoding paths or the conda env:
5
+ #
6
+ # source "$(dirname "${BASH_SOURCE[0]}")/../env.sh"
7
+ #
8
+ # Override any value by exporting it before submitting, or by editing this file /
9
+ # a local copy. Nothing here is host-specific by default β€” set the variables for
10
+ # your cluster in your shell profile or a `.env` next to the repo.
11
+
12
+ # ── Repo root (auto-detected: this file lives at <repo>/infra/slurm/env.sh) ──
13
+ _ENV_SH_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
14
+ export PROJ_DIR="${PROJ_DIR:-$(cd "${_ENV_SH_DIR}/../.." && pwd)}"
15
+
16
+ # Load a repo-local .env for defaults. Precedence: variables already set in the
17
+ # environment (shell export, or `VAR=x sbatch ...`) WIN over .env, which in turn
18
+ # wins over the built-in defaults below. So a per-job override works:
19
+ # ITRIALSPACE_OUTPUT_DIR=/somewhere sbatch infra/slurm/trials/mode1_*.sub
20
+ if [[ -f "${PROJ_DIR}/.env" ]]; then
21
+ while IFS= read -r _line || [[ -n "${_line}" ]]; do
22
+ case "${_line}" in ''|\#*) continue ;; esac # skip blanks/comments
23
+ _key="${_line%%=*}"
24
+ [[ "${_key}" =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]] || continue
25
+ if [[ -z "${!_key+x}" ]]; then # only if not already set
26
+ export "${_key}=$(eval "printf '%s' \"${_line#*=}\"")"
27
+ fi
28
+ done < "${PROJ_DIR}/.env"
29
+ unset _line _key
30
+ fi
31
+
32
+ # ── Data root (unified layout: raw_ct/ masks/ profiles/ ...) ────────────────
33
+ export ITRIALSPACE_DATA_DIR="${ITRIALSPACE_DATA_DIR:-${HOME}/.itrialspace/data}"
34
+ export DATA_BASE="${DATA_BASE:-${ITRIALSPACE_DATA_DIR}}"
35
+ # Output root defaults to the data root β€” computed AFTER .env so it follows it.
36
+ export ITRIALSPACE_OUTPUT_DIR="${ITRIALSPACE_OUTPUT_DIR:-${ITRIALSPACE_DATA_DIR}}"
37
+
38
+ # ── Conda environment ───────────────────────────────────────────────────────
39
+ export ITRIALSPACE_CONDA_ENV="${ITRIALSPACE_CONDA_ENV:-itrialspace}"
40
+ # Isolate from ~/.local user-site packages so the conda env is authoritative
41
+ # (avoids shadowing the env's torch/pytest/etc. with stale user-site copies).
42
+ export PYTHONNOUSERSITE="${PYTHONNOUSERSITE:-1}"
43
+ # Path to your conda profile script (cluster-specific). Common locations tried below.
44
+ export CONDA_PROFILE="${CONDA_PROFILE:-}"
45
+
46
+ # ── SLURM partitions / account (override per cluster) ───────────────────────
47
+ export SLURM_PARTITION_GPU="${SLURM_PARTITION_GPU:-gpu}"
48
+ export SLURM_PARTITION_CPU="${SLURM_PARTITION_CPU:-cpu}"
49
+ export SLURM_ACCOUNT="${SLURM_ACCOUNT:-}"
50
+
51
+ # ── Make the package importable ─────────────────────────────────────────────
52
+ export PYTHONPATH="${PROJ_DIR}/src:${PYTHONPATH:-}"
53
+
54
+ # ── Helper: activate the conda env portably ─────────────────────────────────
55
+ itrialspace_activate_conda() {
56
+ local profile="${CONDA_PROFILE}"
57
+ if [[ -z "${profile}" ]]; then
58
+ for cand in \
59
+ "/cm/shared/apps/miniconda/etc/profile.d/conda.sh" \
60
+ "${HOME}/miniconda3/etc/profile.d/conda.sh" \
61
+ "${HOME}/anaconda3/etc/profile.d/conda.sh" \
62
+ "/opt/conda/etc/profile.d/conda.sh"; do
63
+ [[ -f "${cand}" ]] && profile="${cand}" && break
64
+ done
65
+ fi
66
+ if [[ -n "${profile}" && -f "${profile}" ]]; then
67
+ # shellcheck disable=SC1090
68
+ source "${profile}"
69
+ conda activate "${ITRIALSPACE_CONDA_ENV}"
70
+ else
71
+ echo "WARNING: conda profile not found; set CONDA_PROFILE. Continuing without activation." >&2
72
+ fi
73
+ # torch's pip-installed CUDA libs (cuDNN etc.) aren't auto-found in a clean env β†’
74
+ # put every nvidia/*/lib on LD_LIBRARY_PATH (otherwise: "libcudnn.so.9 not found" /
75
+ # CUDNN_STATUS_NOT_INITIALIZED).
76
+ if [[ -n "${CONDA_PREFIX:-}" ]]; then
77
+ local _d
78
+ for _d in "${CONDA_PREFIX}"/lib/python*/site-packages/nvidia/*/lib; do
79
+ [[ -d "${_d}" ]] && export LD_LIBRARY_PATH="${_d}:${LD_LIBRARY_PATH:-}"
80
+ done
81
+ fi
82
+ }
83
+
84
+ # Run from the repo root and ensure the log directory exists. (The `#SBATCH
85
+ # --output=logs/...` path is opened by SLURM *before* this runs, so also keep a
86
+ # committed logs/ dir and submit from the repo root β€” see infra/slurm/README.md.)
87
+ cd "${PROJ_DIR}" 2>/dev/null || true
88
+ mkdir -p "${PROJ_DIR}/logs"
itrialspace/infra/slurm/mask_inserter/mode10_insert_masks.sub ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # ──────────────────────────────────────────────────────────────────────────────
3
+ # Mode 10: Multi-Nodule Realism Study β€” Mask Insertion
4
+ #
5
+ # Inserts donor nodule masks for multi-nodule realism study manifests.
6
+ # Mode 10 produces 2 manifests (single-nodule and multi-nodule sub-cohorts).
7
+ # Consider the array variant for batch processing across sub-cohorts.
8
+ #
9
+ # Usage:
10
+ # MANIFEST_PATH=.../multi_nodule_study_single.csv sbatch mode10_insert_masks.sub
11
+ # ──────────────────────────────────────────────────────────────────────────────
12
+
13
+ #SBATCH --job-name=ins_M10_MultiNod
14
+ #SBATCH --partition=defq
15
+ #SBATCH --ntasks=1
16
+ #SBATCH --gpus=0
17
+ #SBATCH --cpus-per-task=8
18
+ #SBATCH --mem=32G
19
+ #SBATCH --time=2-00:00:00
20
+ #SBATCH --output=logs/insert_mode10_multi_nodule_realism_%j.out
21
+ #SBATCH --error=logs/insert_mode10_multi_nodule_realism_%j.err
22
+
23
+ # ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) β€” before any var use ──
24
+ 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"
25
+ itrialspace_activate_conda
26
+
27
+
28
+ set -euo pipefail
29
+
30
+ BASE_DIR="${ITRIALSPACE_DATA_DIR}"
31
+ MANIFEST_ROOT="${ITRIALSPACE_OUTPUT_DIR}/manifests"
32
+ OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks"
33
+ PROJECT_DIR="${PROJ_DIR}"
34
+
35
+ TRIAL_MODE="mode10_multi_nodule_realism"
36
+ MANIFEST_PATH="${MANIFEST_PATH:-${MANIFEST_ROOT}/${TRIAL_MODE}/multi_nodule_study_single.csv}"
37
+ OUT_DIR="${OUT_DIR:-${OUTPUT_ROOT}/${TRIAL_MODE}}"
38
+ CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}"
39
+ N_JOBS="${N_JOBS:-8}"
40
+ DRY_RUN="${DRY_RUN:-false}"
41
+ SEED="${SEED:-42}"
42
+
43
+ echo "=================================================================="
44
+ echo " iTrialSpace Mask Insertion β€” Mode 10: Multi-Nodule Realism Study"
45
+ echo " Job ID: ${SLURM_JOB_ID:-local} Node: $(hostname) Date: $(date)"
46
+ echo "=================================================================="
47
+ echo " MANIFEST_PATH : ${MANIFEST_PATH}"
48
+ echo " OUT_DIR : ${OUT_DIR}"
49
+ echo " N_JOBS : ${N_JOBS}"
50
+ echo ""
51
+
52
+ cd "${PROJECT_DIR}"
53
+
54
+ if [ ! -f "${MANIFEST_PATH}" ]; then
55
+ echo "FATAL: Manifest not found: ${MANIFEST_PATH}"
56
+ exit 1
57
+ fi
58
+ mkdir -p "${OUT_DIR}"
59
+
60
+ CFG_ARG=""
61
+ if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then
62
+ CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}"
63
+ elif [ -f "${CONFIG_PATH}" ]; then
64
+ CFG_ARG="--config ${CONFIG_PATH}"
65
+ fi
66
+
67
+ EXTRA_ARGS=""
68
+ [ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run"
69
+
70
+ echo "Running: python3 -m itrialspace.mask_inserter run ..."
71
+ echo " manifest: ${MANIFEST_PATH}"
72
+ echo " output: ${OUT_DIR}"
73
+
74
+ python3 -m itrialspace.mask_inserter run \
75
+ --manifest "${MANIFEST_PATH}" \
76
+ --output-dir "${OUT_DIR}" \
77
+ ${CFG_ARG} \
78
+ --trial-name "${TRIAL_MODE}" \
79
+ --seed ${SEED} \
80
+ --n-jobs ${N_JOBS} \
81
+ ${EXTRA_ARGS}
82
+ EXIT_CODE=$?
83
+ echo "Finished: $(date) Exit: ${EXIT_CODE}"
84
+ exit ${EXIT_CODE}
itrialspace/infra/slurm/mask_inserter/mode10_insert_masks_array.sub ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # ──────────────────────────────────────────────────────────────────────────────
3
+ # Mode 10: Multi-Nodule Realism Study β€” Array Job (one per sub-cohort)
4
+ #
5
+ # Mode 10 produces 2 manifests (single-nodule and multi-nodule sub-cohorts).
6
+ #
7
+ # Usage:
8
+ # python itrialspace_mask_inserter/tools/list_manifests.py \
9
+ # --dir /scratch/.../manifests/mode10_multi_nodule_realism \
10
+ # --output manifests_mode10.txt
11
+ # sbatch --array=0-$(( $(wc -l < manifests_mode10.txt) - 1 )) \
12
+ # mode10_insert_masks_array.sub
13
+ # ──────────────────────────────────────────────────────────────────────────────
14
+
15
+ #SBATCH --job-name=ins_M10_arr
16
+ #SBATCH --partition=defq
17
+ #SBATCH --ntasks=1
18
+ #SBATCH --gpus=0
19
+ #SBATCH --cpus-per-task=8
20
+ #SBATCH --mem=32G
21
+ #SBATCH --time=2-00:00:00
22
+ #SBATCH --output=logs/insert_mode10_multi_nodule_realism_%A_%a.out
23
+ #SBATCH --error=logs/insert_mode10_multi_nodule_realism_%A_%a.err
24
+
25
+ # ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) β€” before any var use ──
26
+ 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"
27
+ itrialspace_activate_conda
28
+
29
+
30
+ set -euo pipefail
31
+
32
+ BASE_DIR="${ITRIALSPACE_DATA_DIR}"
33
+ OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks"
34
+ PROJECT_DIR="${PROJ_DIR}"
35
+
36
+ TRIAL_MODE="mode10_multi_nodule_realism"
37
+ MANIFEST_LIST="${MANIFEST_LIST:-${PROJECT_DIR}/itrialspace_mask_inserter/slurm_trials/manifests_mode10.txt}"
38
+ CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}"
39
+ N_JOBS="${N_JOBS:-8}"
40
+ DRY_RUN="${DRY_RUN:-false}"
41
+ SEED="${SEED:-42}"
42
+
43
+ if [ ! -f "${MANIFEST_LIST}" ]; then
44
+ echo "FATAL: Manifest list not found: ${MANIFEST_LIST}"
45
+ exit 1
46
+ fi
47
+
48
+ TASK_ID="${SLURM_ARRAY_TASK_ID:-0}"
49
+ MANIFEST_PATH=$(sed -n "$((TASK_ID + 1))p" "${MANIFEST_LIST}")
50
+
51
+ if [ -z "${MANIFEST_PATH}" ]; then
52
+ echo "FATAL: No manifest at index ${TASK_ID} in ${MANIFEST_LIST}"
53
+ exit 1
54
+ fi
55
+
56
+ MANIFEST_BASENAME="$(basename "${MANIFEST_PATH}" .csv)"
57
+ MANIFEST_BASENAME="$(basename "${MANIFEST_BASENAME}" .json)"
58
+ OUT_DIR="${OUTPUT_ROOT}/${TRIAL_MODE}/${MANIFEST_BASENAME}"
59
+
60
+ echo "=================================================================="
61
+ echo " iTrialSpace Mask Insertion β€” Mode 10: Multi-Nodule Realism (Array)"
62
+ echo " Job ID: ${SLURM_JOB_ID:-local} Array Task: ${TASK_ID}"
63
+ echo " Node: $(hostname) Date: $(date)"
64
+ echo "=================================================================="
65
+ echo " MANIFEST_PATH : ${MANIFEST_PATH}"
66
+ echo " OUT_DIR : ${OUT_DIR}"
67
+ echo ""
68
+
69
+ cd "${PROJECT_DIR}"
70
+
71
+ if [ ! -f "${MANIFEST_PATH}" ]; then
72
+ echo "FATAL: Manifest not found: ${MANIFEST_PATH}"
73
+ exit 1
74
+ fi
75
+ mkdir -p "${OUT_DIR}"
76
+
77
+ CFG_ARG=""
78
+ if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then
79
+ CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}"
80
+ elif [ -f "${CONFIG_PATH}" ]; then
81
+ CFG_ARG="--config ${CONFIG_PATH}"
82
+ fi
83
+
84
+ EXTRA_ARGS=""
85
+ [ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run"
86
+
87
+ echo "Running: python3 -m itrialspace.mask_inserter run ..."
88
+ echo " manifest: ${MANIFEST_PATH}"
89
+ echo " output: ${OUT_DIR}"
90
+
91
+ python3 -m itrialspace.mask_inserter run \
92
+ --manifest "${MANIFEST_PATH}" \
93
+ --output-dir "${OUT_DIR}" \
94
+ ${CFG_ARG} \
95
+ --trial-name "${TRIAL_MODE}_${MANIFEST_BASENAME}" \
96
+ --seed ${SEED} \
97
+ --n-jobs ${N_JOBS} \
98
+ ${EXTRA_ARGS}
99
+ EXIT_CODE=$?
100
+ echo "Finished: $(date) Exit: ${EXIT_CODE}"
101
+ exit ${EXIT_CODE}
itrialspace/infra/slurm/mask_inserter/mode11_insert_masks.sub ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # ──────────────────────────────────────────────────────────────────────────────
3
+ # Mode 11: Digital Twin Isolation β€” Mask Insertion
4
+ #
5
+ # Inserts one native nodule mask per isolation case. Each row in the manifest
6
+ # represents a single nodule placed into the host patient's own anatomy.
7
+ # Because each case is a single nodule insertion the per-row cost is low,
8
+ # but the total number of rows can be large (one per nodule per patient).
9
+ #
10
+ # Usage:
11
+ # MANIFEST_PATH=.../digital_twin_isolation_DLCS24.csv sbatch mode11_insert_masks.sub
12
+ # ──────────────────────────────────────────────────────────────────────────────
13
+
14
+ #SBATCH --job-name=ins_M11_DTiso
15
+ #SBATCH --partition=defq
16
+ #SBATCH --ntasks=1
17
+ #SBATCH --gpus=0
18
+ #SBATCH --cpus-per-task=8
19
+ #SBATCH --mem=32G
20
+ #SBATCH --time=2-00:00:00
21
+ #SBATCH --output=logs/insert_mode11_digital_twin_isolation_%j.out
22
+ #SBATCH --error=logs/insert_mode11_digital_twin_isolation_%j.err
23
+
24
+ # ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) β€” before any var use ──
25
+ 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"
26
+ itrialspace_activate_conda
27
+
28
+
29
+ set -euo pipefail
30
+
31
+ BASE_DIR="${ITRIALSPACE_DATA_DIR}"
32
+ MANIFEST_ROOT="${ITRIALSPACE_OUTPUT_DIR}/manifests"
33
+ OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks"
34
+ PROJECT_DIR="${PROJ_DIR}"
35
+
36
+ TRIAL_MODE="mode11_digital_twin_isolation"
37
+ MANIFEST_PATH="${MANIFEST_PATH:-${MANIFEST_ROOT}/${TRIAL_MODE}/digital_twin_isolation_DLCS24.csv}"
38
+ OUT_DIR="${OUT_DIR:-${OUTPUT_ROOT}/${TRIAL_MODE}}"
39
+ CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}"
40
+ N_JOBS="${N_JOBS:-8}"
41
+ DRY_RUN="${DRY_RUN:-false}"
42
+ SEED="${SEED:-42}"
43
+
44
+ echo "=================================================================="
45
+ echo " iTrialSpace Mask Insertion β€” Mode 11: Digital Twin Isolation"
46
+ echo " Job ID: ${SLURM_JOB_ID:-local} Node: $(hostname) Date: $(date)"
47
+ echo "=================================================================="
48
+ echo " MANIFEST_PATH : ${MANIFEST_PATH}"
49
+ echo " OUT_DIR : ${OUT_DIR}"
50
+ echo " N_JOBS : ${N_JOBS}"
51
+ echo ""
52
+
53
+ cd "${PROJECT_DIR}"
54
+
55
+ if [ ! -f "${MANIFEST_PATH}" ]; then
56
+ echo "FATAL: Manifest not found: ${MANIFEST_PATH}"
57
+ exit 1
58
+ fi
59
+ mkdir -p "${OUT_DIR}"
60
+
61
+ CFG_ARG=""
62
+ if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then
63
+ CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}"
64
+ elif [ -f "${CONFIG_PATH}" ]; then
65
+ CFG_ARG="--config ${CONFIG_PATH}"
66
+ fi
67
+
68
+ EXTRA_ARGS=""
69
+ [ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run"
70
+
71
+ echo "Running: python3 -m itrialspace.mask_inserter run ..."
72
+ echo " manifest: ${MANIFEST_PATH}"
73
+ echo " output: ${OUT_DIR}"
74
+
75
+ python3 -m itrialspace.mask_inserter run \
76
+ --manifest "${MANIFEST_PATH}" \
77
+ --output-dir "${OUT_DIR}" \
78
+ ${CFG_ARG} \
79
+ --trial-name "${TRIAL_MODE}" \
80
+ --seed ${SEED} \
81
+ --n-jobs ${N_JOBS} \
82
+ ${EXTRA_ARGS}
83
+ EXIT_CODE=$?
84
+ echo "Finished: $(date) Exit: ${EXIT_CODE}"
85
+ exit ${EXIT_CODE}
itrialspace/infra/slurm/mask_inserter/mode11_insert_masks_array.sub ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # ──────────────────────────────────────────────────────────────────────────────
3
+ # Mode 11: Digital Twin Isolation β€” Array Job (one per manifest chunk)
4
+ #
5
+ # When all_patients=True the isolation manifest can be large (one row per
6
+ # nodule per patient). Use the list_manifests tool to split into chunks,
7
+ # then submit an array job so each chunk runs on a separate SLURM task.
8
+ #
9
+ # Usage:
10
+ # python itrialspace_mask_inserter/tools/list_manifests.py \
11
+ # --dir /scratch/.../manifests/mode11_digital_twin_isolation \
12
+ # --output manifests_mode11.txt
13
+ # sbatch --array=0-$(( $(wc -l < manifests_mode11.txt) - 1 )) \
14
+ # mode11_insert_masks_array.sub
15
+ # ──────────────────────────────────────────────────────────────────────────────
16
+
17
+ #SBATCH --job-name=ins_M11_arr
18
+ #SBATCH --partition=defq
19
+ #SBATCH --ntasks=1
20
+ #SBATCH --gpus=0
21
+ #SBATCH --cpus-per-task=8
22
+ #SBATCH --mem=32G
23
+ #SBATCH --time=2-00:00:00
24
+ #SBATCH --output=logs/insert_mode11_digital_twin_isolation_%A_%a.out
25
+ #SBATCH --error=logs/insert_mode11_digital_twin_isolation_%A_%a.err
26
+
27
+ # ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) β€” before any var use ──
28
+ 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"
29
+ itrialspace_activate_conda
30
+
31
+
32
+ set -euo pipefail
33
+
34
+ BASE_DIR="${ITRIALSPACE_DATA_DIR}"
35
+ OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks"
36
+ PROJECT_DIR="${PROJ_DIR}"
37
+
38
+ TRIAL_MODE="mode11_digital_twin_isolation"
39
+ MANIFEST_LIST="${MANIFEST_LIST:-${PROJECT_DIR}/itrialspace_mask_inserter/slurm_trials/manifests_mode11.txt}"
40
+ CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}"
41
+ N_JOBS="${N_JOBS:-8}"
42
+ DRY_RUN="${DRY_RUN:-false}"
43
+ SEED="${SEED:-42}"
44
+
45
+ if [ ! -f "${MANIFEST_LIST}" ]; then
46
+ echo "FATAL: Manifest list not found: ${MANIFEST_LIST}"
47
+ exit 1
48
+ fi
49
+
50
+ TASK_ID="${SLURM_ARRAY_TASK_ID:-0}"
51
+ MANIFEST_PATH=$(sed -n "$((TASK_ID + 1))p" "${MANIFEST_LIST}")
52
+
53
+ if [ -z "${MANIFEST_PATH}" ]; then
54
+ echo "FATAL: No manifest at index ${TASK_ID} in ${MANIFEST_LIST}"
55
+ exit 1
56
+ fi
57
+
58
+ MANIFEST_BASENAME="$(basename "${MANIFEST_PATH}" .csv)"
59
+ MANIFEST_BASENAME="$(basename "${MANIFEST_BASENAME}" .json)"
60
+ OUT_DIR="${OUTPUT_ROOT}/${TRIAL_MODE}/${MANIFEST_BASENAME}"
61
+
62
+ echo "=================================================================="
63
+ echo " iTrialSpace Mask Insertion β€” Mode 11: Digital Twin Isolation (Array)"
64
+ echo " Job ID: ${SLURM_JOB_ID:-local} Array Task: ${TASK_ID}"
65
+ echo " Node: $(hostname) Date: $(date)"
66
+ echo "=================================================================="
67
+ echo " MANIFEST_PATH : ${MANIFEST_PATH}"
68
+ echo " OUT_DIR : ${OUT_DIR}"
69
+ echo ""
70
+
71
+ cd "${PROJECT_DIR}"
72
+
73
+ if [ ! -f "${MANIFEST_PATH}" ]; then
74
+ echo "FATAL: Manifest not found: ${MANIFEST_PATH}"
75
+ exit 1
76
+ fi
77
+ mkdir -p "${OUT_DIR}"
78
+
79
+ CFG_ARG=""
80
+ if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then
81
+ CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}"
82
+ elif [ -f "${CONFIG_PATH}" ]; then
83
+ CFG_ARG="--config ${CONFIG_PATH}"
84
+ fi
85
+
86
+ EXTRA_ARGS=""
87
+ [ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run"
88
+
89
+ echo "Running: python3 -m itrialspace.mask_inserter run ..."
90
+ echo " manifest: ${MANIFEST_PATH}"
91
+ echo " output: ${OUT_DIR}"
92
+
93
+ python3 -m itrialspace.mask_inserter run \
94
+ --manifest "${MANIFEST_PATH}" \
95
+ --output-dir "${OUT_DIR}" \
96
+ ${CFG_ARG} \
97
+ --trial-name "${TRIAL_MODE}_${MANIFEST_BASENAME}" \
98
+ --seed ${SEED} \
99
+ --n-jobs ${N_JOBS} \
100
+ ${EXTRA_ARGS}
101
+ EXIT_CODE=$?
102
+ echo "Finished: $(date) Exit: ${EXIT_CODE}"
103
+ exit ${EXIT_CODE}
itrialspace/infra/slurm/mask_inserter/mode12_insert_masks.sub ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # ──────────────────────────────────────────────────────────────────────────────
3
+ # Mode 12: Digital Twin Complete β€” Mask Insertion
4
+ #
5
+ # Inserts ALL native nodule masks per patient into one combined conditioning
6
+ # mask. Each case has multiple manifest rows sharing a case_id; the inserter
7
+ # processes them sequentially and merges with label value 23.
8
+ #
9
+ # Usage:
10
+ # MANIFEST_PATH=.../digital_twin_complete_DLCS24.csv sbatch mode12_insert_masks.sub
11
+ # ──────────────────────────────────────────────────────────────────────────────
12
+
13
+ #SBATCH --job-name=ins_M12_DTcomp
14
+ #SBATCH --partition=defq
15
+ #SBATCH --ntasks=1
16
+ #SBATCH --gpus=0
17
+ #SBATCH --cpus-per-task=8
18
+ #SBATCH --mem=32G
19
+ #SBATCH --time=2-00:00:00
20
+ #SBATCH --output=logs/insert_mode12_digital_twin_complete_%j.out
21
+ #SBATCH --error=logs/insert_mode12_digital_twin_complete_%j.err
22
+
23
+ # ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) β€” before any var use ──
24
+ 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"
25
+ itrialspace_activate_conda
26
+
27
+
28
+ set -euo pipefail
29
+
30
+ BASE_DIR="${ITRIALSPACE_DATA_DIR}"
31
+ MANIFEST_ROOT="${ITRIALSPACE_OUTPUT_DIR}/manifests"
32
+ OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks"
33
+ PROJECT_DIR="${PROJ_DIR}"
34
+
35
+ TRIAL_MODE="mode12_digital_twin_complete"
36
+ MANIFEST_PATH="${MANIFEST_PATH:-${MANIFEST_ROOT}/${TRIAL_MODE}/digital_twin_complete_DLCS24.csv}"
37
+ OUT_DIR="${OUT_DIR:-${OUTPUT_ROOT}/${TRIAL_MODE}}"
38
+ CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}"
39
+ N_JOBS="${N_JOBS:-8}"
40
+ DRY_RUN="${DRY_RUN:-false}"
41
+ SEED="${SEED:-42}"
42
+
43
+ echo "=================================================================="
44
+ echo " iTrialSpace Mask Insertion β€” Mode 12: Digital Twin Complete"
45
+ echo " Job ID: ${SLURM_JOB_ID:-local} Node: $(hostname) Date: $(date)"
46
+ echo "=================================================================="
47
+ echo " MANIFEST_PATH : ${MANIFEST_PATH}"
48
+ echo " OUT_DIR : ${OUT_DIR}"
49
+ echo " N_JOBS : ${N_JOBS}"
50
+ echo ""
51
+
52
+ cd "${PROJECT_DIR}"
53
+
54
+ if [ ! -f "${MANIFEST_PATH}" ]; then
55
+ echo "FATAL: Manifest not found: ${MANIFEST_PATH}"
56
+ exit 1
57
+ fi
58
+ mkdir -p "${OUT_DIR}"
59
+
60
+ CFG_ARG=""
61
+ if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then
62
+ CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}"
63
+ elif [ -f "${CONFIG_PATH}" ]; then
64
+ CFG_ARG="--config ${CONFIG_PATH}"
65
+ fi
66
+
67
+ EXTRA_ARGS=""
68
+ [ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run"
69
+
70
+ echo "Running: python3 -m itrialspace.mask_inserter run ..."
71
+ echo " manifest: ${MANIFEST_PATH}"
72
+ echo " output: ${OUT_DIR}"
73
+
74
+ python3 -m itrialspace.mask_inserter run \
75
+ --manifest "${MANIFEST_PATH}" \
76
+ --output-dir "${OUT_DIR}" \
77
+ ${CFG_ARG} \
78
+ --trial-name "${TRIAL_MODE}" \
79
+ --seed ${SEED} \
80
+ --n-jobs ${N_JOBS} \
81
+ ${EXTRA_ARGS}
82
+ EXIT_CODE=$?
83
+ echo "Finished: $(date) Exit: ${EXIT_CODE}"
84
+ exit ${EXIT_CODE}
itrialspace/infra/slurm/mask_inserter/mode12_insert_masks_array.sub ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # ──────────────────────────────────────────────────────────────────────────────
3
+ # Mode 12: Digital Twin Complete β€” Array Job (one per manifest chunk)
4
+ #
5
+ # When all_patients=True the complete manifest can be large.
6
+ # Use the list_manifests tool to split into chunks, then submit an array job.
7
+ #
8
+ # Usage:
9
+ # python itrialspace_mask_inserter/tools/list_manifests.py \
10
+ # --dir /scratch/.../manifests/mode12_digital_twin_complete \
11
+ # --output manifests_mode12.txt
12
+ # sbatch --array=0-$(( $(wc -l < manifests_mode12.txt) - 1 )) \
13
+ # mode12_insert_masks_array.sub
14
+ # ──────────────────────────────────────────────────────────────────────────────
15
+
16
+ #SBATCH --job-name=ins_M12_arr
17
+ #SBATCH --partition=defq
18
+ #SBATCH --ntasks=1
19
+ #SBATCH --gpus=0
20
+ #SBATCH --cpus-per-task=8
21
+ #SBATCH --mem=32G
22
+ #SBATCH --time=2-00:00:00
23
+ #SBATCH --output=logs/insert_mode12_digital_twin_complete_%A_%a.out
24
+ #SBATCH --error=logs/insert_mode12_digital_twin_complete_%A_%a.err
25
+
26
+ # ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) β€” before any var use ──
27
+ 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"
28
+ itrialspace_activate_conda
29
+
30
+
31
+ set -euo pipefail
32
+
33
+ BASE_DIR="${ITRIALSPACE_DATA_DIR}"
34
+ OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks"
35
+ PROJECT_DIR="${PROJ_DIR}"
36
+
37
+ TRIAL_MODE="mode12_digital_twin_complete"
38
+ MANIFEST_LIST="${MANIFEST_LIST:-${PROJECT_DIR}/itrialspace_mask_inserter/slurm_trials/manifests_mode12.txt}"
39
+ CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}"
40
+ N_JOBS="${N_JOBS:-8}"
41
+ DRY_RUN="${DRY_RUN:-false}"
42
+ SEED="${SEED:-42}"
43
+
44
+ if [ ! -f "${MANIFEST_LIST}" ]; then
45
+ echo "FATAL: Manifest list not found: ${MANIFEST_LIST}"
46
+ exit 1
47
+ fi
48
+
49
+ TASK_ID="${SLURM_ARRAY_TASK_ID:-0}"
50
+ MANIFEST_PATH=$(sed -n "$((TASK_ID + 1))p" "${MANIFEST_LIST}")
51
+
52
+ if [ -z "${MANIFEST_PATH}" ]; then
53
+ echo "FATAL: No manifest at index ${TASK_ID} in ${MANIFEST_LIST}"
54
+ exit 1
55
+ fi
56
+
57
+ MANIFEST_BASENAME="$(basename "${MANIFEST_PATH}" .csv)"
58
+ MANIFEST_BASENAME="$(basename "${MANIFEST_BASENAME}" .json)"
59
+ OUT_DIR="${OUTPUT_ROOT}/${TRIAL_MODE}/${MANIFEST_BASENAME}"
60
+
61
+ echo "=================================================================="
62
+ echo " iTrialSpace Mask Insertion β€” Mode 12: Digital Twin Complete (Array)"
63
+ echo " Job ID: ${SLURM_JOB_ID:-local} Array Task: ${TASK_ID}"
64
+ echo " Node: $(hostname) Date: $(date)"
65
+ echo "=================================================================="
66
+ echo " MANIFEST_PATH : ${MANIFEST_PATH}"
67
+ echo " OUT_DIR : ${OUT_DIR}"
68
+ echo ""
69
+
70
+ cd "${PROJECT_DIR}"
71
+
72
+ if [ ! -f "${MANIFEST_PATH}" ]; then
73
+ echo "FATAL: Manifest not found: ${MANIFEST_PATH}"
74
+ exit 1
75
+ fi
76
+ mkdir -p "${OUT_DIR}"
77
+
78
+ CFG_ARG=""
79
+ if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then
80
+ CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}"
81
+ elif [ -f "${CONFIG_PATH}" ]; then
82
+ CFG_ARG="--config ${CONFIG_PATH}"
83
+ fi
84
+
85
+ EXTRA_ARGS=""
86
+ [ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run"
87
+
88
+ echo "Running: python3 -m itrialspace.mask_inserter run ..."
89
+ echo " manifest: ${MANIFEST_PATH}"
90
+ echo " output: ${OUT_DIR}"
91
+
92
+ python3 -m itrialspace.mask_inserter run \
93
+ --manifest "${MANIFEST_PATH}" \
94
+ --output-dir "${OUT_DIR}" \
95
+ ${CFG_ARG} \
96
+ --trial-name "${TRIAL_MODE}_${MANIFEST_BASENAME}" \
97
+ --seed ${SEED} \
98
+ --n-jobs ${N_JOBS} \
99
+ ${EXTRA_ARGS}
100
+ EXIT_CODE=$?
101
+ echo "Finished: $(date) Exit: ${EXIT_CODE}"
102
+ exit ${EXIT_CODE}
itrialspace/infra/slurm/mask_inserter/mode13_insert_masks.sub ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # ──────────────────────────────────────────────────────────────────────────────
3
+ # Mode 13: Digital Twin Cross β€” Mask Insertion
4
+ #
5
+ # Inserts donor nodule masks from a DIFFERENT patient (possibly a different
6
+ # dataset) into the host patient anatomy. The manifest contains separate
7
+ # host and donor paths; the inserter reads them directly.
8
+ #
9
+ # Usage:
10
+ # MANIFEST_PATH=.../digital_twin_cross_DLCS24_x_LUNA25.csv sbatch mode13_insert_masks.sub
11
+ # ──────────────────────────────────────────────────────────────────────────────
12
+
13
+ #SBATCH --job-name=ins_M13_DTcross
14
+ #SBATCH --partition=defq
15
+ #SBATCH --ntasks=1
16
+ #SBATCH --gpus=0
17
+ #SBATCH --cpus-per-task=8
18
+ #SBATCH --mem=32G
19
+ #SBATCH --time=2-00:00:00
20
+ #SBATCH --output=logs/insert_mode13_digital_twin_cross_%j.out
21
+ #SBATCH --error=logs/insert_mode13_digital_twin_cross_%j.err
22
+
23
+ # ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) β€” before any var use ──
24
+ 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"
25
+ itrialspace_activate_conda
26
+
27
+
28
+ set -euo pipefail
29
+
30
+ BASE_DIR="${ITRIALSPACE_DATA_DIR}"
31
+ MANIFEST_ROOT="${ITRIALSPACE_OUTPUT_DIR}/manifests"
32
+ OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks"
33
+ PROJECT_DIR="${PROJ_DIR}"
34
+
35
+ TRIAL_MODE="mode13_digital_twin_cross"
36
+ MANIFEST_PATH="${MANIFEST_PATH:-${MANIFEST_ROOT}/${TRIAL_MODE}/digital_twin_cross_DLCS24_x_LUNA25.csv}"
37
+ OUT_DIR="${OUT_DIR:-${OUTPUT_ROOT}/${TRIAL_MODE}}"
38
+ CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}"
39
+ N_JOBS="${N_JOBS:-8}"
40
+ DRY_RUN="${DRY_RUN:-false}"
41
+ SEED="${SEED:-42}"
42
+
43
+ echo "=================================================================="
44
+ echo " iTrialSpace Mask Insertion β€” Mode 13: Digital Twin Cross"
45
+ echo " Job ID: ${SLURM_JOB_ID:-local} Node: $(hostname) Date: $(date)"
46
+ echo "=================================================================="
47
+ echo " MANIFEST_PATH : ${MANIFEST_PATH}"
48
+ echo " OUT_DIR : ${OUT_DIR}"
49
+ echo " N_JOBS : ${N_JOBS}"
50
+ echo ""
51
+
52
+ cd "${PROJECT_DIR}"
53
+
54
+ if [ ! -f "${MANIFEST_PATH}" ]; then
55
+ echo "FATAL: Manifest not found: ${MANIFEST_PATH}"
56
+ exit 1
57
+ fi
58
+ mkdir -p "${OUT_DIR}"
59
+
60
+ CFG_ARG=""
61
+ if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then
62
+ CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}"
63
+ elif [ -f "${CONFIG_PATH}" ]; then
64
+ CFG_ARG="--config ${CONFIG_PATH}"
65
+ fi
66
+
67
+ EXTRA_ARGS=""
68
+ [ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run"
69
+
70
+ echo "Running: python3 -m itrialspace.mask_inserter run ..."
71
+ echo " manifest: ${MANIFEST_PATH}"
72
+ echo " output: ${OUT_DIR}"
73
+
74
+ python3 -m itrialspace.mask_inserter run \
75
+ --manifest "${MANIFEST_PATH}" \
76
+ --output-dir "${OUT_DIR}" \
77
+ ${CFG_ARG} \
78
+ --trial-name "${TRIAL_MODE}" \
79
+ --seed ${SEED} \
80
+ --n-jobs ${N_JOBS} \
81
+ ${EXTRA_ARGS}
82
+ EXIT_CODE=$?
83
+ echo "Finished: $(date) Exit: ${EXIT_CODE}"
84
+ exit ${EXIT_CODE}
itrialspace/infra/slurm/mask_inserter/mode13_insert_masks_array.sub ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # ──────────────────────────────────────────────────────────────────────────────
3
+ # Mode 13: Digital Twin Cross β€” Array Job (one per manifest chunk)
4
+ #
5
+ # Cross-patient insertion may produce many manifests (one per hostΓ—donor
6
+ # dataset combination). Use the list_manifests tool to split into chunks,
7
+ # then submit an array job.
8
+ #
9
+ # Usage:
10
+ # python itrialspace_mask_inserter/tools/list_manifests.py \
11
+ # --dir /scratch/.../manifests/mode13_digital_twin_cross \
12
+ # --output manifests_mode13.txt
13
+ # sbatch --array=0-$(( $(wc -l < manifests_mode13.txt) - 1 )) \
14
+ # mode13_insert_masks_array.sub
15
+ # ──────────────────────────────────────────────────────────────────────────────
16
+
17
+ #SBATCH --job-name=ins_M13_arr
18
+ #SBATCH --partition=defq
19
+ #SBATCH --ntasks=1
20
+ #SBATCH --gpus=0
21
+ #SBATCH --cpus-per-task=8
22
+ #SBATCH --mem=32G
23
+ #SBATCH --time=2-00:00:00
24
+ #SBATCH --output=logs/insert_mode13_digital_twin_cross_%A_%a.out
25
+ #SBATCH --error=logs/insert_mode13_digital_twin_cross_%A_%a.err
26
+
27
+ # ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) β€” before any var use ──
28
+ 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"
29
+ itrialspace_activate_conda
30
+
31
+
32
+ set -euo pipefail
33
+
34
+ BASE_DIR="${ITRIALSPACE_DATA_DIR}"
35
+ OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks"
36
+ PROJECT_DIR="${PROJ_DIR}"
37
+
38
+ TRIAL_MODE="mode13_digital_twin_cross"
39
+ MANIFEST_LIST="${MANIFEST_LIST:-${PROJECT_DIR}/itrialspace_mask_inserter/slurm_trials/manifests_mode13.txt}"
40
+ CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}"
41
+ N_JOBS="${N_JOBS:-8}"
42
+ DRY_RUN="${DRY_RUN:-false}"
43
+ SEED="${SEED:-42}"
44
+
45
+ if [ ! -f "${MANIFEST_LIST}" ]; then
46
+ echo "FATAL: Manifest list not found: ${MANIFEST_LIST}"
47
+ exit 1
48
+ fi
49
+
50
+ TASK_ID="${SLURM_ARRAY_TASK_ID:-0}"
51
+ MANIFEST_PATH=$(sed -n "$((TASK_ID + 1))p" "${MANIFEST_LIST}")
52
+
53
+ if [ -z "${MANIFEST_PATH}" ]; then
54
+ echo "FATAL: No manifest at index ${TASK_ID} in ${MANIFEST_LIST}"
55
+ exit 1
56
+ fi
57
+
58
+ MANIFEST_BASENAME="$(basename "${MANIFEST_PATH}" .csv)"
59
+ MANIFEST_BASENAME="$(basename "${MANIFEST_BASENAME}" .json)"
60
+ OUT_DIR="${OUTPUT_ROOT}/${TRIAL_MODE}/${MANIFEST_BASENAME}"
61
+
62
+ echo "=================================================================="
63
+ echo " iTrialSpace Mask Insertion β€” Mode 13: Digital Twin Cross (Array)"
64
+ echo " Job ID: ${SLURM_JOB_ID:-local} Array Task: ${TASK_ID}"
65
+ echo " Node: $(hostname) Date: $(date)"
66
+ echo "=================================================================="
67
+ echo " MANIFEST_PATH : ${MANIFEST_PATH}"
68
+ echo " OUT_DIR : ${OUT_DIR}"
69
+ echo ""
70
+
71
+ cd "${PROJECT_DIR}"
72
+
73
+ if [ ! -f "${MANIFEST_PATH}" ]; then
74
+ echo "FATAL: Manifest not found: ${MANIFEST_PATH}"
75
+ exit 1
76
+ fi
77
+ mkdir -p "${OUT_DIR}"
78
+
79
+ CFG_ARG=""
80
+ if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then
81
+ CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}"
82
+ elif [ -f "${CONFIG_PATH}" ]; then
83
+ CFG_ARG="--config ${CONFIG_PATH}"
84
+ fi
85
+
86
+ EXTRA_ARGS=""
87
+ [ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run"
88
+
89
+ echo "Running: python3 -m itrialspace.mask_inserter run ..."
90
+ echo " manifest: ${MANIFEST_PATH}"
91
+ echo " output: ${OUT_DIR}"
92
+
93
+ python3 -m itrialspace.mask_inserter run \
94
+ --manifest "${MANIFEST_PATH}" \
95
+ --output-dir "${OUT_DIR}" \
96
+ ${CFG_ARG} \
97
+ --trial-name "${TRIAL_MODE}_${MANIFEST_BASENAME}" \
98
+ --seed ${SEED} \
99
+ --n-jobs ${N_JOBS} \
100
+ ${EXTRA_ARGS}
101
+ EXIT_CODE=$?
102
+ echo "Finished: $(date) Exit: ${EXIT_CODE}"
103
+ exit ${EXIT_CODE}
itrialspace/infra/slurm/mask_inserter/mode1_insert_masks.sub ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # ──────────────────────────────────────────────────────────────────────────────
3
+ # Mode 1: Controlled Prevalence β€” Mask Insertion
4
+ #
5
+ # Inserts donor nodule masks into host CTs for the controlled-prevalence
6
+ # cohort manifest (single manifest with fixed malignancy prevalence).
7
+ #
8
+ # Usage:
9
+ # sbatch mode1_insert_masks.sub
10
+ # sbatch --mem=64G --time=08:00:00 mode1_insert_masks.sub # override
11
+ # ──────────────────────────────────────────────────────────────────────────────
12
+
13
+ #SBATCH --job-name=ins_M1_Prev
14
+ #SBATCH --partition=defq
15
+ #SBATCH --ntasks=1
16
+ #SBATCH --gpus=0
17
+ #SBATCH --cpus-per-task=8
18
+ #SBATCH --mem=32G
19
+ #SBATCH --time=08:00:00
20
+ #SBATCH --output=logs/insert_mode1_controlled_prevalence_%j.out
21
+ #SBATCH --error=logs/insert_mode1_controlled_prevalence_%j.err
22
+
23
+ # ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) β€” before any var use ──
24
+ 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"
25
+ itrialspace_activate_conda
26
+
27
+
28
+ set -euo pipefail
29
+
30
+ # ── Site-specific paths (edit these) ─────────────────────────────────────────
31
+ BASE_DIR="${ITRIALSPACE_DATA_DIR}"
32
+ MANIFEST_ROOT="${ITRIALSPACE_OUTPUT_DIR}/manifests"
33
+ OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks"
34
+ PROJECT_DIR="${PROJ_DIR}"
35
+
36
+ # ── Mode configuration ───────────────────────────────────────────────────────
37
+ TRIAL_MODE="mode1_controlled_prevalence"
38
+ MANIFEST_PATH="${MANIFEST_PATH:-${MANIFEST_ROOT}/${TRIAL_MODE}/NLST_cohort.csv}"
39
+ OUT_DIR="${OUT_DIR:-${OUTPUT_ROOT}/${TRIAL_MODE}}"
40
+ CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}"
41
+ N_JOBS="${N_JOBS:-8}"
42
+ DRY_RUN="${DRY_RUN:-false}"
43
+ SEED="${SEED:-42}"
44
+
45
+ # ── Banner ────────────────────────────────────────────────────────────────────
46
+ echo "=================================================================="
47
+ echo " iTrialSpace Mask Insertion β€” Mode 1: Controlled Prevalence"
48
+ echo " Job ID: ${SLURM_JOB_ID:-local} Node: $(hostname) Date: $(date)"
49
+ echo "=================================================================="
50
+ echo " MANIFEST_PATH : ${MANIFEST_PATH}"
51
+ echo " OUT_DIR : ${OUT_DIR}"
52
+ echo " CONFIG_PATH : ${CONFIG_PATH}"
53
+ echo " N_JOBS : ${N_JOBS}"
54
+ echo " DRY_RUN : ${DRY_RUN}"
55
+ echo ""
56
+
57
+ # ── Environment ──────────────────────────────────────────────────────────────
58
+ cd "${PROJECT_DIR}"
59
+
60
+ # ── Validate ─────────────────────────────────────────────────────────────────
61
+ if [ ! -f "${MANIFEST_PATH}" ]; then
62
+ echo "FATAL: Manifest not found: ${MANIFEST_PATH}"
63
+ exit 1
64
+ fi
65
+ mkdir -p "${OUT_DIR}"
66
+
67
+ # Resolve config path (falls back to the package's bundled defaults.yaml if unset)
68
+ CFG_ARG=""
69
+ if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then
70
+ CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}"
71
+ elif [ -f "${CONFIG_PATH}" ]; then
72
+ CFG_ARG="--config ${CONFIG_PATH}"
73
+ fi
74
+
75
+ # ── Run ──────────────────────────────────────────────────────────────────────
76
+ EXTRA_ARGS=""
77
+ [ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run"
78
+
79
+ echo "Running: python3 -m itrialspace.mask_inserter run ..."
80
+ echo " manifest: ${MANIFEST_PATH}"
81
+ echo " output: ${OUT_DIR}"
82
+
83
+ python3 -m itrialspace.mask_inserter run \
84
+ --manifest "${MANIFEST_PATH}" \
85
+ --output-dir "${OUT_DIR}" \
86
+ ${CFG_ARG} \
87
+ --trial-name "${TRIAL_MODE}" \
88
+ --seed ${SEED} \
89
+ --n-jobs ${N_JOBS} \
90
+ ${EXTRA_ARGS}
91
+ EXIT_CODE=$?
92
+
93
+ echo ""
94
+ echo "Finished: $(date) Exit: ${EXIT_CODE}"
95
+ exit ${EXIT_CODE}
itrialspace/infra/slurm/mask_inserter/mode1_insert_masks_array.sub ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # ──────────────────────────────────────────────────────────────────────────────
3
+ # Mode 1: Controlled Prevalence β€” Array Job (multiple manifests)
4
+ #
5
+ # Reads a manifest list file and processes one manifest per array task.
6
+ #
7
+ # Usage:
8
+ # # 1. Generate the manifest list:
9
+ # python itrialspace_mask_inserter/tools/list_manifests.py \
10
+ # --dir /scratch/.../manifests/mode1_controlled_prevalence \
11
+ # --output manifests_mode1.txt
12
+ #
13
+ # # 2. Submit array job (N = number of manifests - 1):
14
+ # sbatch --array=0-$(( $(wc -l < manifests_mode1.txt) - 1 )) \
15
+ # mode1_insert_masks_array.sub
16
+ # ──────────────────────────────────────────────────────────────────────────────
17
+
18
+ #SBATCH --job-name=ins_M1_arr
19
+ #SBATCH --partition=defq
20
+ #SBATCH --ntasks=1
21
+ #SBATCH --gpus=0
22
+ #SBATCH --cpus-per-task=8
23
+ #SBATCH --mem=32G
24
+ #SBATCH --time=04:00:00
25
+ #SBATCH --output=logs/insert_mode1_controlled_prevalence_%A_%a.out
26
+ #SBATCH --error=logs/insert_mode1_controlled_prevalence_%A_%a.err
27
+
28
+ # ── Load shared environment (PROJ_DIR, ITRIALSPACE_*, conda) β€” before any var use ──
29
+ 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"
30
+ itrialspace_activate_conda
31
+
32
+
33
+ set -euo pipefail
34
+
35
+ # ── Site-specific paths ──────────────────────────────────────────────────────
36
+ BASE_DIR="${ITRIALSPACE_DATA_DIR}"
37
+ OUTPUT_ROOT="${ITRIALSPACE_OUTPUT_DIR}/inserted_masks"
38
+ PROJECT_DIR="${PROJ_DIR}"
39
+
40
+ TRIAL_MODE="mode1_controlled_prevalence"
41
+ MANIFEST_LIST="${MANIFEST_LIST:-${PROJECT_DIR}/itrialspace_mask_inserter/slurm_trials/manifests_mode1.txt}"
42
+ CONFIG_PATH="${CONFIG_PATH:-config/defaults.yaml}"
43
+ N_JOBS="${N_JOBS:-8}"
44
+ DRY_RUN="${DRY_RUN:-false}"
45
+ SEED="${SEED:-42}"
46
+
47
+ # ── Resolve manifest for this array task ─────────────────────────────────────
48
+ if [ ! -f "${MANIFEST_LIST}" ]; then
49
+ echo "FATAL: Manifest list not found: ${MANIFEST_LIST}"
50
+ exit 1
51
+ fi
52
+
53
+ TASK_ID="${SLURM_ARRAY_TASK_ID:-0}"
54
+ MANIFEST_PATH=$(sed -n "$((TASK_ID + 1))p" "${MANIFEST_LIST}")
55
+
56
+ if [ -z "${MANIFEST_PATH}" ]; then
57
+ echo "FATAL: No manifest at index ${TASK_ID} in ${MANIFEST_LIST}"
58
+ exit 1
59
+ fi
60
+
61
+ # Derive a unique output subdirectory from the manifest filename
62
+ MANIFEST_BASENAME="$(basename "${MANIFEST_PATH}" .csv)"
63
+ MANIFEST_BASENAME="$(basename "${MANIFEST_BASENAME}" .json)"
64
+ OUT_DIR="${OUTPUT_ROOT}/${TRIAL_MODE}/${MANIFEST_BASENAME}"
65
+
66
+ echo "=================================================================="
67
+ echo " iTrialSpace Mask Insertion β€” Mode 1: Controlled Prevalence (Array)"
68
+ echo " Job ID: ${SLURM_JOB_ID:-local} Array Task: ${TASK_ID}"
69
+ echo " Node: $(hostname) Date: $(date)"
70
+ echo "=================================================================="
71
+ echo " MANIFEST_PATH : ${MANIFEST_PATH}"
72
+ echo " OUT_DIR : ${OUT_DIR}"
73
+ echo " N_JOBS : ${N_JOBS}"
74
+ echo ""
75
+
76
+ cd "${PROJECT_DIR}"
77
+
78
+ if [ ! -f "${MANIFEST_PATH}" ]; then
79
+ echo "FATAL: Manifest not found: ${MANIFEST_PATH}"
80
+ exit 1
81
+ fi
82
+ mkdir -p "${OUT_DIR}"
83
+
84
+ CFG_ARG=""
85
+ if [ -f "src/itrialspace/mask_inserter/${CONFIG_PATH}" ]; then
86
+ CFG_ARG="--config src/itrialspace/mask_inserter/${CONFIG_PATH}"
87
+ elif [ -f "${CONFIG_PATH}" ]; then
88
+ CFG_ARG="--config ${CONFIG_PATH}"
89
+ fi
90
+
91
+ EXTRA_ARGS=""
92
+ [ "${DRY_RUN}" = "true" ] && EXTRA_ARGS="--dry-run"
93
+
94
+ echo "Running: python3 -m itrialspace.mask_inserter run ..."
95
+ echo " manifest: ${MANIFEST_PATH}"
96
+ echo " output: ${OUT_DIR}"
97
+
98
+ python3 -m itrialspace.mask_inserter run \
99
+ --manifest "${MANIFEST_PATH}" \
100
+ --output-dir "${OUT_DIR}" \
101
+ ${CFG_ARG} \
102
+ --trial-name "${TRIAL_MODE}_${MANIFEST_BASENAME}" \
103
+ --seed ${SEED} \
104
+ --n-jobs ${N_JOBS} \
105
+ ${EXTRA_ARGS}
106
+ EXIT_CODE=$?
107
+ echo "Finished: $(date) Exit: ${EXIT_CODE}"
108
+ exit ${EXIT_CODE}